aframe-master.js 2.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AFRAME = f()}})(function(){var define,module,exports;return (function(){function 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){
  2. var str = Object.prototype.toString
  3. module.exports = anArray
  4. function anArray(arr) {
  5. return (
  6. arr.BYTES_PER_ELEMENT
  7. && str.call(arr.buffer) === '[object ArrayBuffer]'
  8. || Array.isArray(arr)
  9. )
  10. }
  11. },{}],2:[function(_dereq_,module,exports){
  12. (function (global){
  13. /*
  14. 2017 Julian Garnier
  15. Released under the MIT license
  16. */
  17. var $jscomp={scope:{}};$jscomp.defineProperty="function"==typeof Object.defineProperties?Object.defineProperty:function(e,r,p){if(p.get||p.set)throw new TypeError("ES3 does not support getters and setters.");e!=Array.prototype&&e!=Object.prototype&&(e[r]=p.value)};$jscomp.getGlobal=function(e){return"undefined"!=typeof window&&window===e?e:"undefined"!=typeof global&&null!=global?global:e};$jscomp.global=$jscomp.getGlobal(this);$jscomp.SYMBOL_PREFIX="jscomp_symbol_";
  18. $jscomp.initSymbol=function(){$jscomp.initSymbol=function(){};$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)};$jscomp.symbolCounter_=0;$jscomp.Symbol=function(e){return $jscomp.SYMBOL_PREFIX+(e||"")+$jscomp.symbolCounter_++};
  19. $jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var e=$jscomp.global.Symbol.iterator;e||(e=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator"));"function"!=typeof Array.prototype[e]&&$jscomp.defineProperty(Array.prototype,e,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}});$jscomp.initSymbolIterator=function(){}};$jscomp.arrayIterator=function(e){var r=0;return $jscomp.iteratorPrototype(function(){return r<e.length?{done:!1,value:e[r++]}:{done:!0}})};
  20. $jscomp.iteratorPrototype=function(e){$jscomp.initSymbolIterator();e={next:e};e[$jscomp.global.Symbol.iterator]=function(){return this};return e};$jscomp.array=$jscomp.array||{};$jscomp.iteratorFromArray=function(e,r){$jscomp.initSymbolIterator();e instanceof String&&(e+="");var p=0,m={next:function(){if(p<e.length){var u=p++;return{value:r(u,e[u]),done:!1}}m.next=function(){return{done:!0,value:void 0}};return m.next()}};m[Symbol.iterator]=function(){return m};return m};
  21. $jscomp.polyfill=function(e,r,p,m){if(r){p=$jscomp.global;e=e.split(".");for(m=0;m<e.length-1;m++){var u=e[m];u in p||(p[u]={});p=p[u]}e=e[e.length-1];m=p[e];r=r(m);r!=m&&null!=r&&$jscomp.defineProperty(p,e,{configurable:!0,writable:!0,value:r})}};$jscomp.polyfill("Array.prototype.keys",function(e){return e?e:function(){return $jscomp.iteratorFromArray(this,function(e){return e})}},"es6-impl","es3");var $jscomp$this=this;
  22. (function(e,r){"function"===typeof define&&define.amd?define([],r):"object"===typeof module&&module.exports?module.exports=r():e.anime=r()})(this,function(){function e(a){if(!h.col(a))try{return document.querySelectorAll(a)}catch(c){}}function r(a,c){for(var d=a.length,b=2<=arguments.length?arguments[1]:void 0,f=[],n=0;n<d;n++)if(n in a){var k=a[n];c.call(b,k,n,a)&&f.push(k)}return f}function p(a){return a.reduce(function(a,d){return a.concat(h.arr(d)?p(d):d)},[])}function m(a){if(h.arr(a))return a;
  23. h.str(a)&&(a=e(a)||a);return a instanceof NodeList||a instanceof HTMLCollection?[].slice.call(a):[a]}function u(a,c){return a.some(function(a){return a===c})}function C(a){var c={},d;for(d in a)c[d]=a[d];return c}function D(a,c){var d=C(a),b;for(b in a)d[b]=c.hasOwnProperty(b)?c[b]:a[b];return d}function z(a,c){var d=C(a),b;for(b in c)d[b]=h.und(a[b])?c[b]:a[b];return d}function T(a){a=a.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,function(a,c,d,k){return c+c+d+d+k+k});var c=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(a);
  24. a=parseInt(c[1],16);var d=parseInt(c[2],16),c=parseInt(c[3],16);return"rgba("+a+","+d+","+c+",1)"}function U(a){function c(a,c,b){0>b&&(b+=1);1<b&&--b;return b<1/6?a+6*(c-a)*b:.5>b?c:b<2/3?a+(c-a)*(2/3-b)*6:a}var d=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(a)||/hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g.exec(a);a=parseInt(d[1])/360;var b=parseInt(d[2])/100,f=parseInt(d[3])/100,d=d[4]||1;if(0==b)f=b=a=f;else{var n=.5>f?f*(1+b):f+b-f*b,k=2*f-n,f=c(k,n,a+1/3),b=c(k,n,a);a=c(k,n,a-1/3)}return"rgba("+
  25. 255*f+","+255*b+","+255*a+","+d+")"}function y(a){if(a=/([\+\-]?[0-9#\.]+)(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(a))return a[2]}function V(a){if(-1<a.indexOf("translate")||"perspective"===a)return"px";if(-1<a.indexOf("rotate")||-1<a.indexOf("skew"))return"deg"}function I(a,c){return h.fnc(a)?a(c.target,c.id,c.total):a}function E(a,c){if(c in a.style)return getComputedStyle(a).getPropertyValue(c.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase())||"0"}function J(a,c){if(h.dom(a)&&
  26. u(W,c))return"transform";if(h.dom(a)&&(a.getAttribute(c)||h.svg(a)&&a[c]))return"attribute";if(h.dom(a)&&"transform"!==c&&E(a,c))return"css";if(null!=a[c])return"object"}function X(a,c){var d=V(c),d=-1<c.indexOf("scale")?1:0+d;a=a.style.transform;if(!a)return d;for(var b=[],f=[],n=[],k=/(\w+)\((.+?)\)/g;b=k.exec(a);)f.push(b[1]),n.push(b[2]);a=r(n,function(a,b){return f[b]===c});return a.length?a[0]:d}function K(a,c){switch(J(a,c)){case "transform":return X(a,c);case "css":return E(a,c);case "attribute":return a.getAttribute(c)}return a[c]||
  27. 0}function L(a,c){var d=/^(\*=|\+=|-=)/.exec(a);if(!d)return a;var b=y(a)||0;c=parseFloat(c);a=parseFloat(a.replace(d[0],""));switch(d[0][0]){case "+":return c+a+b;case "-":return c-a+b;case "*":return c*a+b}}function F(a,c){return Math.sqrt(Math.pow(c.x-a.x,2)+Math.pow(c.y-a.y,2))}function M(a){a=a.points;for(var c=0,d,b=0;b<a.numberOfItems;b++){var f=a.getItem(b);0<b&&(c+=F(d,f));d=f}return c}function N(a){if(a.getTotalLength)return a.getTotalLength();switch(a.tagName.toLowerCase()){case "circle":return 2*
  28. Math.PI*a.getAttribute("r");case "rect":return 2*a.getAttribute("width")+2*a.getAttribute("height");case "line":return F({x:a.getAttribute("x1"),y:a.getAttribute("y1")},{x:a.getAttribute("x2"),y:a.getAttribute("y2")});case "polyline":return M(a);case "polygon":var c=a.points;return M(a)+F(c.getItem(c.numberOfItems-1),c.getItem(0))}}function Y(a,c){function d(b){b=void 0===b?0:b;return a.el.getPointAtLength(1<=c+b?c+b:0)}var b=d(),f=d(-1),n=d(1);switch(a.property){case "x":return b.x;case "y":return b.y;
  29. case "angle":return 180*Math.atan2(n.y-f.y,n.x-f.x)/Math.PI}}function O(a,c){var d=/-?\d*\.?\d+/g,b;b=h.pth(a)?a.totalLength:a;if(h.col(b))if(h.rgb(b)){var f=/rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g.exec(b);b=f?"rgba("+f[1]+",1)":b}else b=h.hex(b)?T(b):h.hsl(b)?U(b):void 0;else f=(f=y(b))?b.substr(0,b.length-f.length):b,b=c&&!/\s/g.test(b)?f+c:f;b+="";return{original:b,numbers:b.match(d)?b.match(d).map(Number):[0],strings:h.str(a)||c?b.split(d):[]}}function P(a){a=a?p(h.arr(a)?a.map(m):m(a)):[];return r(a,
  30. function(a,d,b){return b.indexOf(a)===d})}function Z(a){var c=P(a);return c.map(function(a,b){return{target:a,id:b,total:c.length}})}function aa(a,c){var d=C(c);if(h.arr(a)){var b=a.length;2!==b||h.obj(a[0])?h.fnc(c.duration)||(d.duration=c.duration/b):a={value:a}}return m(a).map(function(a,b){b=b?0:c.delay;a=h.obj(a)&&!h.pth(a)?a:{value:a};h.und(a.delay)&&(a.delay=b);return a}).map(function(a){return z(a,d)})}function ba(a,c){var d={},b;for(b in a){var f=I(a[b],c);h.arr(f)&&(f=f.map(function(a){return I(a,
  31. c)}),1===f.length&&(f=f[0]));d[b]=f}d.duration=parseFloat(d.duration);d.delay=parseFloat(d.delay);return d}function ca(a){return h.arr(a)?A.apply(this,a):Q[a]}function da(a,c){var d;return a.tweens.map(function(b){b=ba(b,c);var f=b.value,e=K(c.target,a.name),k=d?d.to.original:e,k=h.arr(f)?f[0]:k,w=L(h.arr(f)?f[1]:f,k),e=y(w)||y(k)||y(e);b.from=O(k,e);b.to=O(w,e);b.start=d?d.end:a.offset;b.end=b.start+b.delay+b.duration;b.easing=ca(b.easing);b.elasticity=(1E3-Math.min(Math.max(b.elasticity,1),999))/
  32. 1E3;b.isPath=h.pth(f);b.isColor=h.col(b.from.original);b.isColor&&(b.round=1);return d=b})}function ea(a,c){return r(p(a.map(function(a){return c.map(function(b){var c=J(a.target,b.name);if(c){var d=da(b,a);b={type:c,property:b.name,animatable:a,tweens:d,duration:d[d.length-1].end,delay:d[0].delay}}else b=void 0;return b})})),function(a){return!h.und(a)})}function R(a,c,d,b){var f="delay"===a;return c.length?(f?Math.min:Math.max).apply(Math,c.map(function(b){return b[a]})):f?b.delay:d.offset+b.delay+
  33. b.duration}function fa(a){var c=D(ga,a),d=D(S,a),b=Z(a.targets),f=[],e=z(c,d),k;for(k in a)e.hasOwnProperty(k)||"targets"===k||f.push({name:k,offset:e.offset,tweens:aa(a[k],d)});a=ea(b,f);return z(c,{children:[],animatables:b,animations:a,duration:R("duration",a,c,d),delay:R("delay",a,c,d)})}function q(a){function c(){return window.Promise&&new Promise(function(a){return p=a})}function d(a){return g.reversed?g.duration-a:a}function b(a){for(var b=0,c={},d=g.animations,f=d.length;b<f;){var e=d[b],
  34. k=e.animatable,h=e.tweens,n=h.length-1,l=h[n];n&&(l=r(h,function(b){return a<b.end})[0]||l);for(var h=Math.min(Math.max(a-l.start-l.delay,0),l.duration)/l.duration,w=isNaN(h)?1:l.easing(h,l.elasticity),h=l.to.strings,p=l.round,n=[],m=void 0,m=l.to.numbers.length,t=0;t<m;t++){var x=void 0,x=l.to.numbers[t],q=l.from.numbers[t],x=l.isPath?Y(l.value,w*x):q+w*(x-q);p&&(l.isColor&&2<t||(x=Math.round(x*p)/p));n.push(x)}if(l=h.length)for(m=h[0],w=0;w<l;w++)p=h[w+1],t=n[w],isNaN(t)||(m=p?m+(t+p):m+(t+" "));
  35. else m=n[0];ha[e.type](k.target,e.property,m,c,k.id);e.currentValue=m;b++}if(b=Object.keys(c).length)for(d=0;d<b;d++)H||(H=E(document.body,"transform")?"transform":"-webkit-transform"),g.animatables[d].target.style[H]=c[d].join(" ");g.currentTime=a;g.progress=a/g.duration*100}function f(a){if(g[a])g[a](g)}function e(){g.remaining&&!0!==g.remaining&&g.remaining--}function k(a){var k=g.duration,n=g.offset,w=n+g.delay,r=g.currentTime,x=g.reversed,q=d(a);if(g.children.length){var u=g.children,v=u.length;
  36. if(q>=g.currentTime)for(var G=0;G<v;G++)u[G].seek(q);else for(;v--;)u[v].seek(q)}if(q>=w||!k)g.began||(g.began=!0,f("begin")),f("run");if(q>n&&q<k)b(q);else if(q<=n&&0!==r&&(b(0),x&&e()),q>=k&&r!==k||!k)b(k),x||e();f("update");a>=k&&(g.remaining?(t=h,"alternate"===g.direction&&(g.reversed=!g.reversed)):(g.pause(),g.completed||(g.completed=!0,f("complete"),"Promise"in window&&(p(),m=c()))),l=0)}a=void 0===a?{}:a;var h,t,l=0,p=null,m=c(),g=fa(a);g.reset=function(){var a=g.direction,c=g.loop;g.currentTime=
  37. 0;g.progress=0;g.paused=!0;g.began=!1;g.completed=!1;g.reversed="reverse"===a;g.remaining="alternate"===a&&1===c?2:c;b(0);for(a=g.children.length;a--;)g.children[a].reset()};g.tick=function(a){h=a;t||(t=h);k((l+h-t)*q.speed)};g.seek=function(a){k(d(a))};g.pause=function(){var a=v.indexOf(g);-1<a&&v.splice(a,1);g.paused=!0};g.play=function(){g.paused&&(g.paused=!1,t=0,l=d(g.currentTime),v.push(g),B||ia())};g.reverse=function(){g.reversed=!g.reversed;t=0;l=d(g.currentTime)};g.restart=function(){g.pause();
  38. g.reset();g.play()};g.finished=m;g.reset();g.autoplay&&g.play();return g}var ga={update:void 0,begin:void 0,run:void 0,complete:void 0,loop:1,direction:"normal",autoplay:!0,offset:0},S={duration:1E3,delay:0,easing:"easeOutElastic",elasticity:500,round:0},W="translateX translateY translateZ rotate rotateX rotateY rotateZ scale scaleX scaleY scaleZ skewX skewY perspective".split(" "),H,h={arr:function(a){return Array.isArray(a)},obj:function(a){return-1<Object.prototype.toString.call(a).indexOf("Object")},
  39. pth:function(a){return h.obj(a)&&a.hasOwnProperty("totalLength")},svg:function(a){return a instanceof SVGElement},dom:function(a){return a.nodeType||h.svg(a)},str:function(a){return"string"===typeof a},fnc:function(a){return"function"===typeof a},und:function(a){return"undefined"===typeof a},hex:function(a){return/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(a)},rgb:function(a){return/^rgb/.test(a)},hsl:function(a){return/^hsl/.test(a)},col:function(a){return h.hex(a)||h.rgb(a)||h.hsl(a)}},A=function(){function a(a,
  40. d,b){return(((1-3*b+3*d)*a+(3*b-6*d))*a+3*d)*a}return function(c,d,b,f){if(0<=c&&1>=c&&0<=b&&1>=b){var e=new Float32Array(11);if(c!==d||b!==f)for(var k=0;11>k;++k)e[k]=a(.1*k,c,b);return function(k){if(c===d&&b===f)return k;if(0===k)return 0;if(1===k)return 1;for(var h=0,l=1;10!==l&&e[l]<=k;++l)h+=.1;--l;var l=h+(k-e[l])/(e[l+1]-e[l])*.1,n=3*(1-3*b+3*c)*l*l+2*(3*b-6*c)*l+3*c;if(.001<=n){for(h=0;4>h;++h){n=3*(1-3*b+3*c)*l*l+2*(3*b-6*c)*l+3*c;if(0===n)break;var m=a(l,c,b)-k,l=l-m/n}k=l}else if(0===
  41. n)k=l;else{var l=h,h=h+.1,g=0;do m=l+(h-l)/2,n=a(m,c,b)-k,0<n?h=m:l=m;while(1e-7<Math.abs(n)&&10>++g);k=m}return a(k,d,f)}}}}(),Q=function(){function a(a,b){return 0===a||1===a?a:-Math.pow(2,10*(a-1))*Math.sin(2*(a-1-b/(2*Math.PI)*Math.asin(1))*Math.PI/b)}var c="Quad Cubic Quart Quint Sine Expo Circ Back Elastic".split(" "),d={In:[[.55,.085,.68,.53],[.55,.055,.675,.19],[.895,.03,.685,.22],[.755,.05,.855,.06],[.47,0,.745,.715],[.95,.05,.795,.035],[.6,.04,.98,.335],[.6,-.28,.735,.045],a],Out:[[.25,
  42. .46,.45,.94],[.215,.61,.355,1],[.165,.84,.44,1],[.23,1,.32,1],[.39,.575,.565,1],[.19,1,.22,1],[.075,.82,.165,1],[.175,.885,.32,1.275],function(b,c){return 1-a(1-b,c)}],InOut:[[.455,.03,.515,.955],[.645,.045,.355,1],[.77,0,.175,1],[.86,0,.07,1],[.445,.05,.55,.95],[1,0,0,1],[.785,.135,.15,.86],[.68,-.55,.265,1.55],function(b,c){return.5>b?a(2*b,c)/2:1-a(-2*b+2,c)/2}]},b={linear:A(.25,.25,.75,.75)},f={},e;for(e in d)f.type=e,d[f.type].forEach(function(a){return function(d,f){b["ease"+a.type+c[f]]=h.fnc(d)?
  43. d:A.apply($jscomp$this,d)}}(f)),f={type:f.type};return b}(),ha={css:function(a,c,d){return a.style[c]=d},attribute:function(a,c,d){return a.setAttribute(c,d)},object:function(a,c,d){return a[c]=d},transform:function(a,c,d,b,f){b[f]||(b[f]=[]);b[f].push(c+"("+d+")")}},v=[],B=0,ia=function(){function a(){B=requestAnimationFrame(c)}function c(c){var b=v.length;if(b){for(var d=0;d<b;)v[d]&&v[d].tick(c),d++;a()}else cancelAnimationFrame(B),B=0}return a}();q.version="2.2.0";q.speed=1;q.running=v;q.remove=
  44. function(a){a=P(a);for(var c=v.length;c--;)for(var d=v[c],b=d.animations,f=b.length;f--;)u(a,b[f].animatable.target)&&(b.splice(f,1),b.length||d.pause())};q.getValue=K;q.path=function(a,c){var d=h.str(a)?e(a)[0]:a,b=c||100;return function(a){return{el:d,property:a,totalLength:N(d)*(b/100)}}};q.setDashoffset=function(a){var c=N(a);a.setAttribute("stroke-dasharray",c);return c};q.bezier=A;q.easings=Q;q.timeline=function(a){var c=q(a);c.pause();c.duration=0;c.add=function(d){c.children.forEach(function(a){a.began=
  45. !0;a.completed=!0});m(d).forEach(function(b){var d=z(b,D(S,a||{}));d.targets=d.targets||a.targets;b=c.duration;var e=d.offset;d.autoplay=!1;d.direction=c.direction;d.offset=h.und(e)?b:L(e,b);c.began=!0;c.completed=!0;c.seek(d.offset);d=q(d);d.began=!0;d.completed=!0;d.duration>b&&(c.duration=d.duration);c.children.push(d)});c.seek(0);c.reset();c.autoplay&&c.restart();return c};return c};q.random=function(a,c){return Math.floor(Math.random()*(c-a+1))+a};return q});
  46. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  47. },{}],3:[function(_dereq_,module,exports){
  48. module.exports = function numtype(num, def) {
  49. return typeof num === 'number'
  50. ? num
  51. : (typeof def === 'number' ? def : 0)
  52. }
  53. },{}],4:[function(_dereq_,module,exports){
  54. 'use strict'
  55. exports.byteLength = byteLength
  56. exports.toByteArray = toByteArray
  57. exports.fromByteArray = fromByteArray
  58. var lookup = []
  59. var revLookup = []
  60. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  61. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  62. for (var i = 0, len = code.length; i < len; ++i) {
  63. lookup[i] = code[i]
  64. revLookup[code.charCodeAt(i)] = i
  65. }
  66. // Support decoding URL-safe base64 strings, as Node.js does.
  67. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  68. revLookup['-'.charCodeAt(0)] = 62
  69. revLookup['_'.charCodeAt(0)] = 63
  70. function placeHoldersCount (b64) {
  71. var len = b64.length
  72. if (len % 4 > 0) {
  73. throw new Error('Invalid string. Length must be a multiple of 4')
  74. }
  75. // the number of equal signs (place holders)
  76. // if there are two placeholders, than the two characters before it
  77. // represent one byte
  78. // if there is only one, then the three characters before it represent 2 bytes
  79. // this is just a cheap hack to not do indexOf twice
  80. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  81. }
  82. function byteLength (b64) {
  83. // base64 is 4/3 + up to two characters of the original data
  84. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  85. }
  86. function toByteArray (b64) {
  87. var i, l, tmp, placeHolders, arr
  88. var len = b64.length
  89. placeHolders = placeHoldersCount(b64)
  90. arr = new Arr((len * 3 / 4) - placeHolders)
  91. // if there are placeholders, only get up to the last complete 4 chars
  92. l = placeHolders > 0 ? len - 4 : len
  93. var L = 0
  94. for (i = 0; i < l; i += 4) {
  95. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  96. arr[L++] = (tmp >> 16) & 0xFF
  97. arr[L++] = (tmp >> 8) & 0xFF
  98. arr[L++] = tmp & 0xFF
  99. }
  100. if (placeHolders === 2) {
  101. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  102. arr[L++] = tmp & 0xFF
  103. } else if (placeHolders === 1) {
  104. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  105. arr[L++] = (tmp >> 8) & 0xFF
  106. arr[L++] = tmp & 0xFF
  107. }
  108. return arr
  109. }
  110. function tripletToBase64 (num) {
  111. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  112. }
  113. function encodeChunk (uint8, start, end) {
  114. var tmp
  115. var output = []
  116. for (var i = start; i < end; i += 3) {
  117. tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF)
  118. output.push(tripletToBase64(tmp))
  119. }
  120. return output.join('')
  121. }
  122. function fromByteArray (uint8) {
  123. var tmp
  124. var len = uint8.length
  125. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  126. var output = ''
  127. var parts = []
  128. var maxChunkLength = 16383 // must be multiple of 3
  129. // go through the array every three bytes, we'll deal with trailing stuff later
  130. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  131. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  132. }
  133. // pad the end with zeros, but make sure to not forget the extra bytes
  134. if (extraBytes === 1) {
  135. tmp = uint8[len - 1]
  136. output += lookup[tmp >> 2]
  137. output += lookup[(tmp << 4) & 0x3F]
  138. output += '=='
  139. } else if (extraBytes === 2) {
  140. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  141. output += lookup[tmp >> 10]
  142. output += lookup[(tmp >> 4) & 0x3F]
  143. output += lookup[(tmp << 2) & 0x3F]
  144. output += '='
  145. }
  146. parts.push(output)
  147. return parts.join('')
  148. }
  149. },{}],5:[function(_dereq_,module,exports){
  150. 'use strict';
  151. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  152. module.exports = {
  153. // Create a <link> tag with optional data attributes
  154. createLink: function(href, attributes) {
  155. var head = document.head || document.getElementsByTagName('head')[0];
  156. var link = document.createElement('link');
  157. link.href = href;
  158. link.rel = 'stylesheet';
  159. for (var key in attributes) {
  160. if ( ! attributes.hasOwnProperty(key)) {
  161. continue;
  162. }
  163. var value = attributes[key];
  164. link.setAttribute('data-' + key, value);
  165. }
  166. head.appendChild(link);
  167. },
  168. // Create a <style> tag with optional data attributes
  169. createStyle: function(cssText, attributes) {
  170. var head = document.head || document.getElementsByTagName('head')[0],
  171. style = document.createElement('style');
  172. style.type = 'text/css';
  173. for (var key in attributes) {
  174. if ( ! attributes.hasOwnProperty(key)) {
  175. continue;
  176. }
  177. var value = attributes[key];
  178. style.setAttribute('data-' + key, value);
  179. }
  180. if (style.sheet) { // for jsdom and IE9+
  181. style.innerHTML = cssText;
  182. style.sheet.cssText = cssText;
  183. head.appendChild(style);
  184. } else if (style.styleSheet) { // for IE8 and below
  185. head.appendChild(style);
  186. style.styleSheet.cssText = cssText;
  187. } else { // for Chrome, Firefox, and Safari
  188. style.appendChild(document.createTextNode(cssText));
  189. head.appendChild(style);
  190. }
  191. }
  192. };
  193. },{}],6:[function(_dereq_,module,exports){
  194. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  195. module.exports = function (a, b) {
  196. if (!Buffer.isBuffer(a)) return undefined;
  197. if (!Buffer.isBuffer(b)) return undefined;
  198. if (typeof a.equals === 'function') return a.equals(b);
  199. if (a.length !== b.length) return false;
  200. for (var i = 0; i < a.length; i++) {
  201. if (a[i] !== b[i]) return false;
  202. }
  203. return true;
  204. };
  205. },{"buffer":7}],7:[function(_dereq_,module,exports){
  206. (function (global){
  207. /*!
  208. * The buffer module from node.js, for the browser.
  209. *
  210. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  211. * @license MIT
  212. */
  213. /* eslint-disable no-proto */
  214. 'use strict'
  215. var base64 = _dereq_('base64-js')
  216. var ieee754 = _dereq_('ieee754')
  217. var isArray = _dereq_('isarray')
  218. exports.Buffer = Buffer
  219. exports.SlowBuffer = SlowBuffer
  220. exports.INSPECT_MAX_BYTES = 50
  221. /**
  222. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  223. * === true Use Uint8Array implementation (fastest)
  224. * === false Use Object implementation (most compatible, even IE6)
  225. *
  226. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  227. * Opera 11.6+, iOS 4.2+.
  228. *
  229. * Due to various browser bugs, sometimes the Object implementation will be used even
  230. * when the browser supports typed arrays.
  231. *
  232. * Note:
  233. *
  234. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  235. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  236. *
  237. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  238. *
  239. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  240. * incorrect length in some situations.
  241. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  242. * get the Object implementation, which is slower but behaves correctly.
  243. */
  244. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  245. ? global.TYPED_ARRAY_SUPPORT
  246. : typedArraySupport()
  247. /*
  248. * Export kMaxLength after typed array support is determined.
  249. */
  250. exports.kMaxLength = kMaxLength()
  251. function typedArraySupport () {
  252. try {
  253. var arr = new Uint8Array(1)
  254. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  255. return arr.foo() === 42 && // typed array instances can be augmented
  256. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  257. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  258. } catch (e) {
  259. return false
  260. }
  261. }
  262. function kMaxLength () {
  263. return Buffer.TYPED_ARRAY_SUPPORT
  264. ? 0x7fffffff
  265. : 0x3fffffff
  266. }
  267. function createBuffer (that, length) {
  268. if (kMaxLength() < length) {
  269. throw new RangeError('Invalid typed array length')
  270. }
  271. if (Buffer.TYPED_ARRAY_SUPPORT) {
  272. // Return an augmented `Uint8Array` instance, for best performance
  273. that = new Uint8Array(length)
  274. that.__proto__ = Buffer.prototype
  275. } else {
  276. // Fallback: Return an object instance of the Buffer class
  277. if (that === null) {
  278. that = new Buffer(length)
  279. }
  280. that.length = length
  281. }
  282. return that
  283. }
  284. /**
  285. * The Buffer constructor returns instances of `Uint8Array` that have their
  286. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  287. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  288. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  289. * returns a single octet.
  290. *
  291. * The `Uint8Array` prototype remains unmodified.
  292. */
  293. function Buffer (arg, encodingOrOffset, length) {
  294. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  295. return new Buffer(arg, encodingOrOffset, length)
  296. }
  297. // Common case.
  298. if (typeof arg === 'number') {
  299. if (typeof encodingOrOffset === 'string') {
  300. throw new Error(
  301. 'If encoding is specified then the first argument must be a string'
  302. )
  303. }
  304. return allocUnsafe(this, arg)
  305. }
  306. return from(this, arg, encodingOrOffset, length)
  307. }
  308. Buffer.poolSize = 8192 // not used by this implementation
  309. // TODO: Legacy, not needed anymore. Remove in next major version.
  310. Buffer._augment = function (arr) {
  311. arr.__proto__ = Buffer.prototype
  312. return arr
  313. }
  314. function from (that, value, encodingOrOffset, length) {
  315. if (typeof value === 'number') {
  316. throw new TypeError('"value" argument must not be a number')
  317. }
  318. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  319. return fromArrayBuffer(that, value, encodingOrOffset, length)
  320. }
  321. if (typeof value === 'string') {
  322. return fromString(that, value, encodingOrOffset)
  323. }
  324. return fromObject(that, value)
  325. }
  326. /**
  327. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  328. * if value is a number.
  329. * Buffer.from(str[, encoding])
  330. * Buffer.from(array)
  331. * Buffer.from(buffer)
  332. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  333. **/
  334. Buffer.from = function (value, encodingOrOffset, length) {
  335. return from(null, value, encodingOrOffset, length)
  336. }
  337. if (Buffer.TYPED_ARRAY_SUPPORT) {
  338. Buffer.prototype.__proto__ = Uint8Array.prototype
  339. Buffer.__proto__ = Uint8Array
  340. if (typeof Symbol !== 'undefined' && Symbol.species &&
  341. Buffer[Symbol.species] === Buffer) {
  342. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  343. Object.defineProperty(Buffer, Symbol.species, {
  344. value: null,
  345. configurable: true
  346. })
  347. }
  348. }
  349. function assertSize (size) {
  350. if (typeof size !== 'number') {
  351. throw new TypeError('"size" argument must be a number')
  352. } else if (size < 0) {
  353. throw new RangeError('"size" argument must not be negative')
  354. }
  355. }
  356. function alloc (that, size, fill, encoding) {
  357. assertSize(size)
  358. if (size <= 0) {
  359. return createBuffer(that, size)
  360. }
  361. if (fill !== undefined) {
  362. // Only pay attention to encoding if it's a string. This
  363. // prevents accidentally sending in a number that would
  364. // be interpretted as a start offset.
  365. return typeof encoding === 'string'
  366. ? createBuffer(that, size).fill(fill, encoding)
  367. : createBuffer(that, size).fill(fill)
  368. }
  369. return createBuffer(that, size)
  370. }
  371. /**
  372. * Creates a new filled Buffer instance.
  373. * alloc(size[, fill[, encoding]])
  374. **/
  375. Buffer.alloc = function (size, fill, encoding) {
  376. return alloc(null, size, fill, encoding)
  377. }
  378. function allocUnsafe (that, size) {
  379. assertSize(size)
  380. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  381. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  382. for (var i = 0; i < size; ++i) {
  383. that[i] = 0
  384. }
  385. }
  386. return that
  387. }
  388. /**
  389. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  390. * */
  391. Buffer.allocUnsafe = function (size) {
  392. return allocUnsafe(null, size)
  393. }
  394. /**
  395. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  396. */
  397. Buffer.allocUnsafeSlow = function (size) {
  398. return allocUnsafe(null, size)
  399. }
  400. function fromString (that, string, encoding) {
  401. if (typeof encoding !== 'string' || encoding === '') {
  402. encoding = 'utf8'
  403. }
  404. if (!Buffer.isEncoding(encoding)) {
  405. throw new TypeError('"encoding" must be a valid string encoding')
  406. }
  407. var length = byteLength(string, encoding) | 0
  408. that = createBuffer(that, length)
  409. var actual = that.write(string, encoding)
  410. if (actual !== length) {
  411. // Writing a hex string, for example, that contains invalid characters will
  412. // cause everything after the first invalid character to be ignored. (e.g.
  413. // 'abxxcd' will be treated as 'ab')
  414. that = that.slice(0, actual)
  415. }
  416. return that
  417. }
  418. function fromArrayLike (that, array) {
  419. var length = array.length < 0 ? 0 : checked(array.length) | 0
  420. that = createBuffer(that, length)
  421. for (var i = 0; i < length; i += 1) {
  422. that[i] = array[i] & 255
  423. }
  424. return that
  425. }
  426. function fromArrayBuffer (that, array, byteOffset, length) {
  427. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  428. if (byteOffset < 0 || array.byteLength < byteOffset) {
  429. throw new RangeError('\'offset\' is out of bounds')
  430. }
  431. if (array.byteLength < byteOffset + (length || 0)) {
  432. throw new RangeError('\'length\' is out of bounds')
  433. }
  434. if (byteOffset === undefined && length === undefined) {
  435. array = new Uint8Array(array)
  436. } else if (length === undefined) {
  437. array = new Uint8Array(array, byteOffset)
  438. } else {
  439. array = new Uint8Array(array, byteOffset, length)
  440. }
  441. if (Buffer.TYPED_ARRAY_SUPPORT) {
  442. // Return an augmented `Uint8Array` instance, for best performance
  443. that = array
  444. that.__proto__ = Buffer.prototype
  445. } else {
  446. // Fallback: Return an object instance of the Buffer class
  447. that = fromArrayLike(that, array)
  448. }
  449. return that
  450. }
  451. function fromObject (that, obj) {
  452. if (Buffer.isBuffer(obj)) {
  453. var len = checked(obj.length) | 0
  454. that = createBuffer(that, len)
  455. if (that.length === 0) {
  456. return that
  457. }
  458. obj.copy(that, 0, 0, len)
  459. return that
  460. }
  461. if (obj) {
  462. if ((typeof ArrayBuffer !== 'undefined' &&
  463. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  464. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  465. return createBuffer(that, 0)
  466. }
  467. return fromArrayLike(that, obj)
  468. }
  469. if (obj.type === 'Buffer' && isArray(obj.data)) {
  470. return fromArrayLike(that, obj.data)
  471. }
  472. }
  473. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  474. }
  475. function checked (length) {
  476. // Note: cannot use `length < kMaxLength()` here because that fails when
  477. // length is NaN (which is otherwise coerced to zero.)
  478. if (length >= kMaxLength()) {
  479. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  480. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  481. }
  482. return length | 0
  483. }
  484. function SlowBuffer (length) {
  485. if (+length != length) { // eslint-disable-line eqeqeq
  486. length = 0
  487. }
  488. return Buffer.alloc(+length)
  489. }
  490. Buffer.isBuffer = function isBuffer (b) {
  491. return !!(b != null && b._isBuffer)
  492. }
  493. Buffer.compare = function compare (a, b) {
  494. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  495. throw new TypeError('Arguments must be Buffers')
  496. }
  497. if (a === b) return 0
  498. var x = a.length
  499. var y = b.length
  500. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  501. if (a[i] !== b[i]) {
  502. x = a[i]
  503. y = b[i]
  504. break
  505. }
  506. }
  507. if (x < y) return -1
  508. if (y < x) return 1
  509. return 0
  510. }
  511. Buffer.isEncoding = function isEncoding (encoding) {
  512. switch (String(encoding).toLowerCase()) {
  513. case 'hex':
  514. case 'utf8':
  515. case 'utf-8':
  516. case 'ascii':
  517. case 'latin1':
  518. case 'binary':
  519. case 'base64':
  520. case 'ucs2':
  521. case 'ucs-2':
  522. case 'utf16le':
  523. case 'utf-16le':
  524. return true
  525. default:
  526. return false
  527. }
  528. }
  529. Buffer.concat = function concat (list, length) {
  530. if (!isArray(list)) {
  531. throw new TypeError('"list" argument must be an Array of Buffers')
  532. }
  533. if (list.length === 0) {
  534. return Buffer.alloc(0)
  535. }
  536. var i
  537. if (length === undefined) {
  538. length = 0
  539. for (i = 0; i < list.length; ++i) {
  540. length += list[i].length
  541. }
  542. }
  543. var buffer = Buffer.allocUnsafe(length)
  544. var pos = 0
  545. for (i = 0; i < list.length; ++i) {
  546. var buf = list[i]
  547. if (!Buffer.isBuffer(buf)) {
  548. throw new TypeError('"list" argument must be an Array of Buffers')
  549. }
  550. buf.copy(buffer, pos)
  551. pos += buf.length
  552. }
  553. return buffer
  554. }
  555. function byteLength (string, encoding) {
  556. if (Buffer.isBuffer(string)) {
  557. return string.length
  558. }
  559. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  560. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  561. return string.byteLength
  562. }
  563. if (typeof string !== 'string') {
  564. string = '' + string
  565. }
  566. var len = string.length
  567. if (len === 0) return 0
  568. // Use a for loop to avoid recursion
  569. var loweredCase = false
  570. for (;;) {
  571. switch (encoding) {
  572. case 'ascii':
  573. case 'latin1':
  574. case 'binary':
  575. return len
  576. case 'utf8':
  577. case 'utf-8':
  578. case undefined:
  579. return utf8ToBytes(string).length
  580. case 'ucs2':
  581. case 'ucs-2':
  582. case 'utf16le':
  583. case 'utf-16le':
  584. return len * 2
  585. case 'hex':
  586. return len >>> 1
  587. case 'base64':
  588. return base64ToBytes(string).length
  589. default:
  590. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  591. encoding = ('' + encoding).toLowerCase()
  592. loweredCase = true
  593. }
  594. }
  595. }
  596. Buffer.byteLength = byteLength
  597. function slowToString (encoding, start, end) {
  598. var loweredCase = false
  599. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  600. // property of a typed array.
  601. // This behaves neither like String nor Uint8Array in that we set start/end
  602. // to their upper/lower bounds if the value passed is out of range.
  603. // undefined is handled specially as per ECMA-262 6th Edition,
  604. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  605. if (start === undefined || start < 0) {
  606. start = 0
  607. }
  608. // Return early if start > this.length. Done here to prevent potential uint32
  609. // coercion fail below.
  610. if (start > this.length) {
  611. return ''
  612. }
  613. if (end === undefined || end > this.length) {
  614. end = this.length
  615. }
  616. if (end <= 0) {
  617. return ''
  618. }
  619. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  620. end >>>= 0
  621. start >>>= 0
  622. if (end <= start) {
  623. return ''
  624. }
  625. if (!encoding) encoding = 'utf8'
  626. while (true) {
  627. switch (encoding) {
  628. case 'hex':
  629. return hexSlice(this, start, end)
  630. case 'utf8':
  631. case 'utf-8':
  632. return utf8Slice(this, start, end)
  633. case 'ascii':
  634. return asciiSlice(this, start, end)
  635. case 'latin1':
  636. case 'binary':
  637. return latin1Slice(this, start, end)
  638. case 'base64':
  639. return base64Slice(this, start, end)
  640. case 'ucs2':
  641. case 'ucs-2':
  642. case 'utf16le':
  643. case 'utf-16le':
  644. return utf16leSlice(this, start, end)
  645. default:
  646. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  647. encoding = (encoding + '').toLowerCase()
  648. loweredCase = true
  649. }
  650. }
  651. }
  652. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  653. // Buffer instances.
  654. Buffer.prototype._isBuffer = true
  655. function swap (b, n, m) {
  656. var i = b[n]
  657. b[n] = b[m]
  658. b[m] = i
  659. }
  660. Buffer.prototype.swap16 = function swap16 () {
  661. var len = this.length
  662. if (len % 2 !== 0) {
  663. throw new RangeError('Buffer size must be a multiple of 16-bits')
  664. }
  665. for (var i = 0; i < len; i += 2) {
  666. swap(this, i, i + 1)
  667. }
  668. return this
  669. }
  670. Buffer.prototype.swap32 = function swap32 () {
  671. var len = this.length
  672. if (len % 4 !== 0) {
  673. throw new RangeError('Buffer size must be a multiple of 32-bits')
  674. }
  675. for (var i = 0; i < len; i += 4) {
  676. swap(this, i, i + 3)
  677. swap(this, i + 1, i + 2)
  678. }
  679. return this
  680. }
  681. Buffer.prototype.swap64 = function swap64 () {
  682. var len = this.length
  683. if (len % 8 !== 0) {
  684. throw new RangeError('Buffer size must be a multiple of 64-bits')
  685. }
  686. for (var i = 0; i < len; i += 8) {
  687. swap(this, i, i + 7)
  688. swap(this, i + 1, i + 6)
  689. swap(this, i + 2, i + 5)
  690. swap(this, i + 3, i + 4)
  691. }
  692. return this
  693. }
  694. Buffer.prototype.toString = function toString () {
  695. var length = this.length | 0
  696. if (length === 0) return ''
  697. if (arguments.length === 0) return utf8Slice(this, 0, length)
  698. return slowToString.apply(this, arguments)
  699. }
  700. Buffer.prototype.equals = function equals (b) {
  701. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  702. if (this === b) return true
  703. return Buffer.compare(this, b) === 0
  704. }
  705. Buffer.prototype.inspect = function inspect () {
  706. var str = ''
  707. var max = exports.INSPECT_MAX_BYTES
  708. if (this.length > 0) {
  709. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  710. if (this.length > max) str += ' ... '
  711. }
  712. return '<Buffer ' + str + '>'
  713. }
  714. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  715. if (!Buffer.isBuffer(target)) {
  716. throw new TypeError('Argument must be a Buffer')
  717. }
  718. if (start === undefined) {
  719. start = 0
  720. }
  721. if (end === undefined) {
  722. end = target ? target.length : 0
  723. }
  724. if (thisStart === undefined) {
  725. thisStart = 0
  726. }
  727. if (thisEnd === undefined) {
  728. thisEnd = this.length
  729. }
  730. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  731. throw new RangeError('out of range index')
  732. }
  733. if (thisStart >= thisEnd && start >= end) {
  734. return 0
  735. }
  736. if (thisStart >= thisEnd) {
  737. return -1
  738. }
  739. if (start >= end) {
  740. return 1
  741. }
  742. start >>>= 0
  743. end >>>= 0
  744. thisStart >>>= 0
  745. thisEnd >>>= 0
  746. if (this === target) return 0
  747. var x = thisEnd - thisStart
  748. var y = end - start
  749. var len = Math.min(x, y)
  750. var thisCopy = this.slice(thisStart, thisEnd)
  751. var targetCopy = target.slice(start, end)
  752. for (var i = 0; i < len; ++i) {
  753. if (thisCopy[i] !== targetCopy[i]) {
  754. x = thisCopy[i]
  755. y = targetCopy[i]
  756. break
  757. }
  758. }
  759. if (x < y) return -1
  760. if (y < x) return 1
  761. return 0
  762. }
  763. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  764. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  765. //
  766. // Arguments:
  767. // - buffer - a Buffer to search
  768. // - val - a string, Buffer, or number
  769. // - byteOffset - an index into `buffer`; will be clamped to an int32
  770. // - encoding - an optional encoding, relevant is val is a string
  771. // - dir - true for indexOf, false for lastIndexOf
  772. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  773. // Empty buffer means no match
  774. if (buffer.length === 0) return -1
  775. // Normalize byteOffset
  776. if (typeof byteOffset === 'string') {
  777. encoding = byteOffset
  778. byteOffset = 0
  779. } else if (byteOffset > 0x7fffffff) {
  780. byteOffset = 0x7fffffff
  781. } else if (byteOffset < -0x80000000) {
  782. byteOffset = -0x80000000
  783. }
  784. byteOffset = +byteOffset // Coerce to Number.
  785. if (isNaN(byteOffset)) {
  786. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  787. byteOffset = dir ? 0 : (buffer.length - 1)
  788. }
  789. // Normalize byteOffset: negative offsets start from the end of the buffer
  790. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  791. if (byteOffset >= buffer.length) {
  792. if (dir) return -1
  793. else byteOffset = buffer.length - 1
  794. } else if (byteOffset < 0) {
  795. if (dir) byteOffset = 0
  796. else return -1
  797. }
  798. // Normalize val
  799. if (typeof val === 'string') {
  800. val = Buffer.from(val, encoding)
  801. }
  802. // Finally, search either indexOf (if dir is true) or lastIndexOf
  803. if (Buffer.isBuffer(val)) {
  804. // Special case: looking for empty string/buffer always fails
  805. if (val.length === 0) {
  806. return -1
  807. }
  808. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  809. } else if (typeof val === 'number') {
  810. val = val & 0xFF // Search for a byte value [0-255]
  811. if (Buffer.TYPED_ARRAY_SUPPORT &&
  812. typeof Uint8Array.prototype.indexOf === 'function') {
  813. if (dir) {
  814. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  815. } else {
  816. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  817. }
  818. }
  819. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  820. }
  821. throw new TypeError('val must be string, number or Buffer')
  822. }
  823. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  824. var indexSize = 1
  825. var arrLength = arr.length
  826. var valLength = val.length
  827. if (encoding !== undefined) {
  828. encoding = String(encoding).toLowerCase()
  829. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  830. encoding === 'utf16le' || encoding === 'utf-16le') {
  831. if (arr.length < 2 || val.length < 2) {
  832. return -1
  833. }
  834. indexSize = 2
  835. arrLength /= 2
  836. valLength /= 2
  837. byteOffset /= 2
  838. }
  839. }
  840. function read (buf, i) {
  841. if (indexSize === 1) {
  842. return buf[i]
  843. } else {
  844. return buf.readUInt16BE(i * indexSize)
  845. }
  846. }
  847. var i
  848. if (dir) {
  849. var foundIndex = -1
  850. for (i = byteOffset; i < arrLength; i++) {
  851. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  852. if (foundIndex === -1) foundIndex = i
  853. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  854. } else {
  855. if (foundIndex !== -1) i -= i - foundIndex
  856. foundIndex = -1
  857. }
  858. }
  859. } else {
  860. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  861. for (i = byteOffset; i >= 0; i--) {
  862. var found = true
  863. for (var j = 0; j < valLength; j++) {
  864. if (read(arr, i + j) !== read(val, j)) {
  865. found = false
  866. break
  867. }
  868. }
  869. if (found) return i
  870. }
  871. }
  872. return -1
  873. }
  874. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  875. return this.indexOf(val, byteOffset, encoding) !== -1
  876. }
  877. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  878. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  879. }
  880. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  881. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  882. }
  883. function hexWrite (buf, string, offset, length) {
  884. offset = Number(offset) || 0
  885. var remaining = buf.length - offset
  886. if (!length) {
  887. length = remaining
  888. } else {
  889. length = Number(length)
  890. if (length > remaining) {
  891. length = remaining
  892. }
  893. }
  894. // must be an even number of digits
  895. var strLen = string.length
  896. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  897. if (length > strLen / 2) {
  898. length = strLen / 2
  899. }
  900. for (var i = 0; i < length; ++i) {
  901. var parsed = parseInt(string.substr(i * 2, 2), 16)
  902. if (isNaN(parsed)) return i
  903. buf[offset + i] = parsed
  904. }
  905. return i
  906. }
  907. function utf8Write (buf, string, offset, length) {
  908. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  909. }
  910. function asciiWrite (buf, string, offset, length) {
  911. return blitBuffer(asciiToBytes(string), buf, offset, length)
  912. }
  913. function latin1Write (buf, string, offset, length) {
  914. return asciiWrite(buf, string, offset, length)
  915. }
  916. function base64Write (buf, string, offset, length) {
  917. return blitBuffer(base64ToBytes(string), buf, offset, length)
  918. }
  919. function ucs2Write (buf, string, offset, length) {
  920. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  921. }
  922. Buffer.prototype.write = function write (string, offset, length, encoding) {
  923. // Buffer#write(string)
  924. if (offset === undefined) {
  925. encoding = 'utf8'
  926. length = this.length
  927. offset = 0
  928. // Buffer#write(string, encoding)
  929. } else if (length === undefined && typeof offset === 'string') {
  930. encoding = offset
  931. length = this.length
  932. offset = 0
  933. // Buffer#write(string, offset[, length][, encoding])
  934. } else if (isFinite(offset)) {
  935. offset = offset | 0
  936. if (isFinite(length)) {
  937. length = length | 0
  938. if (encoding === undefined) encoding = 'utf8'
  939. } else {
  940. encoding = length
  941. length = undefined
  942. }
  943. // legacy write(string, encoding, offset, length) - remove in v0.13
  944. } else {
  945. throw new Error(
  946. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  947. )
  948. }
  949. var remaining = this.length - offset
  950. if (length === undefined || length > remaining) length = remaining
  951. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  952. throw new RangeError('Attempt to write outside buffer bounds')
  953. }
  954. if (!encoding) encoding = 'utf8'
  955. var loweredCase = false
  956. for (;;) {
  957. switch (encoding) {
  958. case 'hex':
  959. return hexWrite(this, string, offset, length)
  960. case 'utf8':
  961. case 'utf-8':
  962. return utf8Write(this, string, offset, length)
  963. case 'ascii':
  964. return asciiWrite(this, string, offset, length)
  965. case 'latin1':
  966. case 'binary':
  967. return latin1Write(this, string, offset, length)
  968. case 'base64':
  969. // Warning: maxLength not taken into account in base64Write
  970. return base64Write(this, string, offset, length)
  971. case 'ucs2':
  972. case 'ucs-2':
  973. case 'utf16le':
  974. case 'utf-16le':
  975. return ucs2Write(this, string, offset, length)
  976. default:
  977. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  978. encoding = ('' + encoding).toLowerCase()
  979. loweredCase = true
  980. }
  981. }
  982. }
  983. Buffer.prototype.toJSON = function toJSON () {
  984. return {
  985. type: 'Buffer',
  986. data: Array.prototype.slice.call(this._arr || this, 0)
  987. }
  988. }
  989. function base64Slice (buf, start, end) {
  990. if (start === 0 && end === buf.length) {
  991. return base64.fromByteArray(buf)
  992. } else {
  993. return base64.fromByteArray(buf.slice(start, end))
  994. }
  995. }
  996. function utf8Slice (buf, start, end) {
  997. end = Math.min(buf.length, end)
  998. var res = []
  999. var i = start
  1000. while (i < end) {
  1001. var firstByte = buf[i]
  1002. var codePoint = null
  1003. var bytesPerSequence = (firstByte > 0xEF) ? 4
  1004. : (firstByte > 0xDF) ? 3
  1005. : (firstByte > 0xBF) ? 2
  1006. : 1
  1007. if (i + bytesPerSequence <= end) {
  1008. var secondByte, thirdByte, fourthByte, tempCodePoint
  1009. switch (bytesPerSequence) {
  1010. case 1:
  1011. if (firstByte < 0x80) {
  1012. codePoint = firstByte
  1013. }
  1014. break
  1015. case 2:
  1016. secondByte = buf[i + 1]
  1017. if ((secondByte & 0xC0) === 0x80) {
  1018. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1019. if (tempCodePoint > 0x7F) {
  1020. codePoint = tempCodePoint
  1021. }
  1022. }
  1023. break
  1024. case 3:
  1025. secondByte = buf[i + 1]
  1026. thirdByte = buf[i + 2]
  1027. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1028. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1029. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1030. codePoint = tempCodePoint
  1031. }
  1032. }
  1033. break
  1034. case 4:
  1035. secondByte = buf[i + 1]
  1036. thirdByte = buf[i + 2]
  1037. fourthByte = buf[i + 3]
  1038. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1039. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1040. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1041. codePoint = tempCodePoint
  1042. }
  1043. }
  1044. }
  1045. }
  1046. if (codePoint === null) {
  1047. // we did not generate a valid codePoint so insert a
  1048. // replacement char (U+FFFD) and advance only 1 byte
  1049. codePoint = 0xFFFD
  1050. bytesPerSequence = 1
  1051. } else if (codePoint > 0xFFFF) {
  1052. // encode to utf16 (surrogate pair dance)
  1053. codePoint -= 0x10000
  1054. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1055. codePoint = 0xDC00 | codePoint & 0x3FF
  1056. }
  1057. res.push(codePoint)
  1058. i += bytesPerSequence
  1059. }
  1060. return decodeCodePointsArray(res)
  1061. }
  1062. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1063. // the lowest limit is Chrome, with 0x10000 args.
  1064. // We go 1 magnitude less, for safety
  1065. var MAX_ARGUMENTS_LENGTH = 0x1000
  1066. function decodeCodePointsArray (codePoints) {
  1067. var len = codePoints.length
  1068. if (len <= MAX_ARGUMENTS_LENGTH) {
  1069. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1070. }
  1071. // Decode in chunks to avoid "call stack size exceeded".
  1072. var res = ''
  1073. var i = 0
  1074. while (i < len) {
  1075. res += String.fromCharCode.apply(
  1076. String,
  1077. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1078. )
  1079. }
  1080. return res
  1081. }
  1082. function asciiSlice (buf, start, end) {
  1083. var ret = ''
  1084. end = Math.min(buf.length, end)
  1085. for (var i = start; i < end; ++i) {
  1086. ret += String.fromCharCode(buf[i] & 0x7F)
  1087. }
  1088. return ret
  1089. }
  1090. function latin1Slice (buf, start, end) {
  1091. var ret = ''
  1092. end = Math.min(buf.length, end)
  1093. for (var i = start; i < end; ++i) {
  1094. ret += String.fromCharCode(buf[i])
  1095. }
  1096. return ret
  1097. }
  1098. function hexSlice (buf, start, end) {
  1099. var len = buf.length
  1100. if (!start || start < 0) start = 0
  1101. if (!end || end < 0 || end > len) end = len
  1102. var out = ''
  1103. for (var i = start; i < end; ++i) {
  1104. out += toHex(buf[i])
  1105. }
  1106. return out
  1107. }
  1108. function utf16leSlice (buf, start, end) {
  1109. var bytes = buf.slice(start, end)
  1110. var res = ''
  1111. for (var i = 0; i < bytes.length; i += 2) {
  1112. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1113. }
  1114. return res
  1115. }
  1116. Buffer.prototype.slice = function slice (start, end) {
  1117. var len = this.length
  1118. start = ~~start
  1119. end = end === undefined ? len : ~~end
  1120. if (start < 0) {
  1121. start += len
  1122. if (start < 0) start = 0
  1123. } else if (start > len) {
  1124. start = len
  1125. }
  1126. if (end < 0) {
  1127. end += len
  1128. if (end < 0) end = 0
  1129. } else if (end > len) {
  1130. end = len
  1131. }
  1132. if (end < start) end = start
  1133. var newBuf
  1134. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1135. newBuf = this.subarray(start, end)
  1136. newBuf.__proto__ = Buffer.prototype
  1137. } else {
  1138. var sliceLen = end - start
  1139. newBuf = new Buffer(sliceLen, undefined)
  1140. for (var i = 0; i < sliceLen; ++i) {
  1141. newBuf[i] = this[i + start]
  1142. }
  1143. }
  1144. return newBuf
  1145. }
  1146. /*
  1147. * Need to make sure that buffer isn't trying to write out of bounds.
  1148. */
  1149. function checkOffset (offset, ext, length) {
  1150. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1151. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1152. }
  1153. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1154. offset = offset | 0
  1155. byteLength = byteLength | 0
  1156. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1157. var val = this[offset]
  1158. var mul = 1
  1159. var i = 0
  1160. while (++i < byteLength && (mul *= 0x100)) {
  1161. val += this[offset + i] * mul
  1162. }
  1163. return val
  1164. }
  1165. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1166. offset = offset | 0
  1167. byteLength = byteLength | 0
  1168. if (!noAssert) {
  1169. checkOffset(offset, byteLength, this.length)
  1170. }
  1171. var val = this[offset + --byteLength]
  1172. var mul = 1
  1173. while (byteLength > 0 && (mul *= 0x100)) {
  1174. val += this[offset + --byteLength] * mul
  1175. }
  1176. return val
  1177. }
  1178. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1179. if (!noAssert) checkOffset(offset, 1, this.length)
  1180. return this[offset]
  1181. }
  1182. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1183. if (!noAssert) checkOffset(offset, 2, this.length)
  1184. return this[offset] | (this[offset + 1] << 8)
  1185. }
  1186. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1187. if (!noAssert) checkOffset(offset, 2, this.length)
  1188. return (this[offset] << 8) | this[offset + 1]
  1189. }
  1190. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1191. if (!noAssert) checkOffset(offset, 4, this.length)
  1192. return ((this[offset]) |
  1193. (this[offset + 1] << 8) |
  1194. (this[offset + 2] << 16)) +
  1195. (this[offset + 3] * 0x1000000)
  1196. }
  1197. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1198. if (!noAssert) checkOffset(offset, 4, this.length)
  1199. return (this[offset] * 0x1000000) +
  1200. ((this[offset + 1] << 16) |
  1201. (this[offset + 2] << 8) |
  1202. this[offset + 3])
  1203. }
  1204. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1205. offset = offset | 0
  1206. byteLength = byteLength | 0
  1207. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1208. var val = this[offset]
  1209. var mul = 1
  1210. var i = 0
  1211. while (++i < byteLength && (mul *= 0x100)) {
  1212. val += this[offset + i] * mul
  1213. }
  1214. mul *= 0x80
  1215. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1216. return val
  1217. }
  1218. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1219. offset = offset | 0
  1220. byteLength = byteLength | 0
  1221. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1222. var i = byteLength
  1223. var mul = 1
  1224. var val = this[offset + --i]
  1225. while (i > 0 && (mul *= 0x100)) {
  1226. val += this[offset + --i] * mul
  1227. }
  1228. mul *= 0x80
  1229. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1230. return val
  1231. }
  1232. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1233. if (!noAssert) checkOffset(offset, 1, this.length)
  1234. if (!(this[offset] & 0x80)) return (this[offset])
  1235. return ((0xff - this[offset] + 1) * -1)
  1236. }
  1237. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1238. if (!noAssert) checkOffset(offset, 2, this.length)
  1239. var val = this[offset] | (this[offset + 1] << 8)
  1240. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1241. }
  1242. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1243. if (!noAssert) checkOffset(offset, 2, this.length)
  1244. var val = this[offset + 1] | (this[offset] << 8)
  1245. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1246. }
  1247. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1248. if (!noAssert) checkOffset(offset, 4, this.length)
  1249. return (this[offset]) |
  1250. (this[offset + 1] << 8) |
  1251. (this[offset + 2] << 16) |
  1252. (this[offset + 3] << 24)
  1253. }
  1254. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1255. if (!noAssert) checkOffset(offset, 4, this.length)
  1256. return (this[offset] << 24) |
  1257. (this[offset + 1] << 16) |
  1258. (this[offset + 2] << 8) |
  1259. (this[offset + 3])
  1260. }
  1261. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1262. if (!noAssert) checkOffset(offset, 4, this.length)
  1263. return ieee754.read(this, offset, true, 23, 4)
  1264. }
  1265. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1266. if (!noAssert) checkOffset(offset, 4, this.length)
  1267. return ieee754.read(this, offset, false, 23, 4)
  1268. }
  1269. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1270. if (!noAssert) checkOffset(offset, 8, this.length)
  1271. return ieee754.read(this, offset, true, 52, 8)
  1272. }
  1273. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1274. if (!noAssert) checkOffset(offset, 8, this.length)
  1275. return ieee754.read(this, offset, false, 52, 8)
  1276. }
  1277. function checkInt (buf, value, offset, ext, max, min) {
  1278. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1279. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1280. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1281. }
  1282. Buffer.prototype.writeUIntLE = function writeUIntLE (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 mul = 1
  1291. var i = 0
  1292. this[offset] = value & 0xFF
  1293. while (++i < byteLength && (mul *= 0x100)) {
  1294. this[offset + i] = (value / mul) & 0xFF
  1295. }
  1296. return offset + byteLength
  1297. }
  1298. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1299. value = +value
  1300. offset = offset | 0
  1301. byteLength = byteLength | 0
  1302. if (!noAssert) {
  1303. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1304. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1305. }
  1306. var i = byteLength - 1
  1307. var mul = 1
  1308. this[offset + i] = value & 0xFF
  1309. while (--i >= 0 && (mul *= 0x100)) {
  1310. this[offset + i] = (value / mul) & 0xFF
  1311. }
  1312. return offset + byteLength
  1313. }
  1314. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1315. value = +value
  1316. offset = offset | 0
  1317. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1318. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1319. this[offset] = (value & 0xff)
  1320. return offset + 1
  1321. }
  1322. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1323. if (value < 0) value = 0xffff + value + 1
  1324. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1325. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1326. (littleEndian ? i : 1 - i) * 8
  1327. }
  1328. }
  1329. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1330. value = +value
  1331. offset = offset | 0
  1332. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1333. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1334. this[offset] = (value & 0xff)
  1335. this[offset + 1] = (value >>> 8)
  1336. } else {
  1337. objectWriteUInt16(this, value, offset, true)
  1338. }
  1339. return offset + 2
  1340. }
  1341. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1342. value = +value
  1343. offset = offset | 0
  1344. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1345. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1346. this[offset] = (value >>> 8)
  1347. this[offset + 1] = (value & 0xff)
  1348. } else {
  1349. objectWriteUInt16(this, value, offset, false)
  1350. }
  1351. return offset + 2
  1352. }
  1353. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1354. if (value < 0) value = 0xffffffff + value + 1
  1355. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1356. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1357. }
  1358. }
  1359. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1360. value = +value
  1361. offset = offset | 0
  1362. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1363. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1364. this[offset + 3] = (value >>> 24)
  1365. this[offset + 2] = (value >>> 16)
  1366. this[offset + 1] = (value >>> 8)
  1367. this[offset] = (value & 0xff)
  1368. } else {
  1369. objectWriteUInt32(this, value, offset, true)
  1370. }
  1371. return offset + 4
  1372. }
  1373. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1374. value = +value
  1375. offset = offset | 0
  1376. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1377. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1378. this[offset] = (value >>> 24)
  1379. this[offset + 1] = (value >>> 16)
  1380. this[offset + 2] = (value >>> 8)
  1381. this[offset + 3] = (value & 0xff)
  1382. } else {
  1383. objectWriteUInt32(this, value, offset, false)
  1384. }
  1385. return offset + 4
  1386. }
  1387. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1388. value = +value
  1389. offset = offset | 0
  1390. if (!noAssert) {
  1391. var limit = Math.pow(2, 8 * byteLength - 1)
  1392. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1393. }
  1394. var i = 0
  1395. var mul = 1
  1396. var sub = 0
  1397. this[offset] = value & 0xFF
  1398. while (++i < byteLength && (mul *= 0x100)) {
  1399. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1400. sub = 1
  1401. }
  1402. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1403. }
  1404. return offset + byteLength
  1405. }
  1406. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1407. value = +value
  1408. offset = offset | 0
  1409. if (!noAssert) {
  1410. var limit = Math.pow(2, 8 * byteLength - 1)
  1411. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1412. }
  1413. var i = byteLength - 1
  1414. var mul = 1
  1415. var sub = 0
  1416. this[offset + i] = value & 0xFF
  1417. while (--i >= 0 && (mul *= 0x100)) {
  1418. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1419. sub = 1
  1420. }
  1421. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1422. }
  1423. return offset + byteLength
  1424. }
  1425. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1426. value = +value
  1427. offset = offset | 0
  1428. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1429. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1430. if (value < 0) value = 0xff + value + 1
  1431. this[offset] = (value & 0xff)
  1432. return offset + 1
  1433. }
  1434. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1435. value = +value
  1436. offset = offset | 0
  1437. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1438. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1439. this[offset] = (value & 0xff)
  1440. this[offset + 1] = (value >>> 8)
  1441. } else {
  1442. objectWriteUInt16(this, value, offset, true)
  1443. }
  1444. return offset + 2
  1445. }
  1446. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1447. value = +value
  1448. offset = offset | 0
  1449. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1450. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1451. this[offset] = (value >>> 8)
  1452. this[offset + 1] = (value & 0xff)
  1453. } else {
  1454. objectWriteUInt16(this, value, offset, false)
  1455. }
  1456. return offset + 2
  1457. }
  1458. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1459. value = +value
  1460. offset = offset | 0
  1461. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1462. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1463. this[offset] = (value & 0xff)
  1464. this[offset + 1] = (value >>> 8)
  1465. this[offset + 2] = (value >>> 16)
  1466. this[offset + 3] = (value >>> 24)
  1467. } else {
  1468. objectWriteUInt32(this, value, offset, true)
  1469. }
  1470. return offset + 4
  1471. }
  1472. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1473. value = +value
  1474. offset = offset | 0
  1475. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1476. if (value < 0) value = 0xffffffff + value + 1
  1477. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1478. this[offset] = (value >>> 24)
  1479. this[offset + 1] = (value >>> 16)
  1480. this[offset + 2] = (value >>> 8)
  1481. this[offset + 3] = (value & 0xff)
  1482. } else {
  1483. objectWriteUInt32(this, value, offset, false)
  1484. }
  1485. return offset + 4
  1486. }
  1487. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1488. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1489. if (offset < 0) throw new RangeError('Index out of range')
  1490. }
  1491. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1492. if (!noAssert) {
  1493. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1494. }
  1495. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1496. return offset + 4
  1497. }
  1498. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1499. return writeFloat(this, value, offset, true, noAssert)
  1500. }
  1501. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1502. return writeFloat(this, value, offset, false, noAssert)
  1503. }
  1504. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1505. if (!noAssert) {
  1506. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1507. }
  1508. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1509. return offset + 8
  1510. }
  1511. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1512. return writeDouble(this, value, offset, true, noAssert)
  1513. }
  1514. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1515. return writeDouble(this, value, offset, false, noAssert)
  1516. }
  1517. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1518. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1519. if (!start) start = 0
  1520. if (!end && end !== 0) end = this.length
  1521. if (targetStart >= target.length) targetStart = target.length
  1522. if (!targetStart) targetStart = 0
  1523. if (end > 0 && end < start) end = start
  1524. // Copy 0 bytes; we're done
  1525. if (end === start) return 0
  1526. if (target.length === 0 || this.length === 0) return 0
  1527. // Fatal error conditions
  1528. if (targetStart < 0) {
  1529. throw new RangeError('targetStart out of bounds')
  1530. }
  1531. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1532. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1533. // Are we oob?
  1534. if (end > this.length) end = this.length
  1535. if (target.length - targetStart < end - start) {
  1536. end = target.length - targetStart + start
  1537. }
  1538. var len = end - start
  1539. var i
  1540. if (this === target && start < targetStart && targetStart < end) {
  1541. // descending copy from end
  1542. for (i = len - 1; i >= 0; --i) {
  1543. target[i + targetStart] = this[i + start]
  1544. }
  1545. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1546. // ascending copy from start
  1547. for (i = 0; i < len; ++i) {
  1548. target[i + targetStart] = this[i + start]
  1549. }
  1550. } else {
  1551. Uint8Array.prototype.set.call(
  1552. target,
  1553. this.subarray(start, start + len),
  1554. targetStart
  1555. )
  1556. }
  1557. return len
  1558. }
  1559. // Usage:
  1560. // buffer.fill(number[, offset[, end]])
  1561. // buffer.fill(buffer[, offset[, end]])
  1562. // buffer.fill(string[, offset[, end]][, encoding])
  1563. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1564. // Handle string cases:
  1565. if (typeof val === 'string') {
  1566. if (typeof start === 'string') {
  1567. encoding = start
  1568. start = 0
  1569. end = this.length
  1570. } else if (typeof end === 'string') {
  1571. encoding = end
  1572. end = this.length
  1573. }
  1574. if (val.length === 1) {
  1575. var code = val.charCodeAt(0)
  1576. if (code < 256) {
  1577. val = code
  1578. }
  1579. }
  1580. if (encoding !== undefined && typeof encoding !== 'string') {
  1581. throw new TypeError('encoding must be a string')
  1582. }
  1583. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1584. throw new TypeError('Unknown encoding: ' + encoding)
  1585. }
  1586. } else if (typeof val === 'number') {
  1587. val = val & 255
  1588. }
  1589. // Invalid ranges are not set to a default, so can range check early.
  1590. if (start < 0 || this.length < start || this.length < end) {
  1591. throw new RangeError('Out of range index')
  1592. }
  1593. if (end <= start) {
  1594. return this
  1595. }
  1596. start = start >>> 0
  1597. end = end === undefined ? this.length : end >>> 0
  1598. if (!val) val = 0
  1599. var i
  1600. if (typeof val === 'number') {
  1601. for (i = start; i < end; ++i) {
  1602. this[i] = val
  1603. }
  1604. } else {
  1605. var bytes = Buffer.isBuffer(val)
  1606. ? val
  1607. : utf8ToBytes(new Buffer(val, encoding).toString())
  1608. var len = bytes.length
  1609. for (i = 0; i < end - start; ++i) {
  1610. this[i + start] = bytes[i % len]
  1611. }
  1612. }
  1613. return this
  1614. }
  1615. // HELPER FUNCTIONS
  1616. // ================
  1617. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1618. function base64clean (str) {
  1619. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1620. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1621. // Node converts strings with length < 2 to ''
  1622. if (str.length < 2) return ''
  1623. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1624. while (str.length % 4 !== 0) {
  1625. str = str + '='
  1626. }
  1627. return str
  1628. }
  1629. function stringtrim (str) {
  1630. if (str.trim) return str.trim()
  1631. return str.replace(/^\s+|\s+$/g, '')
  1632. }
  1633. function toHex (n) {
  1634. if (n < 16) return '0' + n.toString(16)
  1635. return n.toString(16)
  1636. }
  1637. function utf8ToBytes (string, units) {
  1638. units = units || Infinity
  1639. var codePoint
  1640. var length = string.length
  1641. var leadSurrogate = null
  1642. var bytes = []
  1643. for (var i = 0; i < length; ++i) {
  1644. codePoint = string.charCodeAt(i)
  1645. // is surrogate component
  1646. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1647. // last char was a lead
  1648. if (!leadSurrogate) {
  1649. // no lead yet
  1650. if (codePoint > 0xDBFF) {
  1651. // unexpected trail
  1652. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1653. continue
  1654. } else if (i + 1 === length) {
  1655. // unpaired lead
  1656. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1657. continue
  1658. }
  1659. // valid lead
  1660. leadSurrogate = codePoint
  1661. continue
  1662. }
  1663. // 2 leads in a row
  1664. if (codePoint < 0xDC00) {
  1665. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1666. leadSurrogate = codePoint
  1667. continue
  1668. }
  1669. // valid surrogate pair
  1670. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1671. } else if (leadSurrogate) {
  1672. // valid bmp char, but last char was a lead
  1673. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1674. }
  1675. leadSurrogate = null
  1676. // encode utf8
  1677. if (codePoint < 0x80) {
  1678. if ((units -= 1) < 0) break
  1679. bytes.push(codePoint)
  1680. } else if (codePoint < 0x800) {
  1681. if ((units -= 2) < 0) break
  1682. bytes.push(
  1683. codePoint >> 0x6 | 0xC0,
  1684. codePoint & 0x3F | 0x80
  1685. )
  1686. } else if (codePoint < 0x10000) {
  1687. if ((units -= 3) < 0) break
  1688. bytes.push(
  1689. codePoint >> 0xC | 0xE0,
  1690. codePoint >> 0x6 & 0x3F | 0x80,
  1691. codePoint & 0x3F | 0x80
  1692. )
  1693. } else if (codePoint < 0x110000) {
  1694. if ((units -= 4) < 0) break
  1695. bytes.push(
  1696. codePoint >> 0x12 | 0xF0,
  1697. codePoint >> 0xC & 0x3F | 0x80,
  1698. codePoint >> 0x6 & 0x3F | 0x80,
  1699. codePoint & 0x3F | 0x80
  1700. )
  1701. } else {
  1702. throw new Error('Invalid code point')
  1703. }
  1704. }
  1705. return bytes
  1706. }
  1707. function asciiToBytes (str) {
  1708. var byteArray = []
  1709. for (var i = 0; i < str.length; ++i) {
  1710. // Node's code seems to be doing this and not & 0x7F..
  1711. byteArray.push(str.charCodeAt(i) & 0xFF)
  1712. }
  1713. return byteArray
  1714. }
  1715. function utf16leToBytes (str, units) {
  1716. var c, hi, lo
  1717. var byteArray = []
  1718. for (var i = 0; i < str.length; ++i) {
  1719. if ((units -= 2) < 0) break
  1720. c = str.charCodeAt(i)
  1721. hi = c >> 8
  1722. lo = c % 256
  1723. byteArray.push(lo)
  1724. byteArray.push(hi)
  1725. }
  1726. return byteArray
  1727. }
  1728. function base64ToBytes (str) {
  1729. return base64.toByteArray(base64clean(str))
  1730. }
  1731. function blitBuffer (src, dst, offset, length) {
  1732. for (var i = 0; i < length; ++i) {
  1733. if ((i + offset >= dst.length) || (i >= src.length)) break
  1734. dst[i + offset] = src[i]
  1735. }
  1736. return i
  1737. }
  1738. function isnan (val) {
  1739. return val !== val // eslint-disable-line no-self-compare
  1740. }
  1741. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1742. },{"base64-js":4,"ieee754":16,"isarray":21}],8:[function(_dereq_,module,exports){
  1743. /**
  1744. * This is the web browser implementation of `debug()`.
  1745. *
  1746. * Expose `debug()` as the module.
  1747. */
  1748. exports = module.exports = _dereq_('./debug');
  1749. exports.log = log;
  1750. exports.formatArgs = formatArgs;
  1751. exports.save = save;
  1752. exports.load = load;
  1753. exports.useColors = useColors;
  1754. exports.storage = 'undefined' != typeof chrome
  1755. && 'undefined' != typeof chrome.storage
  1756. ? chrome.storage.local
  1757. : localstorage();
  1758. /**
  1759. * Colors.
  1760. */
  1761. exports.colors = [
  1762. 'lightseagreen',
  1763. 'forestgreen',
  1764. 'goldenrod',
  1765. 'dodgerblue',
  1766. 'darkorchid',
  1767. 'crimson'
  1768. ];
  1769. /**
  1770. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1771. * and the Firebug extension (any Firefox version) are known
  1772. * to support "%c" CSS customizations.
  1773. *
  1774. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1775. */
  1776. function useColors() {
  1777. // is webkit? http://stackoverflow.com/a/16459606/376773
  1778. return ('WebkitAppearance' in document.documentElement.style) ||
  1779. // is firebug? http://stackoverflow.com/a/398120/376773
  1780. (window.console && (console.firebug || (console.exception && console.table))) ||
  1781. // is firefox >= v31?
  1782. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1783. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  1784. }
  1785. /**
  1786. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1787. */
  1788. exports.formatters.j = function(v) {
  1789. return JSON.stringify(v);
  1790. };
  1791. /**
  1792. * Colorize log arguments if enabled.
  1793. *
  1794. * @api public
  1795. */
  1796. function formatArgs() {
  1797. var args = arguments;
  1798. var useColors = this.useColors;
  1799. args[0] = (useColors ? '%c' : '')
  1800. + this.namespace
  1801. + (useColors ? ' %c' : ' ')
  1802. + args[0]
  1803. + (useColors ? '%c ' : ' ');
  1804. if (!useColors) return args;
  1805. var c = 'color: ' + this.color;
  1806. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  1807. // the final "%c" is somewhat tricky, because there could be other
  1808. // arguments passed either before or after the %c, so we need to
  1809. // figure out the correct index to insert the CSS into
  1810. var index = 0;
  1811. var lastC = 0;
  1812. args[0].replace(/%[a-z%]/g, function(match) {
  1813. if ('%%' === match) return;
  1814. index++;
  1815. if ('%c' === match) {
  1816. // we only are interested in the *last* %c
  1817. // (the user may have provided their own)
  1818. lastC = index;
  1819. }
  1820. });
  1821. args.splice(lastC, 0, c);
  1822. return args;
  1823. }
  1824. /**
  1825. * Invokes `console.log()` when available.
  1826. * No-op when `console.log` is not a "function".
  1827. *
  1828. * @api public
  1829. */
  1830. function log() {
  1831. // this hackery is required for IE8/9, where
  1832. // the `console.log` function doesn't have 'apply'
  1833. return 'object' === typeof console
  1834. && console.log
  1835. && Function.prototype.apply.call(console.log, console, arguments);
  1836. }
  1837. /**
  1838. * Save `namespaces`.
  1839. *
  1840. * @param {String} namespaces
  1841. * @api private
  1842. */
  1843. function save(namespaces) {
  1844. try {
  1845. if (null == namespaces) {
  1846. exports.storage.removeItem('debug');
  1847. } else {
  1848. exports.storage.debug = namespaces;
  1849. }
  1850. } catch(e) {}
  1851. }
  1852. /**
  1853. * Load `namespaces`.
  1854. *
  1855. * @return {String} returns the previously persisted debug modes
  1856. * @api private
  1857. */
  1858. function load() {
  1859. var r;
  1860. try {
  1861. r = exports.storage.debug;
  1862. } catch(e) {}
  1863. return r;
  1864. }
  1865. /**
  1866. * Enable namespaces listed in `localStorage.debug` initially.
  1867. */
  1868. exports.enable(load());
  1869. /**
  1870. * Localstorage attempts to return the localstorage.
  1871. *
  1872. * This is necessary because safari throws
  1873. * when a user disables cookies/localstorage
  1874. * and you attempt to access it.
  1875. *
  1876. * @return {LocalStorage}
  1877. * @api private
  1878. */
  1879. function localstorage(){
  1880. try {
  1881. return window.localStorage;
  1882. } catch (e) {}
  1883. }
  1884. },{"./debug":9}],9:[function(_dereq_,module,exports){
  1885. /**
  1886. * This is the common logic for both the Node.js and web browser
  1887. * implementations of `debug()`.
  1888. *
  1889. * Expose `debug()` as the module.
  1890. */
  1891. exports = module.exports = debug;
  1892. exports.coerce = coerce;
  1893. exports.disable = disable;
  1894. exports.enable = enable;
  1895. exports.enabled = enabled;
  1896. /**
  1897. * The currently active debug mode names, and names to skip.
  1898. */
  1899. exports.names = [];
  1900. exports.skips = [];
  1901. /**
  1902. * Map of special "%n" handling functions, for the debug "format" argument.
  1903. *
  1904. * Valid key names are a single, lowercased letter, i.e. "n".
  1905. */
  1906. exports.formatters = {};
  1907. /**
  1908. * Previously assigned color.
  1909. */
  1910. var prevColor = 0;
  1911. /**
  1912. * Select a color.
  1913. *
  1914. * @return {Number}
  1915. * @api private
  1916. */
  1917. function selectColor() {
  1918. return exports.colors[prevColor++ % exports.colors.length];
  1919. }
  1920. /**
  1921. * Create a debugger with the given `namespace`.
  1922. *
  1923. * @param {String} namespace
  1924. * @return {Function}
  1925. * @api public
  1926. */
  1927. function debug(namespace) {
  1928. // define the `disabled` version
  1929. function disabled() {
  1930. }
  1931. disabled.enabled = false;
  1932. // define the `enabled` version
  1933. function enabled() {
  1934. var self = enabled;
  1935. // add the `color` if not set
  1936. if (null == self.useColors) self.useColors = exports.useColors();
  1937. if (null == self.color && self.useColors) self.color = selectColor();
  1938. var args = Array.prototype.slice.call(arguments);
  1939. args[0] = exports.coerce(args[0]);
  1940. if ('string' !== typeof args[0]) {
  1941. // anything else let's inspect with %o
  1942. args = ['%o'].concat(args);
  1943. }
  1944. // apply any `formatters` transformations
  1945. var index = 0;
  1946. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  1947. // if we encounter an escaped % then don't increase the array index
  1948. if (match === '%%') return match;
  1949. index++;
  1950. var formatter = exports.formatters[format];
  1951. if ('function' === typeof formatter) {
  1952. var val = args[index];
  1953. match = formatter.call(self, val);
  1954. // now we need to remove `args[index]` since it's inlined in the `format`
  1955. args.splice(index, 1);
  1956. index--;
  1957. }
  1958. return match;
  1959. });
  1960. if ('function' === typeof exports.formatArgs) {
  1961. args = exports.formatArgs.apply(self, args);
  1962. }
  1963. var logFn = enabled.log || exports.log || console.log.bind(console);
  1964. logFn.apply(self, args);
  1965. }
  1966. enabled.enabled = true;
  1967. var fn = exports.enabled(namespace) ? enabled : disabled;
  1968. fn.namespace = namespace;
  1969. return fn;
  1970. }
  1971. /**
  1972. * Enables a debug mode by namespaces. This can include modes
  1973. * separated by a colon and wildcards.
  1974. *
  1975. * @param {String} namespaces
  1976. * @api public
  1977. */
  1978. function enable(namespaces) {
  1979. exports.save(namespaces);
  1980. var split = (namespaces || '').split(/[\s,]+/);
  1981. var len = split.length;
  1982. for (var i = 0; i < len; i++) {
  1983. if (!split[i]) continue; // ignore empty strings
  1984. namespaces = split[i].replace(/\*/g, '.*?');
  1985. if (namespaces[0] === '-') {
  1986. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  1987. } else {
  1988. exports.names.push(new RegExp('^' + namespaces + '$'));
  1989. }
  1990. }
  1991. }
  1992. /**
  1993. * Disable debug output.
  1994. *
  1995. * @api public
  1996. */
  1997. function disable() {
  1998. exports.enable('');
  1999. }
  2000. /**
  2001. * Returns true if the given mode name is enabled, false otherwise.
  2002. *
  2003. * @param {String} name
  2004. * @return {Boolean}
  2005. * @api public
  2006. */
  2007. function enabled(name) {
  2008. var i, len;
  2009. for (i = 0, len = exports.skips.length; i < len; i++) {
  2010. if (exports.skips[i].test(name)) {
  2011. return false;
  2012. }
  2013. }
  2014. for (i = 0, len = exports.names.length; i < len; i++) {
  2015. if (exports.names[i].test(name)) {
  2016. return true;
  2017. }
  2018. }
  2019. return false;
  2020. }
  2021. /**
  2022. * Coerce `val`.
  2023. *
  2024. * @param {Mixed} val
  2025. * @return {Mixed}
  2026. * @api private
  2027. */
  2028. function coerce(val) {
  2029. if (val instanceof Error) return val.stack || val.message;
  2030. return val;
  2031. }
  2032. },{}],10:[function(_dereq_,module,exports){
  2033. 'use strict';
  2034. var isObj = _dereq_('is-obj');
  2035. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2036. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2037. function toObject(val) {
  2038. if (val === null || val === undefined) {
  2039. throw new TypeError('Sources cannot be null or undefined');
  2040. }
  2041. return Object(val);
  2042. }
  2043. function assignKey(to, from, key) {
  2044. var val = from[key];
  2045. if (val === undefined || val === null) {
  2046. return;
  2047. }
  2048. if (hasOwnProperty.call(to, key)) {
  2049. if (to[key] === undefined || to[key] === null) {
  2050. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2051. }
  2052. }
  2053. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2054. to[key] = val;
  2055. } else {
  2056. to[key] = assign(Object(to[key]), from[key]);
  2057. }
  2058. }
  2059. function assign(to, from) {
  2060. if (to === from) {
  2061. return to;
  2062. }
  2063. from = Object(from);
  2064. for (var key in from) {
  2065. if (hasOwnProperty.call(from, key)) {
  2066. assignKey(to, from, key);
  2067. }
  2068. }
  2069. if (Object.getOwnPropertySymbols) {
  2070. var symbols = Object.getOwnPropertySymbols(from);
  2071. for (var i = 0; i < symbols.length; i++) {
  2072. if (propIsEnumerable.call(from, symbols[i])) {
  2073. assignKey(to, from, symbols[i]);
  2074. }
  2075. }
  2076. }
  2077. return to;
  2078. }
  2079. module.exports = function deepAssign(target) {
  2080. target = toObject(target);
  2081. for (var s = 1; s < arguments.length; s++) {
  2082. assign(target, arguments[s]);
  2083. }
  2084. return target;
  2085. };
  2086. },{"is-obj":20}],11:[function(_dereq_,module,exports){
  2087. /*! (C) WebReflection Mit Style License */
  2088. (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");
  2089. },{}],12:[function(_dereq_,module,exports){
  2090. module.exports = function(dtype) {
  2091. switch (dtype) {
  2092. case 'int8':
  2093. return Int8Array
  2094. case 'int16':
  2095. return Int16Array
  2096. case 'int32':
  2097. return Int32Array
  2098. case 'uint8':
  2099. return Uint8Array
  2100. case 'uint16':
  2101. return Uint16Array
  2102. case 'uint32':
  2103. return Uint32Array
  2104. case 'float32':
  2105. return Float32Array
  2106. case 'float64':
  2107. return Float64Array
  2108. case 'array':
  2109. return Array
  2110. case 'uint8_clamped':
  2111. return Uint8ClampedArray
  2112. }
  2113. }
  2114. },{}],13:[function(_dereq_,module,exports){
  2115. /*eslint new-cap:0*/
  2116. var dtype = _dereq_('dtype')
  2117. module.exports = flattenVertexData
  2118. function flattenVertexData (data, output, offset) {
  2119. if (!data) throw new TypeError('must specify data as first parameter')
  2120. offset = +(offset || 0) | 0
  2121. if (Array.isArray(data) && Array.isArray(data[0])) {
  2122. var dim = data[0].length
  2123. var length = data.length * dim
  2124. // no output specified, create a new typed array
  2125. if (!output || typeof output === 'string') {
  2126. output = new (dtype(output || 'float32'))(length + offset)
  2127. }
  2128. var dstLength = output.length - offset
  2129. if (length !== dstLength) {
  2130. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2131. ' does not match destination length ' + dstLength)
  2132. }
  2133. for (var i = 0, k = offset; i < data.length; i++) {
  2134. for (var j = 0; j < dim; j++) {
  2135. output[k++] = data[i][j]
  2136. }
  2137. }
  2138. } else {
  2139. if (!output || typeof output === 'string') {
  2140. // no output, create a new one
  2141. var Ctor = dtype(output || 'float32')
  2142. if (offset === 0) {
  2143. output = new Ctor(data)
  2144. } else {
  2145. output = new Ctor(data.length + offset)
  2146. output.set(data, offset)
  2147. }
  2148. } else {
  2149. // store output in existing array
  2150. output.set(data, offset)
  2151. }
  2152. }
  2153. return output
  2154. }
  2155. },{"dtype":12}],14:[function(_dereq_,module,exports){
  2156. var isFunction = _dereq_('is-function')
  2157. module.exports = forEach
  2158. var toString = Object.prototype.toString
  2159. var hasOwnProperty = Object.prototype.hasOwnProperty
  2160. function forEach(list, iterator, context) {
  2161. if (!isFunction(iterator)) {
  2162. throw new TypeError('iterator must be a function')
  2163. }
  2164. if (arguments.length < 3) {
  2165. context = this
  2166. }
  2167. if (toString.call(list) === '[object Array]')
  2168. forEachArray(list, iterator, context)
  2169. else if (typeof list === 'string')
  2170. forEachString(list, iterator, context)
  2171. else
  2172. forEachObject(list, iterator, context)
  2173. }
  2174. function forEachArray(array, iterator, context) {
  2175. for (var i = 0, len = array.length; i < len; i++) {
  2176. if (hasOwnProperty.call(array, i)) {
  2177. iterator.call(context, array[i], i, array)
  2178. }
  2179. }
  2180. }
  2181. function forEachString(string, iterator, context) {
  2182. for (var i = 0, len = string.length; i < len; i++) {
  2183. // no such thing as a sparse string.
  2184. iterator.call(context, string.charAt(i), i, string)
  2185. }
  2186. }
  2187. function forEachObject(object, iterator, context) {
  2188. for (var k in object) {
  2189. if (hasOwnProperty.call(object, k)) {
  2190. iterator.call(context, object[k], k, object)
  2191. }
  2192. }
  2193. }
  2194. },{"is-function":19}],15:[function(_dereq_,module,exports){
  2195. (function (global){
  2196. var win;
  2197. if (typeof window !== "undefined") {
  2198. win = window;
  2199. } else if (typeof global !== "undefined") {
  2200. win = global;
  2201. } else if (typeof self !== "undefined"){
  2202. win = self;
  2203. } else {
  2204. win = {};
  2205. }
  2206. module.exports = win;
  2207. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2208. },{}],16:[function(_dereq_,module,exports){
  2209. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2210. var e, m
  2211. var eLen = nBytes * 8 - mLen - 1
  2212. var eMax = (1 << eLen) - 1
  2213. var eBias = eMax >> 1
  2214. var nBits = -7
  2215. var i = isLE ? (nBytes - 1) : 0
  2216. var d = isLE ? -1 : 1
  2217. var s = buffer[offset + i]
  2218. i += d
  2219. e = s & ((1 << (-nBits)) - 1)
  2220. s >>= (-nBits)
  2221. nBits += eLen
  2222. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2223. m = e & ((1 << (-nBits)) - 1)
  2224. e >>= (-nBits)
  2225. nBits += mLen
  2226. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2227. if (e === 0) {
  2228. e = 1 - eBias
  2229. } else if (e === eMax) {
  2230. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2231. } else {
  2232. m = m + Math.pow(2, mLen)
  2233. e = e - eBias
  2234. }
  2235. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2236. }
  2237. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2238. var e, m, c
  2239. var eLen = nBytes * 8 - mLen - 1
  2240. var eMax = (1 << eLen) - 1
  2241. var eBias = eMax >> 1
  2242. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2243. var i = isLE ? 0 : (nBytes - 1)
  2244. var d = isLE ? 1 : -1
  2245. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2246. value = Math.abs(value)
  2247. if (isNaN(value) || value === Infinity) {
  2248. m = isNaN(value) ? 1 : 0
  2249. e = eMax
  2250. } else {
  2251. e = Math.floor(Math.log(value) / Math.LN2)
  2252. if (value * (c = Math.pow(2, -e)) < 1) {
  2253. e--
  2254. c *= 2
  2255. }
  2256. if (e + eBias >= 1) {
  2257. value += rt / c
  2258. } else {
  2259. value += rt * Math.pow(2, 1 - eBias)
  2260. }
  2261. if (value * c >= 2) {
  2262. e++
  2263. c /= 2
  2264. }
  2265. if (e + eBias >= eMax) {
  2266. m = 0
  2267. e = eMax
  2268. } else if (e + eBias >= 1) {
  2269. m = (value * c - 1) * Math.pow(2, mLen)
  2270. e = e + eBias
  2271. } else {
  2272. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2273. e = 0
  2274. }
  2275. }
  2276. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2277. e = (e << mLen) | m
  2278. eLen += mLen
  2279. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2280. buffer[offset + i - d] |= s * 128
  2281. }
  2282. },{}],17:[function(_dereq_,module,exports){
  2283. if (typeof Object.create === 'function') {
  2284. // implementation from standard node.js 'util' module
  2285. module.exports = function inherits(ctor, superCtor) {
  2286. ctor.super_ = superCtor
  2287. ctor.prototype = Object.create(superCtor.prototype, {
  2288. constructor: {
  2289. value: ctor,
  2290. enumerable: false,
  2291. writable: true,
  2292. configurable: true
  2293. }
  2294. });
  2295. };
  2296. } else {
  2297. // old school shim for old browsers
  2298. module.exports = function inherits(ctor, superCtor) {
  2299. ctor.super_ = superCtor
  2300. var TempCtor = function () {}
  2301. TempCtor.prototype = superCtor.prototype
  2302. ctor.prototype = new TempCtor()
  2303. ctor.prototype.constructor = ctor
  2304. }
  2305. }
  2306. },{}],18:[function(_dereq_,module,exports){
  2307. /*!
  2308. * Determine if an object is a Buffer
  2309. *
  2310. * @author Feross Aboukhadijeh <https://feross.org>
  2311. * @license MIT
  2312. */
  2313. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2314. // Object.prototype.constructor. Remove this eventually
  2315. module.exports = function (obj) {
  2316. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2317. }
  2318. function isBuffer (obj) {
  2319. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2320. }
  2321. // For Node v0.10 support. Remove this eventually.
  2322. function isSlowBuffer (obj) {
  2323. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2324. }
  2325. },{}],19:[function(_dereq_,module,exports){
  2326. module.exports = isFunction
  2327. var toString = Object.prototype.toString
  2328. function isFunction (fn) {
  2329. var string = toString.call(fn)
  2330. return string === '[object Function]' ||
  2331. (typeof fn === 'function' && string !== '[object RegExp]') ||
  2332. (typeof window !== 'undefined' &&
  2333. // IE8 and below
  2334. (fn === window.setTimeout ||
  2335. fn === window.alert ||
  2336. fn === window.confirm ||
  2337. fn === window.prompt))
  2338. };
  2339. },{}],20:[function(_dereq_,module,exports){
  2340. 'use strict';
  2341. module.exports = function (x) {
  2342. var type = typeof x;
  2343. return x !== null && (type === 'object' || type === 'function');
  2344. };
  2345. },{}],21:[function(_dereq_,module,exports){
  2346. var toString = {}.toString;
  2347. module.exports = Array.isArray || function (arr) {
  2348. return toString.call(arr) == '[object Array]';
  2349. };
  2350. },{}],22:[function(_dereq_,module,exports){
  2351. var wordWrap = _dereq_('word-wrapper')
  2352. var xtend = _dereq_('xtend')
  2353. var number = _dereq_('as-number')
  2354. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  2355. var M_WIDTHS = ['m', 'w']
  2356. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  2357. var TAB_ID = '\t'.charCodeAt(0)
  2358. var SPACE_ID = ' '.charCodeAt(0)
  2359. var ALIGN_LEFT = 0,
  2360. ALIGN_CENTER = 1,
  2361. ALIGN_RIGHT = 2
  2362. module.exports = function createLayout(opt) {
  2363. return new TextLayout(opt)
  2364. }
  2365. function TextLayout(opt) {
  2366. this.glyphs = []
  2367. this._measure = this.computeMetrics.bind(this)
  2368. this.update(opt)
  2369. }
  2370. TextLayout.prototype.update = function(opt) {
  2371. opt = xtend({
  2372. measure: this._measure
  2373. }, opt)
  2374. this._opt = opt
  2375. this._opt.tabSize = number(this._opt.tabSize, 4)
  2376. if (!opt.font)
  2377. throw new Error('must provide a valid bitmap font')
  2378. var glyphs = this.glyphs
  2379. var text = opt.text||''
  2380. var font = opt.font
  2381. this._setupSpaceGlyphs(font)
  2382. var lines = wordWrap.lines(text, opt)
  2383. var minWidth = opt.width || 0
  2384. //clear glyphs
  2385. glyphs.length = 0
  2386. //get max line width
  2387. var maxLineWidth = lines.reduce(function(prev, line) {
  2388. return Math.max(prev, line.width, minWidth)
  2389. }, 0)
  2390. //the pen position
  2391. var x = 0
  2392. var y = 0
  2393. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  2394. var baseline = font.common.base
  2395. var descender = lineHeight-baseline
  2396. var letterSpacing = opt.letterSpacing || 0
  2397. var height = lineHeight * lines.length - descender
  2398. var align = getAlignType(this._opt.align)
  2399. //draw text along baseline
  2400. y -= height
  2401. //the metrics for this text layout
  2402. this._width = maxLineWidth
  2403. this._height = height
  2404. this._descender = lineHeight - baseline
  2405. this._baseline = baseline
  2406. this._xHeight = getXHeight(font)
  2407. this._capHeight = getCapHeight(font)
  2408. this._lineHeight = lineHeight
  2409. this._ascender = lineHeight - descender - this._xHeight
  2410. //layout each glyph
  2411. var self = this
  2412. lines.forEach(function(line, lineIndex) {
  2413. var start = line.start
  2414. var end = line.end
  2415. var lineWidth = line.width
  2416. var lastGlyph
  2417. //for each glyph in that line...
  2418. for (var i=start; i<end; i++) {
  2419. var id = text.charCodeAt(i)
  2420. var glyph = self.getGlyph(font, id)
  2421. if (glyph) {
  2422. if (lastGlyph)
  2423. x += getKerning(font, lastGlyph.id, glyph.id)
  2424. var tx = x
  2425. if (align === ALIGN_CENTER)
  2426. tx += (maxLineWidth-lineWidth)/2
  2427. else if (align === ALIGN_RIGHT)
  2428. tx += (maxLineWidth-lineWidth)
  2429. glyphs.push({
  2430. position: [tx, y],
  2431. data: glyph,
  2432. index: i,
  2433. line: lineIndex
  2434. })
  2435. //move pen forward
  2436. x += glyph.xadvance + letterSpacing
  2437. lastGlyph = glyph
  2438. }
  2439. }
  2440. //next line down
  2441. y += lineHeight
  2442. x = 0
  2443. })
  2444. this._linesTotal = lines.length;
  2445. }
  2446. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  2447. //These are fallbacks, when the font doesn't include
  2448. //' ' or '\t' glyphs
  2449. this._fallbackSpaceGlyph = null
  2450. this._fallbackTabGlyph = null
  2451. if (!font.chars || font.chars.length === 0)
  2452. return
  2453. //try to get space glyph
  2454. //then fall back to the 'm' or 'w' glyphs
  2455. //then fall back to the first glyph available
  2456. var space = getGlyphById(font, SPACE_ID)
  2457. || getMGlyph(font)
  2458. || font.chars[0]
  2459. //and create a fallback for tab
  2460. var tabWidth = this._opt.tabSize * space.xadvance
  2461. this._fallbackSpaceGlyph = space
  2462. this._fallbackTabGlyph = xtend(space, {
  2463. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  2464. xoffset: 0, yoffset: 0, width: 0, height: 0
  2465. })
  2466. }
  2467. TextLayout.prototype.getGlyph = function(font, id) {
  2468. var glyph = getGlyphById(font, id)
  2469. if (glyph)
  2470. return glyph
  2471. else if (id === TAB_ID)
  2472. return this._fallbackTabGlyph
  2473. else if (id === SPACE_ID)
  2474. return this._fallbackSpaceGlyph
  2475. return null
  2476. }
  2477. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  2478. var letterSpacing = this._opt.letterSpacing || 0
  2479. var font = this._opt.font
  2480. var curPen = 0
  2481. var curWidth = 0
  2482. var count = 0
  2483. var glyph
  2484. var lastGlyph
  2485. if (!font.chars || font.chars.length === 0) {
  2486. return {
  2487. start: start,
  2488. end: start,
  2489. width: 0
  2490. }
  2491. }
  2492. end = Math.min(text.length, end)
  2493. for (var i=start; i < end; i++) {
  2494. var id = text.charCodeAt(i)
  2495. var glyph = this.getGlyph(font, id)
  2496. if (glyph) {
  2497. //move pen forward
  2498. var xoff = glyph.xoffset
  2499. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  2500. curPen += kern
  2501. var nextPen = curPen + glyph.xadvance + letterSpacing
  2502. var nextWidth = curPen + glyph.width
  2503. //we've hit our limit; we can't move onto the next glyph
  2504. if (nextWidth >= width || nextPen >= width)
  2505. break
  2506. //otherwise continue along our line
  2507. curPen = nextPen
  2508. curWidth = nextWidth
  2509. lastGlyph = glyph
  2510. }
  2511. count++
  2512. }
  2513. //make sure rightmost edge lines up with rendered glyphs
  2514. if (lastGlyph)
  2515. curWidth += lastGlyph.xoffset
  2516. return {
  2517. start: start,
  2518. end: start + count,
  2519. width: curWidth
  2520. }
  2521. }
  2522. //getters for the private vars
  2523. ;['width', 'height',
  2524. 'descender', 'ascender',
  2525. 'xHeight', 'baseline',
  2526. 'capHeight',
  2527. 'lineHeight' ].forEach(addGetter)
  2528. function addGetter(name) {
  2529. Object.defineProperty(TextLayout.prototype, name, {
  2530. get: wrapper(name),
  2531. configurable: true
  2532. })
  2533. }
  2534. //create lookups for private vars
  2535. function wrapper(name) {
  2536. return (new Function([
  2537. 'return function '+name+'() {',
  2538. ' return this._'+name,
  2539. '}'
  2540. ].join('\n')))()
  2541. }
  2542. function getGlyphById(font, id) {
  2543. if (!font.chars || font.chars.length === 0)
  2544. return null
  2545. var glyphIdx = findChar(font.chars, id)
  2546. if (glyphIdx >= 0)
  2547. return font.chars[glyphIdx]
  2548. return null
  2549. }
  2550. function getXHeight(font) {
  2551. for (var i=0; i<X_HEIGHTS.length; i++) {
  2552. var id = X_HEIGHTS[i].charCodeAt(0)
  2553. var idx = findChar(font.chars, id)
  2554. if (idx >= 0)
  2555. return font.chars[idx].height
  2556. }
  2557. return 0
  2558. }
  2559. function getMGlyph(font) {
  2560. for (var i=0; i<M_WIDTHS.length; i++) {
  2561. var id = M_WIDTHS[i].charCodeAt(0)
  2562. var idx = findChar(font.chars, id)
  2563. if (idx >= 0)
  2564. return font.chars[idx]
  2565. }
  2566. return 0
  2567. }
  2568. function getCapHeight(font) {
  2569. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  2570. var id = CAP_HEIGHTS[i].charCodeAt(0)
  2571. var idx = findChar(font.chars, id)
  2572. if (idx >= 0)
  2573. return font.chars[idx].height
  2574. }
  2575. return 0
  2576. }
  2577. function getKerning(font, left, right) {
  2578. if (!font.kernings || font.kernings.length === 0)
  2579. return 0
  2580. var table = font.kernings
  2581. for (var i=0; i<table.length; i++) {
  2582. var kern = table[i]
  2583. if (kern.first === left && kern.second === right)
  2584. return kern.amount
  2585. }
  2586. return 0
  2587. }
  2588. function getAlignType(align) {
  2589. if (align === 'center')
  2590. return ALIGN_CENTER
  2591. else if (align === 'right')
  2592. return ALIGN_RIGHT
  2593. return ALIGN_LEFT
  2594. }
  2595. function findChar (array, value, start) {
  2596. start = start || 0
  2597. for (var i = start; i < array.length; i++) {
  2598. if (array[i].id === value) {
  2599. return i
  2600. }
  2601. }
  2602. return -1
  2603. }
  2604. },{"as-number":3,"word-wrapper":47,"xtend":50}],23:[function(_dereq_,module,exports){
  2605. (function (Buffer){
  2606. var xhr = _dereq_('xhr')
  2607. var noop = function(){}
  2608. var parseASCII = _dereq_('parse-bmfont-ascii')
  2609. var parseXML = _dereq_('parse-bmfont-xml')
  2610. var readBinary = _dereq_('parse-bmfont-binary')
  2611. var isBinaryFormat = _dereq_('./lib/is-binary')
  2612. var xtend = _dereq_('xtend')
  2613. var xml2 = (function hasXML2() {
  2614. return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  2615. })()
  2616. module.exports = function(opt, cb) {
  2617. cb = typeof cb === 'function' ? cb : noop
  2618. if (typeof opt === 'string')
  2619. opt = { uri: opt }
  2620. else if (!opt)
  2621. opt = {}
  2622. var expectBinary = opt.binary
  2623. if (expectBinary)
  2624. opt = getBinaryOpts(opt)
  2625. xhr(opt, function(err, res, body) {
  2626. if (err)
  2627. return cb(err)
  2628. if (!/^2/.test(res.statusCode))
  2629. return cb(new Error('http status code: '+res.statusCode))
  2630. if (!body)
  2631. return cb(new Error('no body result'))
  2632. var binary = false
  2633. //if the response type is an array buffer,
  2634. //we need to convert it into a regular Buffer object
  2635. if (isArrayBuffer(body)) {
  2636. var array = new Uint8Array(body)
  2637. body = new Buffer(array, 'binary')
  2638. }
  2639. //now check the string/Buffer response
  2640. //and see if it has a binary BMF header
  2641. if (isBinaryFormat(body)) {
  2642. binary = true
  2643. //if we have a string, turn it into a Buffer
  2644. if (typeof body === 'string')
  2645. body = new Buffer(body, 'binary')
  2646. }
  2647. //we are not parsing a binary format, just ASCII/XML/etc
  2648. if (!binary) {
  2649. //might still be a buffer if responseType is 'arraybuffer'
  2650. if (Buffer.isBuffer(body))
  2651. body = body.toString(opt.encoding)
  2652. body = body.trim()
  2653. }
  2654. var result
  2655. try {
  2656. var type = res.headers['content-type']
  2657. if (binary)
  2658. result = readBinary(body)
  2659. else if (/json/.test(type) || body.charAt(0) === '{')
  2660. result = JSON.parse(body)
  2661. else if (/xml/.test(type) || body.charAt(0) === '<')
  2662. result = parseXML(body)
  2663. else
  2664. result = parseASCII(body)
  2665. } catch (e) {
  2666. cb(new Error('error parsing font '+e.message))
  2667. cb = noop
  2668. }
  2669. cb(null, result)
  2670. })
  2671. }
  2672. function isArrayBuffer(arr) {
  2673. var str = Object.prototype.toString
  2674. return str.call(arr) === '[object ArrayBuffer]'
  2675. }
  2676. function getBinaryOpts(opt) {
  2677. //IE10+ and other modern browsers support array buffers
  2678. if (xml2)
  2679. return xtend(opt, { responseType: 'arraybuffer' })
  2680. if (typeof self.XMLHttpRequest === 'undefined')
  2681. throw new Error('your browser does not support XHR loading')
  2682. //IE9 and XML1 browsers could still use an override
  2683. var req = new self.XMLHttpRequest()
  2684. req.overrideMimeType('text/plain; charset=x-user-defined')
  2685. return xtend({
  2686. xhr: req
  2687. }, opt)
  2688. }
  2689. }).call(this,_dereq_("buffer").Buffer)
  2690. },{"./lib/is-binary":24,"buffer":7,"parse-bmfont-ascii":26,"parse-bmfont-binary":27,"parse-bmfont-xml":28,"xhr":48,"xtend":50}],24:[function(_dereq_,module,exports){
  2691. (function (Buffer){
  2692. var equal = _dereq_('buffer-equal')
  2693. var HEADER = new Buffer([66, 77, 70, 3])
  2694. module.exports = function(buf) {
  2695. if (typeof buf === 'string')
  2696. return buf.substring(0, 3) === 'BMF'
  2697. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  2698. }
  2699. }).call(this,_dereq_("buffer").Buffer)
  2700. },{"buffer":7,"buffer-equal":6}],25:[function(_dereq_,module,exports){
  2701. /*
  2702. object-assign
  2703. (c) Sindre Sorhus
  2704. @license MIT
  2705. */
  2706. 'use strict';
  2707. /* eslint-disable no-unused-vars */
  2708. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  2709. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2710. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2711. function toObject(val) {
  2712. if (val === null || val === undefined) {
  2713. throw new TypeError('Object.assign cannot be called with null or undefined');
  2714. }
  2715. return Object(val);
  2716. }
  2717. function shouldUseNative() {
  2718. try {
  2719. if (!Object.assign) {
  2720. return false;
  2721. }
  2722. // Detect buggy property enumeration order in older V8 versions.
  2723. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  2724. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  2725. test1[5] = 'de';
  2726. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  2727. return false;
  2728. }
  2729. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  2730. var test2 = {};
  2731. for (var i = 0; i < 10; i++) {
  2732. test2['_' + String.fromCharCode(i)] = i;
  2733. }
  2734. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  2735. return test2[n];
  2736. });
  2737. if (order2.join('') !== '0123456789') {
  2738. return false;
  2739. }
  2740. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  2741. var test3 = {};
  2742. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  2743. test3[letter] = letter;
  2744. });
  2745. if (Object.keys(Object.assign({}, test3)).join('') !==
  2746. 'abcdefghijklmnopqrst') {
  2747. return false;
  2748. }
  2749. return true;
  2750. } catch (err) {
  2751. // We don't expect any of the above to throw, but better to be safe.
  2752. return false;
  2753. }
  2754. }
  2755. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  2756. var from;
  2757. var to = toObject(target);
  2758. var symbols;
  2759. for (var s = 1; s < arguments.length; s++) {
  2760. from = Object(arguments[s]);
  2761. for (var key in from) {
  2762. if (hasOwnProperty.call(from, key)) {
  2763. to[key] = from[key];
  2764. }
  2765. }
  2766. if (getOwnPropertySymbols) {
  2767. symbols = getOwnPropertySymbols(from);
  2768. for (var i = 0; i < symbols.length; i++) {
  2769. if (propIsEnumerable.call(from, symbols[i])) {
  2770. to[symbols[i]] = from[symbols[i]];
  2771. }
  2772. }
  2773. }
  2774. }
  2775. return to;
  2776. };
  2777. },{}],26:[function(_dereq_,module,exports){
  2778. module.exports = function parseBMFontAscii(data) {
  2779. if (!data)
  2780. throw new Error('no data provided')
  2781. data = data.toString().trim()
  2782. var output = {
  2783. pages: [],
  2784. chars: [],
  2785. kernings: []
  2786. }
  2787. var lines = data.split(/\r\n?|\n/g)
  2788. if (lines.length === 0)
  2789. throw new Error('no data in BMFont file')
  2790. for (var i = 0; i < lines.length; i++) {
  2791. var lineData = splitLine(lines[i], i)
  2792. if (!lineData) //skip empty lines
  2793. continue
  2794. if (lineData.key === 'page') {
  2795. if (typeof lineData.data.id !== 'number')
  2796. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  2797. if (typeof lineData.data.file !== 'string')
  2798. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  2799. output.pages[lineData.data.id] = lineData.data.file
  2800. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  2801. //... do nothing for these two ...
  2802. } else if (lineData.key === 'char') {
  2803. output.chars.push(lineData.data)
  2804. } else if (lineData.key === 'kerning') {
  2805. output.kernings.push(lineData.data)
  2806. } else {
  2807. output[lineData.key] = lineData.data
  2808. }
  2809. }
  2810. return output
  2811. }
  2812. function splitLine(line, idx) {
  2813. line = line.replace(/\t+/g, ' ').trim()
  2814. if (!line)
  2815. return null
  2816. var space = line.indexOf(' ')
  2817. if (space === -1)
  2818. throw new Error("no named row at line " + idx)
  2819. var key = line.substring(0, space)
  2820. line = line.substring(space + 1)
  2821. //clear "letter" field as it is non-standard and
  2822. //requires additional complexity to parse " / = symbols
  2823. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  2824. line = line.split("=")
  2825. line = line.map(function(str) {
  2826. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  2827. })
  2828. var data = []
  2829. for (var i = 0; i < line.length; i++) {
  2830. var dt = line[i]
  2831. if (i === 0) {
  2832. data.push({
  2833. key: dt[0],
  2834. data: ""
  2835. })
  2836. } else if (i === line.length - 1) {
  2837. data[data.length - 1].data = parseData(dt[0])
  2838. } else {
  2839. data[data.length - 1].data = parseData(dt[0])
  2840. data.push({
  2841. key: dt[1],
  2842. data: ""
  2843. })
  2844. }
  2845. }
  2846. var out = {
  2847. key: key,
  2848. data: {}
  2849. }
  2850. data.forEach(function(v) {
  2851. out.data[v.key] = v.data;
  2852. })
  2853. return out
  2854. }
  2855. function parseData(data) {
  2856. if (!data || data.length === 0)
  2857. return ""
  2858. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  2859. return data.substring(1, data.length - 1)
  2860. if (data.indexOf(',') !== -1)
  2861. return parseIntList(data)
  2862. return parseInt(data, 10)
  2863. }
  2864. function parseIntList(data) {
  2865. return data.split(',').map(function(val) {
  2866. return parseInt(val, 10)
  2867. })
  2868. }
  2869. },{}],27:[function(_dereq_,module,exports){
  2870. var HEADER = [66, 77, 70]
  2871. module.exports = function readBMFontBinary(buf) {
  2872. if (buf.length < 6)
  2873. throw new Error('invalid buffer length for BMFont')
  2874. var header = HEADER.every(function(byte, i) {
  2875. return buf.readUInt8(i) === byte
  2876. })
  2877. if (!header)
  2878. throw new Error('BMFont missing BMF byte header')
  2879. var i = 3
  2880. var vers = buf.readUInt8(i++)
  2881. if (vers > 3)
  2882. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  2883. var target = { kernings: [], chars: [] }
  2884. for (var b=0; b<5; b++)
  2885. i += readBlock(target, buf, i)
  2886. return target
  2887. }
  2888. function readBlock(target, buf, i) {
  2889. if (i > buf.length-1)
  2890. return 0
  2891. var blockID = buf.readUInt8(i++)
  2892. var blockSize = buf.readInt32LE(i)
  2893. i += 4
  2894. switch(blockID) {
  2895. case 1:
  2896. target.info = readInfo(buf, i)
  2897. break
  2898. case 2:
  2899. target.common = readCommon(buf, i)
  2900. break
  2901. case 3:
  2902. target.pages = readPages(buf, i, blockSize)
  2903. break
  2904. case 4:
  2905. target.chars = readChars(buf, i, blockSize)
  2906. break
  2907. case 5:
  2908. target.kernings = readKernings(buf, i, blockSize)
  2909. break
  2910. }
  2911. return 5 + blockSize
  2912. }
  2913. function readInfo(buf, i) {
  2914. var info = {}
  2915. info.size = buf.readInt16LE(i)
  2916. var bitField = buf.readUInt8(i+2)
  2917. info.smooth = (bitField >> 7) & 1
  2918. info.unicode = (bitField >> 6) & 1
  2919. info.italic = (bitField >> 5) & 1
  2920. info.bold = (bitField >> 4) & 1
  2921. //fixedHeight is only mentioned in binary spec
  2922. if ((bitField >> 3) & 1)
  2923. info.fixedHeight = 1
  2924. info.charset = buf.readUInt8(i+3) || ''
  2925. info.stretchH = buf.readUInt16LE(i+4)
  2926. info.aa = buf.readUInt8(i+6)
  2927. info.padding = [
  2928. buf.readInt8(i+7),
  2929. buf.readInt8(i+8),
  2930. buf.readInt8(i+9),
  2931. buf.readInt8(i+10)
  2932. ]
  2933. info.spacing = [
  2934. buf.readInt8(i+11),
  2935. buf.readInt8(i+12)
  2936. ]
  2937. info.outline = buf.readUInt8(i+13)
  2938. info.face = readStringNT(buf, i+14)
  2939. return info
  2940. }
  2941. function readCommon(buf, i) {
  2942. var common = {}
  2943. common.lineHeight = buf.readUInt16LE(i)
  2944. common.base = buf.readUInt16LE(i+2)
  2945. common.scaleW = buf.readUInt16LE(i+4)
  2946. common.scaleH = buf.readUInt16LE(i+6)
  2947. common.pages = buf.readUInt16LE(i+8)
  2948. var bitField = buf.readUInt8(i+10)
  2949. common.packed = 0
  2950. common.alphaChnl = buf.readUInt8(i+11)
  2951. common.redChnl = buf.readUInt8(i+12)
  2952. common.greenChnl = buf.readUInt8(i+13)
  2953. common.blueChnl = buf.readUInt8(i+14)
  2954. return common
  2955. }
  2956. function readPages(buf, i, size) {
  2957. var pages = []
  2958. var text = readNameNT(buf, i)
  2959. var len = text.length+1
  2960. var count = size / len
  2961. for (var c=0; c<count; c++) {
  2962. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  2963. i += len
  2964. }
  2965. return pages
  2966. }
  2967. function readChars(buf, i, blockSize) {
  2968. var chars = []
  2969. var count = blockSize / 20
  2970. for (var c=0; c<count; c++) {
  2971. var char = {}
  2972. var off = c*20
  2973. char.id = buf.readUInt32LE(i + 0 + off)
  2974. char.x = buf.readUInt16LE(i + 4 + off)
  2975. char.y = buf.readUInt16LE(i + 6 + off)
  2976. char.width = buf.readUInt16LE(i + 8 + off)
  2977. char.height = buf.readUInt16LE(i + 10 + off)
  2978. char.xoffset = buf.readInt16LE(i + 12 + off)
  2979. char.yoffset = buf.readInt16LE(i + 14 + off)
  2980. char.xadvance = buf.readInt16LE(i + 16 + off)
  2981. char.page = buf.readUInt8(i + 18 + off)
  2982. char.chnl = buf.readUInt8(i + 19 + off)
  2983. chars[c] = char
  2984. }
  2985. return chars
  2986. }
  2987. function readKernings(buf, i, blockSize) {
  2988. var kernings = []
  2989. var count = blockSize / 10
  2990. for (var c=0; c<count; c++) {
  2991. var kern = {}
  2992. var off = c*10
  2993. kern.first = buf.readUInt32LE(i + 0 + off)
  2994. kern.second = buf.readUInt32LE(i + 4 + off)
  2995. kern.amount = buf.readInt16LE(i + 8 + off)
  2996. kernings[c] = kern
  2997. }
  2998. return kernings
  2999. }
  3000. function readNameNT(buf, offset) {
  3001. var pos=offset
  3002. for (; pos<buf.length; pos++) {
  3003. if (buf[pos] === 0x00)
  3004. break
  3005. }
  3006. return buf.slice(offset, pos)
  3007. }
  3008. function readStringNT(buf, offset) {
  3009. return readNameNT(buf, offset).toString('utf8')
  3010. }
  3011. },{}],28:[function(_dereq_,module,exports){
  3012. var parseAttributes = _dereq_('./parse-attribs')
  3013. var parseFromString = _dereq_('xml-parse-from-string')
  3014. //In some cases element.attribute.nodeName can return
  3015. //all lowercase values.. so we need to map them to the correct
  3016. //case
  3017. var NAME_MAP = {
  3018. scaleh: 'scaleH',
  3019. scalew: 'scaleW',
  3020. stretchh: 'stretchH',
  3021. lineheight: 'lineHeight',
  3022. alphachnl: 'alphaChnl',
  3023. redchnl: 'redChnl',
  3024. greenchnl: 'greenChnl',
  3025. bluechnl: 'blueChnl'
  3026. }
  3027. module.exports = function parse(data) {
  3028. data = data.toString()
  3029. var xmlRoot = parseFromString(data)
  3030. var output = {
  3031. pages: [],
  3032. chars: [],
  3033. kernings: []
  3034. }
  3035. //get config settings
  3036. ;['info', 'common'].forEach(function(key) {
  3037. var element = xmlRoot.getElementsByTagName(key)[0]
  3038. if (element)
  3039. output[key] = parseAttributes(getAttribs(element))
  3040. })
  3041. //get page info
  3042. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3043. if (!pageRoot)
  3044. throw new Error('malformed file -- no <pages> element')
  3045. var pages = pageRoot.getElementsByTagName('page')
  3046. for (var i=0; i<pages.length; i++) {
  3047. var p = pages[i]
  3048. var id = parseInt(p.getAttribute('id'), 10)
  3049. var file = p.getAttribute('file')
  3050. if (isNaN(id))
  3051. throw new Error('malformed file -- page "id" attribute is NaN')
  3052. if (!file)
  3053. throw new Error('malformed file -- needs page "file" attribute')
  3054. output.pages[parseInt(id, 10)] = file
  3055. }
  3056. //get kernings / chars
  3057. ;['chars', 'kernings'].forEach(function(key) {
  3058. var element = xmlRoot.getElementsByTagName(key)[0]
  3059. if (!element)
  3060. return
  3061. var childTag = key.substring(0, key.length-1)
  3062. var children = element.getElementsByTagName(childTag)
  3063. for (var i=0; i<children.length; i++) {
  3064. var child = children[i]
  3065. output[key].push(parseAttributes(getAttribs(child)))
  3066. }
  3067. })
  3068. return output
  3069. }
  3070. function getAttribs(element) {
  3071. var attribs = getAttribList(element)
  3072. return attribs.reduce(function(dict, attrib) {
  3073. var key = mapName(attrib.nodeName)
  3074. dict[key] = attrib.nodeValue
  3075. return dict
  3076. }, {})
  3077. }
  3078. function getAttribList(element) {
  3079. //IE8+ and modern browsers
  3080. var attribs = []
  3081. for (var i=0; i<element.attributes.length; i++)
  3082. attribs.push(element.attributes[i])
  3083. return attribs
  3084. }
  3085. function mapName(nodeName) {
  3086. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3087. }
  3088. },{"./parse-attribs":29,"xml-parse-from-string":49}],29:[function(_dereq_,module,exports){
  3089. //Some versions of GlyphDesigner have a typo
  3090. //that causes some bugs with parsing.
  3091. //Need to confirm with recent version of the software
  3092. //to see whether this is still an issue or not.
  3093. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3094. module.exports = function parseAttributes(obj) {
  3095. if (GLYPH_DESIGNER_ERROR in obj) {
  3096. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3097. delete obj[GLYPH_DESIGNER_ERROR]
  3098. }
  3099. for (var k in obj) {
  3100. if (k === 'face' || k === 'charset')
  3101. continue
  3102. else if (k === 'padding' || k === 'spacing')
  3103. obj[k] = parseIntList(obj[k])
  3104. else
  3105. obj[k] = parseInt(obj[k], 10)
  3106. }
  3107. return obj
  3108. }
  3109. function parseIntList(data) {
  3110. return data.split(',').map(function(val) {
  3111. return parseInt(val, 10)
  3112. })
  3113. }
  3114. },{}],30:[function(_dereq_,module,exports){
  3115. var trim = _dereq_('trim')
  3116. , forEach = _dereq_('for-each')
  3117. , isArray = function(arg) {
  3118. return Object.prototype.toString.call(arg) === '[object Array]';
  3119. }
  3120. module.exports = function (headers) {
  3121. if (!headers)
  3122. return {}
  3123. var result = {}
  3124. forEach(
  3125. trim(headers).split('\n')
  3126. , function (row) {
  3127. var index = row.indexOf(':')
  3128. , key = trim(row.slice(0, index)).toLowerCase()
  3129. , value = trim(row.slice(index + 1))
  3130. if (typeof(result[key]) === 'undefined') {
  3131. result[key] = value
  3132. } else if (isArray(result[key])) {
  3133. result[key].push(value)
  3134. } else {
  3135. result[key] = [ result[key], value ]
  3136. }
  3137. }
  3138. )
  3139. return result
  3140. }
  3141. },{"for-each":14,"trim":45}],31:[function(_dereq_,module,exports){
  3142. (function (global){
  3143. var performance = global.performance || {};
  3144. var present = (function () {
  3145. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3146. while (names.length) {
  3147. var name = names.shift();
  3148. if (name in performance) {
  3149. return performance[name].bind(performance);
  3150. }
  3151. }
  3152. var dateNow = Date.now || function () { return new Date().getTime(); };
  3153. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3154. return function () {
  3155. return dateNow() - navigationStart;
  3156. };
  3157. }());
  3158. present.performanceNow = performance.now;
  3159. present.noConflict = function () {
  3160. performance.now = present.performanceNow;
  3161. };
  3162. present.conflict = function () {
  3163. performance.now = present;
  3164. };
  3165. present.conflict();
  3166. module.exports = present;
  3167. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3168. },{}],32:[function(_dereq_,module,exports){
  3169. // shim for using process in browser
  3170. var process = module.exports = {};
  3171. // cached from whatever global is present so that test runners that stub it
  3172. // don't break things. But we need to wrap it in a try catch in case it is
  3173. // wrapped in strict mode code which doesn't define any globals. It's inside a
  3174. // function because try/catches deoptimize in certain engines.
  3175. var cachedSetTimeout;
  3176. var cachedClearTimeout;
  3177. function defaultSetTimout() {
  3178. throw new Error('setTimeout has not been defined');
  3179. }
  3180. function defaultClearTimeout () {
  3181. throw new Error('clearTimeout has not been defined');
  3182. }
  3183. (function () {
  3184. try {
  3185. if (typeof setTimeout === 'function') {
  3186. cachedSetTimeout = setTimeout;
  3187. } else {
  3188. cachedSetTimeout = defaultSetTimout;
  3189. }
  3190. } catch (e) {
  3191. cachedSetTimeout = defaultSetTimout;
  3192. }
  3193. try {
  3194. if (typeof clearTimeout === 'function') {
  3195. cachedClearTimeout = clearTimeout;
  3196. } else {
  3197. cachedClearTimeout = defaultClearTimeout;
  3198. }
  3199. } catch (e) {
  3200. cachedClearTimeout = defaultClearTimeout;
  3201. }
  3202. } ())
  3203. function runTimeout(fun) {
  3204. if (cachedSetTimeout === setTimeout) {
  3205. //normal enviroments in sane situations
  3206. return setTimeout(fun, 0);
  3207. }
  3208. // if setTimeout wasn't available but was latter defined
  3209. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  3210. cachedSetTimeout = setTimeout;
  3211. return setTimeout(fun, 0);
  3212. }
  3213. try {
  3214. // when when somebody has screwed with setTimeout but no I.E. maddness
  3215. return cachedSetTimeout(fun, 0);
  3216. } catch(e){
  3217. try {
  3218. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3219. return cachedSetTimeout.call(null, fun, 0);
  3220. } catch(e){
  3221. // 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
  3222. return cachedSetTimeout.call(this, fun, 0);
  3223. }
  3224. }
  3225. }
  3226. function runClearTimeout(marker) {
  3227. if (cachedClearTimeout === clearTimeout) {
  3228. //normal enviroments in sane situations
  3229. return clearTimeout(marker);
  3230. }
  3231. // if clearTimeout wasn't available but was latter defined
  3232. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3233. cachedClearTimeout = clearTimeout;
  3234. return clearTimeout(marker);
  3235. }
  3236. try {
  3237. // when when somebody has screwed with setTimeout but no I.E. maddness
  3238. return cachedClearTimeout(marker);
  3239. } catch (e){
  3240. try {
  3241. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3242. return cachedClearTimeout.call(null, marker);
  3243. } catch (e){
  3244. // 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.
  3245. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  3246. return cachedClearTimeout.call(this, marker);
  3247. }
  3248. }
  3249. }
  3250. var queue = [];
  3251. var draining = false;
  3252. var currentQueue;
  3253. var queueIndex = -1;
  3254. function cleanUpNextTick() {
  3255. if (!draining || !currentQueue) {
  3256. return;
  3257. }
  3258. draining = false;
  3259. if (currentQueue.length) {
  3260. queue = currentQueue.concat(queue);
  3261. } else {
  3262. queueIndex = -1;
  3263. }
  3264. if (queue.length) {
  3265. drainQueue();
  3266. }
  3267. }
  3268. function drainQueue() {
  3269. if (draining) {
  3270. return;
  3271. }
  3272. var timeout = runTimeout(cleanUpNextTick);
  3273. draining = true;
  3274. var len = queue.length;
  3275. while(len) {
  3276. currentQueue = queue;
  3277. queue = [];
  3278. while (++queueIndex < len) {
  3279. if (currentQueue) {
  3280. currentQueue[queueIndex].run();
  3281. }
  3282. }
  3283. queueIndex = -1;
  3284. len = queue.length;
  3285. }
  3286. currentQueue = null;
  3287. draining = false;
  3288. runClearTimeout(timeout);
  3289. }
  3290. process.nextTick = function (fun) {
  3291. var args = new Array(arguments.length - 1);
  3292. if (arguments.length > 1) {
  3293. for (var i = 1; i < arguments.length; i++) {
  3294. args[i - 1] = arguments[i];
  3295. }
  3296. }
  3297. queue.push(new Item(fun, args));
  3298. if (queue.length === 1 && !draining) {
  3299. runTimeout(drainQueue);
  3300. }
  3301. };
  3302. // v8 likes predictible objects
  3303. function Item(fun, array) {
  3304. this.fun = fun;
  3305. this.array = array;
  3306. }
  3307. Item.prototype.run = function () {
  3308. this.fun.apply(null, this.array);
  3309. };
  3310. process.title = 'browser';
  3311. process.browser = true;
  3312. process.env = {};
  3313. process.argv = [];
  3314. process.version = ''; // empty string to avoid regexp issues
  3315. process.versions = {};
  3316. function noop() {}
  3317. process.on = noop;
  3318. process.addListener = noop;
  3319. process.once = noop;
  3320. process.off = noop;
  3321. process.removeListener = noop;
  3322. process.removeAllListeners = noop;
  3323. process.emit = noop;
  3324. process.prependListener = noop;
  3325. process.prependOnceListener = noop;
  3326. process.listeners = function (name) { return [] }
  3327. process.binding = function (name) {
  3328. throw new Error('process.binding is not supported');
  3329. };
  3330. process.cwd = function () { return '/' };
  3331. process.chdir = function (dir) {
  3332. throw new Error('process.chdir is not supported');
  3333. };
  3334. process.umask = function() { return 0; };
  3335. },{}],33:[function(_dereq_,module,exports){
  3336. (function(root) {
  3337. // Store setTimeout reference so promise-polyfill will be unaffected by
  3338. // other code modifying setTimeout (like sinon.useFakeTimers())
  3339. var setTimeoutFunc = setTimeout;
  3340. // Use polyfill for setImmediate for performance gains
  3341. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  3342. function(fn) { setTimeoutFunc(fn, 1); };
  3343. // Polyfill for Function.prototype.bind
  3344. function bind(fn, thisArg) {
  3345. return function() {
  3346. fn.apply(thisArg, arguments);
  3347. }
  3348. }
  3349. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  3350. function Promise(fn) {
  3351. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  3352. if (typeof fn !== 'function') throw new TypeError('not a function');
  3353. this._state = null;
  3354. this._value = null;
  3355. this._deferreds = []
  3356. doResolve(fn, bind(resolve, this), bind(reject, this))
  3357. }
  3358. function handle(deferred) {
  3359. var me = this;
  3360. if (this._state === null) {
  3361. this._deferreds.push(deferred);
  3362. return
  3363. }
  3364. asap(function() {
  3365. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  3366. if (cb === null) {
  3367. (me._state ? deferred.resolve : deferred.reject)(me._value);
  3368. return;
  3369. }
  3370. var ret;
  3371. try {
  3372. ret = cb(me._value);
  3373. }
  3374. catch (e) {
  3375. deferred.reject(e);
  3376. return;
  3377. }
  3378. deferred.resolve(ret);
  3379. })
  3380. }
  3381. function resolve(newValue) {
  3382. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  3383. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  3384. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  3385. var then = newValue.then;
  3386. if (typeof then === 'function') {
  3387. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  3388. return;
  3389. }
  3390. }
  3391. this._state = true;
  3392. this._value = newValue;
  3393. finale.call(this);
  3394. } catch (e) { reject.call(this, e); }
  3395. }
  3396. function reject(newValue) {
  3397. this._state = false;
  3398. this._value = newValue;
  3399. finale.call(this);
  3400. }
  3401. function finale() {
  3402. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  3403. handle.call(this, this._deferreds[i]);
  3404. }
  3405. this._deferreds = null;
  3406. }
  3407. function Handler(onFulfilled, onRejected, resolve, reject){
  3408. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  3409. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  3410. this.resolve = resolve;
  3411. this.reject = reject;
  3412. }
  3413. /**
  3414. * Take a potentially misbehaving resolver function and make sure
  3415. * onFulfilled and onRejected are only called once.
  3416. *
  3417. * Makes no guarantees about asynchrony.
  3418. */
  3419. function doResolve(fn, onFulfilled, onRejected) {
  3420. var done = false;
  3421. try {
  3422. fn(function (value) {
  3423. if (done) return;
  3424. done = true;
  3425. onFulfilled(value);
  3426. }, function (reason) {
  3427. if (done) return;
  3428. done = true;
  3429. onRejected(reason);
  3430. })
  3431. } catch (ex) {
  3432. if (done) return;
  3433. done = true;
  3434. onRejected(ex);
  3435. }
  3436. }
  3437. Promise.prototype['catch'] = function (onRejected) {
  3438. return this.then(null, onRejected);
  3439. };
  3440. Promise.prototype.then = function(onFulfilled, onRejected) {
  3441. var me = this;
  3442. return new Promise(function(resolve, reject) {
  3443. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  3444. })
  3445. };
  3446. Promise.all = function () {
  3447. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  3448. return new Promise(function (resolve, reject) {
  3449. if (args.length === 0) return resolve([]);
  3450. var remaining = args.length;
  3451. function res(i, val) {
  3452. try {
  3453. if (val && (typeof val === 'object' || typeof val === 'function')) {
  3454. var then = val.then;
  3455. if (typeof then === 'function') {
  3456. then.call(val, function (val) { res(i, val) }, reject);
  3457. return;
  3458. }
  3459. }
  3460. args[i] = val;
  3461. if (--remaining === 0) {
  3462. resolve(args);
  3463. }
  3464. } catch (ex) {
  3465. reject(ex);
  3466. }
  3467. }
  3468. for (var i = 0; i < args.length; i++) {
  3469. res(i, args[i]);
  3470. }
  3471. });
  3472. };
  3473. Promise.resolve = function (value) {
  3474. if (value && typeof value === 'object' && value.constructor === Promise) {
  3475. return value;
  3476. }
  3477. return new Promise(function (resolve) {
  3478. resolve(value);
  3479. });
  3480. };
  3481. Promise.reject = function (value) {
  3482. return new Promise(function (resolve, reject) {
  3483. reject(value);
  3484. });
  3485. };
  3486. Promise.race = function (values) {
  3487. return new Promise(function (resolve, reject) {
  3488. for(var i = 0, len = values.length; i < len; i++) {
  3489. values[i].then(resolve, reject);
  3490. }
  3491. });
  3492. };
  3493. /**
  3494. * Set the immediate function to execute callbacks
  3495. * @param fn {function} Function to execute
  3496. * @private
  3497. */
  3498. Promise._setImmediateFn = function _setImmediateFn(fn) {
  3499. asap = fn;
  3500. };
  3501. if (typeof module !== 'undefined' && module.exports) {
  3502. module.exports = Promise;
  3503. } else if (!root.Promise) {
  3504. root.Promise = Promise;
  3505. }
  3506. })(this);
  3507. },{}],34:[function(_dereq_,module,exports){
  3508. var dtype = _dereq_('dtype')
  3509. var anArray = _dereq_('an-array')
  3510. var isBuffer = _dereq_('is-buffer')
  3511. var CW = [0, 2, 3]
  3512. var CCW = [2, 1, 3]
  3513. module.exports = function createQuadElements(array, opt) {
  3514. //if user didn't specify an output array
  3515. if (!array || !(anArray(array) || isBuffer(array))) {
  3516. opt = array || {}
  3517. array = null
  3518. }
  3519. if (typeof opt === 'number') //backwards-compatible
  3520. opt = { count: opt }
  3521. else
  3522. opt = opt || {}
  3523. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  3524. var count = typeof opt.count === 'number' ? opt.count : 1
  3525. var start = (opt.start || 0)
  3526. var dir = opt.clockwise !== false ? CW : CCW,
  3527. a = dir[0],
  3528. b = dir[1],
  3529. c = dir[2]
  3530. var numIndices = count * 6
  3531. var indices = array || new (dtype(type))(numIndices)
  3532. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  3533. var x = i + start
  3534. indices[x + 0] = j + 0
  3535. indices[x + 1] = j + 1
  3536. indices[x + 2] = j + 2
  3537. indices[x + 3] = j + a
  3538. indices[x + 4] = j + b
  3539. indices[x + 5] = j + c
  3540. }
  3541. return indices
  3542. }
  3543. },{"an-array":1,"dtype":12,"is-buffer":18}],35:[function(_dereq_,module,exports){
  3544. /*:: type Attr = { [key: string]: string | number } */
  3545. /*:: type Opts = { preserveNumbers: ?boolean } */
  3546. /*
  3547. style-attr
  3548. ====
  3549. Very simple parsing and stringifying of style attributes.
  3550. `parse`
  3551. ----
  3552. Convert a style attribute string to an object.
  3553. */
  3554. /*:: declare function parse (raw: string, opts: ?Opts): Attr */
  3555. function parse(raw, opts) {
  3556. opts = opts || {};
  3557. var preserveNumbers = opts.preserveNumbers;
  3558. var trim = function (s) {
  3559. return s.trim();
  3560. };
  3561. var obj = {};
  3562. getKeyValueChunks(raw).map(trim).filter(Boolean).forEach(function (item) {
  3563. // split with `.indexOf` rather than `.split` because the value may also contain colons.
  3564. var pos = item.indexOf(':');
  3565. var key = item.substr(0, pos).trim();
  3566. var val = item.substr(pos + 1).trim();
  3567. if (preserveNumbers && isNumeric(val)) {
  3568. val = Number(val);
  3569. }
  3570. obj[key] = val;
  3571. });
  3572. return obj;
  3573. }
  3574. /*
  3575. `isNumeric`
  3576. ----
  3577. Check if a value is numeric.
  3578. Via: https://stackoverflow.com/a/1830844/9324
  3579. */
  3580. /*:: declare function isNumeric (n: any): boolean */
  3581. function isNumeric(n) {
  3582. return !isNaN(parseFloat(n)) && isFinite(n);
  3583. }
  3584. /*
  3585. `getKeyValueChunks`
  3586. ----
  3587. Split a string into chunks matching `<key>: <value>`
  3588. */
  3589. /*:: declare function getKeyValueChunks (raw: string): Array<string> */
  3590. function getKeyValueChunks(raw) {
  3591. var chunks = [];
  3592. var offset = 0;
  3593. var sep = ';';
  3594. var hasUnclosedUrl = /url\([^\)]+$/;
  3595. var chunk = '';
  3596. var nextSplit;
  3597. while (offset < raw.length) {
  3598. nextSplit = raw.indexOf(sep, offset);
  3599. if (nextSplit === -1) {
  3600. nextSplit = raw.length;
  3601. }
  3602. chunk += raw.substring(offset, nextSplit);
  3603. // data URIs can contain semicolons, so make sure we get the whole thing
  3604. if (hasUnclosedUrl.test(chunk)) {
  3605. chunk += ';';
  3606. offset = nextSplit + 1;
  3607. continue;
  3608. }
  3609. chunks.push(chunk);
  3610. chunk = '';
  3611. offset = nextSplit + 1;
  3612. }
  3613. return chunks;
  3614. }
  3615. /*
  3616. `stringify`
  3617. ----
  3618. Convert an object into an attribute string
  3619. */
  3620. /*:: declare function stringify (obj: Attr): string */
  3621. function stringify(obj) {
  3622. return Object.keys(obj).map(function (key) {
  3623. return key + ':' + obj[key];
  3624. }).join(';');
  3625. }
  3626. /*
  3627. `normalize`
  3628. ----
  3629. Normalize an attribute string (eg. collapse duplicates)
  3630. */
  3631. /*:: declare function normalize (str: string, opts: ?Opts): string */
  3632. function normalize(str, opts) {
  3633. return stringify(parse(str, opts));
  3634. }
  3635. module.exports.parse = parse;
  3636. module.exports.stringify = stringify;
  3637. module.exports.normalize = normalize;
  3638. },{}],36:[function(_dereq_,module,exports){
  3639. var createLayout = _dereq_('layout-bmfont-text')
  3640. var inherits = _dereq_('inherits')
  3641. var createIndices = _dereq_('quad-indices')
  3642. var buffer = _dereq_('three-buffer-vertex-data')
  3643. var assign = _dereq_('object-assign')
  3644. var vertices = _dereq_('./lib/vertices')
  3645. var utils = _dereq_('./lib/utils')
  3646. var Base = THREE.BufferGeometry
  3647. module.exports = function createTextGeometry (opt) {
  3648. return new TextGeometry(opt)
  3649. }
  3650. function TextGeometry (opt) {
  3651. Base.call(this)
  3652. if (typeof opt === 'string') {
  3653. opt = { text: opt }
  3654. }
  3655. // use these as default values for any subsequent
  3656. // calls to update()
  3657. this._opt = assign({}, opt)
  3658. // also do an initial setup...
  3659. if (opt) this.update(opt)
  3660. }
  3661. inherits(TextGeometry, Base)
  3662. TextGeometry.prototype.update = function (opt) {
  3663. if (typeof opt === 'string') {
  3664. opt = { text: opt }
  3665. }
  3666. // use constructor defaults
  3667. opt = assign({}, this._opt, opt)
  3668. if (!opt.font) {
  3669. throw new TypeError('must specify a { font } in options')
  3670. }
  3671. this.layout = createLayout(opt)
  3672. // get vec2 texcoords
  3673. var flipY = opt.flipY !== false
  3674. // the desired BMFont data
  3675. var font = opt.font
  3676. // determine texture size from font file
  3677. var texWidth = font.common.scaleW
  3678. var texHeight = font.common.scaleH
  3679. // get visible glyphs
  3680. var glyphs = this.layout.glyphs.filter(function (glyph) {
  3681. var bitmap = glyph.data
  3682. return bitmap.width * bitmap.height > 0
  3683. })
  3684. // provide visible glyphs for convenience
  3685. this.visibleGlyphs = glyphs
  3686. // get common vertex data
  3687. var positions = vertices.positions(glyphs)
  3688. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  3689. var indices = createIndices({
  3690. clockwise: true,
  3691. type: 'uint16',
  3692. count: glyphs.length
  3693. })
  3694. // update vertex data
  3695. buffer.index(this, indices, 1, 'uint16')
  3696. buffer.attr(this, 'position', positions, 2)
  3697. buffer.attr(this, 'uv', uvs, 2)
  3698. // update multipage data
  3699. if (!opt.multipage && 'page' in this.attributes) {
  3700. // disable multipage rendering
  3701. this.removeAttribute('page')
  3702. } else if (opt.multipage) {
  3703. var pages = vertices.pages(glyphs)
  3704. // enable multipage rendering
  3705. buffer.attr(this, 'page', pages, 1)
  3706. }
  3707. }
  3708. TextGeometry.prototype.computeBoundingSphere = function () {
  3709. if (this.boundingSphere === null) {
  3710. this.boundingSphere = new THREE.Sphere()
  3711. }
  3712. var positions = this.attributes.position.array
  3713. var itemSize = this.attributes.position.itemSize
  3714. if (!positions || !itemSize || positions.length < 2) {
  3715. this.boundingSphere.radius = 0
  3716. this.boundingSphere.center.set(0, 0, 0)
  3717. return
  3718. }
  3719. utils.computeSphere(positions, this.boundingSphere)
  3720. if (isNaN(this.boundingSphere.radius)) {
  3721. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  3722. 'Computed radius is NaN. The ' +
  3723. '"position" attribute is likely to have NaN values.')
  3724. }
  3725. }
  3726. TextGeometry.prototype.computeBoundingBox = function () {
  3727. if (this.boundingBox === null) {
  3728. this.boundingBox = new THREE.Box3()
  3729. }
  3730. var bbox = this.boundingBox
  3731. var positions = this.attributes.position.array
  3732. var itemSize = this.attributes.position.itemSize
  3733. if (!positions || !itemSize || positions.length < 2) {
  3734. bbox.makeEmpty()
  3735. return
  3736. }
  3737. utils.computeBox(positions, bbox)
  3738. }
  3739. },{"./lib/utils":37,"./lib/vertices":38,"inherits":17,"layout-bmfont-text":22,"object-assign":25,"quad-indices":34,"three-buffer-vertex-data":39}],37:[function(_dereq_,module,exports){
  3740. var itemSize = 2
  3741. var box = { min: [0, 0], max: [0, 0] }
  3742. function bounds (positions) {
  3743. var count = positions.length / itemSize
  3744. box.min[0] = positions[0]
  3745. box.min[1] = positions[1]
  3746. box.max[0] = positions[0]
  3747. box.max[1] = positions[1]
  3748. for (var i = 0; i < count; i++) {
  3749. var x = positions[i * itemSize + 0]
  3750. var y = positions[i * itemSize + 1]
  3751. box.min[0] = Math.min(x, box.min[0])
  3752. box.min[1] = Math.min(y, box.min[1])
  3753. box.max[0] = Math.max(x, box.max[0])
  3754. box.max[1] = Math.max(y, box.max[1])
  3755. }
  3756. }
  3757. module.exports.computeBox = function (positions, output) {
  3758. bounds(positions)
  3759. output.min.set(box.min[0], box.min[1], 0)
  3760. output.max.set(box.max[0], box.max[1], 0)
  3761. }
  3762. module.exports.computeSphere = function (positions, output) {
  3763. bounds(positions)
  3764. var minX = box.min[0]
  3765. var minY = box.min[1]
  3766. var maxX = box.max[0]
  3767. var maxY = box.max[1]
  3768. var width = maxX - minX
  3769. var height = maxY - minY
  3770. var length = Math.sqrt(width * width + height * height)
  3771. output.center.set(minX + width / 2, minY + height / 2, 0)
  3772. output.radius = length / 2
  3773. }
  3774. },{}],38:[function(_dereq_,module,exports){
  3775. module.exports.pages = function pages (glyphs) {
  3776. var pages = new Float32Array(glyphs.length * 4 * 1)
  3777. var i = 0
  3778. glyphs.forEach(function (glyph) {
  3779. var id = glyph.data.page || 0
  3780. pages[i++] = id
  3781. pages[i++] = id
  3782. pages[i++] = id
  3783. pages[i++] = id
  3784. })
  3785. return pages
  3786. }
  3787. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  3788. var uvs = new Float32Array(glyphs.length * 4 * 2)
  3789. var i = 0
  3790. glyphs.forEach(function (glyph) {
  3791. var bitmap = glyph.data
  3792. var bw = (bitmap.x + bitmap.width)
  3793. var bh = (bitmap.y + bitmap.height)
  3794. // top left position
  3795. var u0 = bitmap.x / texWidth
  3796. var v1 = bitmap.y / texHeight
  3797. var u1 = bw / texWidth
  3798. var v0 = bh / texHeight
  3799. if (flipY) {
  3800. v1 = (texHeight - bitmap.y) / texHeight
  3801. v0 = (texHeight - bh) / texHeight
  3802. }
  3803. // BL
  3804. uvs[i++] = u0
  3805. uvs[i++] = v1
  3806. // TL
  3807. uvs[i++] = u0
  3808. uvs[i++] = v0
  3809. // TR
  3810. uvs[i++] = u1
  3811. uvs[i++] = v0
  3812. // BR
  3813. uvs[i++] = u1
  3814. uvs[i++] = v1
  3815. })
  3816. return uvs
  3817. }
  3818. module.exports.positions = function positions (glyphs) {
  3819. var positions = new Float32Array(glyphs.length * 4 * 2)
  3820. var i = 0
  3821. glyphs.forEach(function (glyph) {
  3822. var bitmap = glyph.data
  3823. // bottom left position
  3824. var x = glyph.position[0] + bitmap.xoffset
  3825. var y = glyph.position[1] + bitmap.yoffset
  3826. // quad size
  3827. var w = bitmap.width
  3828. var h = bitmap.height
  3829. // BL
  3830. positions[i++] = x
  3831. positions[i++] = y
  3832. // TL
  3833. positions[i++] = x
  3834. positions[i++] = y + h
  3835. // TR
  3836. positions[i++] = x + w
  3837. positions[i++] = y + h
  3838. // BR
  3839. positions[i++] = x + w
  3840. positions[i++] = y
  3841. })
  3842. return positions
  3843. }
  3844. },{}],39:[function(_dereq_,module,exports){
  3845. var flatten = _dereq_('flatten-vertex-data')
  3846. var warned = false;
  3847. module.exports.attr = setAttribute
  3848. module.exports.index = setIndex
  3849. function setIndex (geometry, data, itemSize, dtype) {
  3850. if (typeof itemSize !== 'number') itemSize = 1
  3851. if (typeof dtype !== 'string') dtype = 'uint16'
  3852. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  3853. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  3854. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  3855. if (newAttrib) {
  3856. if (isR69) geometry.addAttribute('index', newAttrib)
  3857. else geometry.index = newAttrib
  3858. }
  3859. }
  3860. function setAttribute (geometry, key, data, itemSize, dtype) {
  3861. if (typeof itemSize !== 'number') itemSize = 3
  3862. if (typeof dtype !== 'string') dtype = 'float32'
  3863. if (Array.isArray(data) &&
  3864. Array.isArray(data[0]) &&
  3865. data[0].length !== itemSize) {
  3866. throw new Error('Nested vertex array has unexpected size; expected ' +
  3867. itemSize + ' but found ' + data[0].length)
  3868. }
  3869. var attrib = geometry.getAttribute(key)
  3870. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  3871. if (newAttrib) {
  3872. geometry.addAttribute(key, newAttrib)
  3873. }
  3874. }
  3875. function updateAttribute (attrib, data, itemSize, dtype) {
  3876. data = data || []
  3877. if (!attrib || rebuildAttribute(attrib, data, itemSize)) {
  3878. // create a new array with desired type
  3879. data = flatten(data, dtype)
  3880. var needsNewBuffer = attrib && typeof attrib.setArray !== 'function'
  3881. if (!attrib || needsNewBuffer) {
  3882. // We are on an old version of ThreeJS which can't
  3883. // support growing / shrinking buffers, so we need
  3884. // to build a new buffer
  3885. if (needsNewBuffer && !warned) {
  3886. warned = true
  3887. console.warn([
  3888. 'A WebGL buffer is being updated with a new size or itemSize, ',
  3889. 'however this version of ThreeJS only supports fixed-size buffers.',
  3890. '\nThe old buffer may still be kept in memory.\n',
  3891. 'To avoid memory leaks, it is recommended that you dispose ',
  3892. 'your geometries and create new ones, or update to ThreeJS r82 or newer.\n',
  3893. 'See here for discussion:\n',
  3894. 'https://github.com/mrdoob/three.js/pull/9631'
  3895. ].join(''))
  3896. }
  3897. // Build a new attribute
  3898. attrib = new THREE.BufferAttribute(data, itemSize);
  3899. }
  3900. attrib.itemSize = itemSize
  3901. attrib.needsUpdate = true
  3902. // New versions of ThreeJS suggest using setArray
  3903. // to change the data. It will use bufferData internally,
  3904. // so you can change the array size without any issues
  3905. if (typeof attrib.setArray === 'function') {
  3906. attrib.setArray(data)
  3907. }
  3908. return attrib
  3909. } else {
  3910. // copy data into the existing array
  3911. flatten(data, attrib.array)
  3912. attrib.needsUpdate = true
  3913. return null
  3914. }
  3915. }
  3916. // Test whether the attribute needs to be re-created,
  3917. // returns false if we can re-use it as-is.
  3918. function rebuildAttribute (attrib, data, itemSize) {
  3919. if (attrib.itemSize !== itemSize) return true
  3920. if (!attrib.array) return true
  3921. var attribLength = attrib.array.length
  3922. if (Array.isArray(data) && Array.isArray(data[0])) {
  3923. // [ [ x, y, z ] ]
  3924. return attribLength !== data.length * itemSize
  3925. } else {
  3926. // [ x, y, z ]
  3927. return attribLength !== data.length
  3928. }
  3929. return false
  3930. }
  3931. },{"flatten-vertex-data":13}],40:[function(_dereq_,module,exports){
  3932. (function (global, factory) {
  3933. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3934. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  3935. (factory((global.THREE = {})));
  3936. }(this, (function (exports) { 'use strict';
  3937. // Polyfills
  3938. if ( Number.EPSILON === undefined ) {
  3939. Number.EPSILON = Math.pow( 2, - 52 );
  3940. }
  3941. if ( Number.isInteger === undefined ) {
  3942. // Missing in IE
  3943. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  3944. Number.isInteger = function ( value ) {
  3945. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  3946. };
  3947. }
  3948. //
  3949. if ( Math.sign === undefined ) {
  3950. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  3951. Math.sign = function ( x ) {
  3952. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  3953. };
  3954. }
  3955. if ( 'name' in Function.prototype === false ) {
  3956. // Missing in IE
  3957. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  3958. Object.defineProperty( Function.prototype, 'name', {
  3959. get: function () {
  3960. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  3961. }
  3962. } );
  3963. }
  3964. if ( Object.assign === undefined ) {
  3965. // Missing in IE
  3966. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  3967. ( function () {
  3968. Object.assign = function ( target ) {
  3969. if ( target === undefined || target === null ) {
  3970. throw new TypeError( 'Cannot convert undefined or null to object' );
  3971. }
  3972. var output = Object( target );
  3973. for ( var index = 1; index < arguments.length; index ++ ) {
  3974. var source = arguments[ index ];
  3975. if ( source !== undefined && source !== null ) {
  3976. for ( var nextKey in source ) {
  3977. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  3978. output[ nextKey ] = source[ nextKey ];
  3979. }
  3980. }
  3981. }
  3982. }
  3983. return output;
  3984. };
  3985. } )();
  3986. }
  3987. /**
  3988. * https://github.com/mrdoob/eventdispatcher.js/
  3989. */
  3990. function EventDispatcher() {}
  3991. Object.assign( EventDispatcher.prototype, {
  3992. addEventListener: function ( type, listener ) {
  3993. if ( this._listeners === undefined ) this._listeners = {};
  3994. var listeners = this._listeners;
  3995. if ( listeners[ type ] === undefined ) {
  3996. listeners[ type ] = [];
  3997. }
  3998. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3999. listeners[ type ].push( listener );
  4000. }
  4001. },
  4002. hasEventListener: function ( type, listener ) {
  4003. if ( this._listeners === undefined ) return false;
  4004. var listeners = this._listeners;
  4005. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  4006. },
  4007. removeEventListener: function ( type, listener ) {
  4008. if ( this._listeners === undefined ) return;
  4009. var listeners = this._listeners;
  4010. var listenerArray = listeners[ type ];
  4011. if ( listenerArray !== undefined ) {
  4012. var index = listenerArray.indexOf( listener );
  4013. if ( index !== - 1 ) {
  4014. listenerArray.splice( index, 1 );
  4015. }
  4016. }
  4017. },
  4018. dispatchEvent: function ( event ) {
  4019. if ( this._listeners === undefined ) return;
  4020. var listeners = this._listeners;
  4021. var listenerArray = listeners[ event.type ];
  4022. if ( listenerArray !== undefined ) {
  4023. event.target = this;
  4024. var array = listenerArray.slice( 0 );
  4025. for ( var i = 0, l = array.length; i < l; i ++ ) {
  4026. array[ i ].call( this, event );
  4027. }
  4028. }
  4029. }
  4030. } );
  4031. var REVISION = '95';
  4032. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  4033. var CullFaceNone = 0;
  4034. var CullFaceBack = 1;
  4035. var CullFaceFront = 2;
  4036. var CullFaceFrontBack = 3;
  4037. var FrontFaceDirectionCW = 0;
  4038. var FrontFaceDirectionCCW = 1;
  4039. var BasicShadowMap = 0;
  4040. var PCFShadowMap = 1;
  4041. var PCFSoftShadowMap = 2;
  4042. var FrontSide = 0;
  4043. var BackSide = 1;
  4044. var DoubleSide = 2;
  4045. var FlatShading = 1;
  4046. var SmoothShading = 2;
  4047. var NoColors = 0;
  4048. var FaceColors = 1;
  4049. var VertexColors = 2;
  4050. var NoBlending = 0;
  4051. var NormalBlending = 1;
  4052. var AdditiveBlending = 2;
  4053. var SubtractiveBlending = 3;
  4054. var MultiplyBlending = 4;
  4055. var CustomBlending = 5;
  4056. var AddEquation = 100;
  4057. var SubtractEquation = 101;
  4058. var ReverseSubtractEquation = 102;
  4059. var MinEquation = 103;
  4060. var MaxEquation = 104;
  4061. var ZeroFactor = 200;
  4062. var OneFactor = 201;
  4063. var SrcColorFactor = 202;
  4064. var OneMinusSrcColorFactor = 203;
  4065. var SrcAlphaFactor = 204;
  4066. var OneMinusSrcAlphaFactor = 205;
  4067. var DstAlphaFactor = 206;
  4068. var OneMinusDstAlphaFactor = 207;
  4069. var DstColorFactor = 208;
  4070. var OneMinusDstColorFactor = 209;
  4071. var SrcAlphaSaturateFactor = 210;
  4072. var NeverDepth = 0;
  4073. var AlwaysDepth = 1;
  4074. var LessDepth = 2;
  4075. var LessEqualDepth = 3;
  4076. var EqualDepth = 4;
  4077. var GreaterEqualDepth = 5;
  4078. var GreaterDepth = 6;
  4079. var NotEqualDepth = 7;
  4080. var MultiplyOperation = 0;
  4081. var MixOperation = 1;
  4082. var AddOperation = 2;
  4083. var NoToneMapping = 0;
  4084. var LinearToneMapping = 1;
  4085. var ReinhardToneMapping = 2;
  4086. var Uncharted2ToneMapping = 3;
  4087. var CineonToneMapping = 4;
  4088. var UVMapping = 300;
  4089. var CubeReflectionMapping = 301;
  4090. var CubeRefractionMapping = 302;
  4091. var EquirectangularReflectionMapping = 303;
  4092. var EquirectangularRefractionMapping = 304;
  4093. var SphericalReflectionMapping = 305;
  4094. var CubeUVReflectionMapping = 306;
  4095. var CubeUVRefractionMapping = 307;
  4096. var RepeatWrapping = 1000;
  4097. var ClampToEdgeWrapping = 1001;
  4098. var MirroredRepeatWrapping = 1002;
  4099. var NearestFilter = 1003;
  4100. var NearestMipMapNearestFilter = 1004;
  4101. var NearestMipMapLinearFilter = 1005;
  4102. var LinearFilter = 1006;
  4103. var LinearMipMapNearestFilter = 1007;
  4104. var LinearMipMapLinearFilter = 1008;
  4105. var UnsignedByteType = 1009;
  4106. var ByteType = 1010;
  4107. var ShortType = 1011;
  4108. var UnsignedShortType = 1012;
  4109. var IntType = 1013;
  4110. var UnsignedIntType = 1014;
  4111. var FloatType = 1015;
  4112. var HalfFloatType = 1016;
  4113. var UnsignedShort4444Type = 1017;
  4114. var UnsignedShort5551Type = 1018;
  4115. var UnsignedShort565Type = 1019;
  4116. var UnsignedInt248Type = 1020;
  4117. var AlphaFormat = 1021;
  4118. var RGBFormat = 1022;
  4119. var RGBAFormat = 1023;
  4120. var LuminanceFormat = 1024;
  4121. var LuminanceAlphaFormat = 1025;
  4122. var RGBEFormat = RGBAFormat;
  4123. var DepthFormat = 1026;
  4124. var DepthStencilFormat = 1027;
  4125. var RGB_S3TC_DXT1_Format = 33776;
  4126. var RGBA_S3TC_DXT1_Format = 33777;
  4127. var RGBA_S3TC_DXT3_Format = 33778;
  4128. var RGBA_S3TC_DXT5_Format = 33779;
  4129. var RGB_PVRTC_4BPPV1_Format = 35840;
  4130. var RGB_PVRTC_2BPPV1_Format = 35841;
  4131. var RGBA_PVRTC_4BPPV1_Format = 35842;
  4132. var RGBA_PVRTC_2BPPV1_Format = 35843;
  4133. var RGB_ETC1_Format = 36196;
  4134. var RGBA_ASTC_4x4_Format = 37808;
  4135. var RGBA_ASTC_5x4_Format = 37809;
  4136. var RGBA_ASTC_5x5_Format = 37810;
  4137. var RGBA_ASTC_6x5_Format = 37811;
  4138. var RGBA_ASTC_6x6_Format = 37812;
  4139. var RGBA_ASTC_8x5_Format = 37813;
  4140. var RGBA_ASTC_8x6_Format = 37814;
  4141. var RGBA_ASTC_8x8_Format = 37815;
  4142. var RGBA_ASTC_10x5_Format = 37816;
  4143. var RGBA_ASTC_10x6_Format = 37817;
  4144. var RGBA_ASTC_10x8_Format = 37818;
  4145. var RGBA_ASTC_10x10_Format = 37819;
  4146. var RGBA_ASTC_12x10_Format = 37820;
  4147. var RGBA_ASTC_12x12_Format = 37821;
  4148. var LoopOnce = 2200;
  4149. var LoopRepeat = 2201;
  4150. var LoopPingPong = 2202;
  4151. var InterpolateDiscrete = 2300;
  4152. var InterpolateLinear = 2301;
  4153. var InterpolateSmooth = 2302;
  4154. var ZeroCurvatureEnding = 2400;
  4155. var ZeroSlopeEnding = 2401;
  4156. var WrapAroundEnding = 2402;
  4157. var TrianglesDrawMode = 0;
  4158. var TriangleStripDrawMode = 1;
  4159. var TriangleFanDrawMode = 2;
  4160. var LinearEncoding = 3000;
  4161. var sRGBEncoding = 3001;
  4162. var GammaEncoding = 3007;
  4163. var RGBEEncoding = 3002;
  4164. var LogLuvEncoding = 3003;
  4165. var RGBM7Encoding = 3004;
  4166. var RGBM16Encoding = 3005;
  4167. var RGBDEncoding = 3006;
  4168. var BasicDepthPacking = 3200;
  4169. var RGBADepthPacking = 3201;
  4170. var TangentSpaceNormalMap = 0;
  4171. var ObjectSpaceNormalMap = 1;
  4172. /**
  4173. * @author alteredq / http://alteredqualia.com/
  4174. * @author mrdoob / http://mrdoob.com/
  4175. */
  4176. var _Math = {
  4177. DEG2RAD: Math.PI / 180,
  4178. RAD2DEG: 180 / Math.PI,
  4179. generateUUID: ( function () {
  4180. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  4181. var lut = [];
  4182. for ( var i = 0; i < 256; i ++ ) {
  4183. lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  4184. }
  4185. return function generateUUID() {
  4186. var d0 = Math.random() * 0xffffffff | 0;
  4187. var d1 = Math.random() * 0xffffffff | 0;
  4188. var d2 = Math.random() * 0xffffffff | 0;
  4189. var d3 = Math.random() * 0xffffffff | 0;
  4190. var uuid = lut[ d0 & 0xff ] + lut[ d0 >> 8 & 0xff ] + lut[ d0 >> 16 & 0xff ] + lut[ d0 >> 24 & 0xff ] + '-' +
  4191. lut[ d1 & 0xff ] + lut[ d1 >> 8 & 0xff ] + '-' + lut[ d1 >> 16 & 0x0f | 0x40 ] + lut[ d1 >> 24 & 0xff ] + '-' +
  4192. lut[ d2 & 0x3f | 0x80 ] + lut[ d2 >> 8 & 0xff ] + '-' + lut[ d2 >> 16 & 0xff ] + lut[ d2 >> 24 & 0xff ] +
  4193. lut[ d3 & 0xff ] + lut[ d3 >> 8 & 0xff ] + lut[ d3 >> 16 & 0xff ] + lut[ d3 >> 24 & 0xff ];
  4194. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  4195. return uuid.toUpperCase();
  4196. };
  4197. } )(),
  4198. clamp: function ( value, min, max ) {
  4199. return Math.max( min, Math.min( max, value ) );
  4200. },
  4201. // compute euclidian modulo of m % n
  4202. // https://en.wikipedia.org/wiki/Modulo_operation
  4203. euclideanModulo: function ( n, m ) {
  4204. return ( ( n % m ) + m ) % m;
  4205. },
  4206. // Linear mapping from range <a1, a2> to range <b1, b2>
  4207. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4208. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4209. },
  4210. // https://en.wikipedia.org/wiki/Linear_interpolation
  4211. lerp: function ( x, y, t ) {
  4212. return ( 1 - t ) * x + t * y;
  4213. },
  4214. // http://en.wikipedia.org/wiki/Smoothstep
  4215. smoothstep: function ( x, min, max ) {
  4216. if ( x <= min ) return 0;
  4217. if ( x >= max ) return 1;
  4218. x = ( x - min ) / ( max - min );
  4219. return x * x * ( 3 - 2 * x );
  4220. },
  4221. smootherstep: function ( x, min, max ) {
  4222. if ( x <= min ) return 0;
  4223. if ( x >= max ) return 1;
  4224. x = ( x - min ) / ( max - min );
  4225. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4226. },
  4227. // Random integer from <low, high> interval
  4228. randInt: function ( low, high ) {
  4229. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4230. },
  4231. // Random float from <low, high> interval
  4232. randFloat: function ( low, high ) {
  4233. return low + Math.random() * ( high - low );
  4234. },
  4235. // Random float from <-range/2, range/2> interval
  4236. randFloatSpread: function ( range ) {
  4237. return range * ( 0.5 - Math.random() );
  4238. },
  4239. degToRad: function ( degrees ) {
  4240. return degrees * _Math.DEG2RAD;
  4241. },
  4242. radToDeg: function ( radians ) {
  4243. return radians * _Math.RAD2DEG;
  4244. },
  4245. isPowerOfTwo: function ( value ) {
  4246. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4247. },
  4248. ceilPowerOfTwo: function ( value ) {
  4249. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  4250. },
  4251. floorPowerOfTwo: function ( value ) {
  4252. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  4253. }
  4254. };
  4255. /**
  4256. * @author mrdoob / http://mrdoob.com/
  4257. * @author philogb / http://blog.thejit.org/
  4258. * @author egraether / http://egraether.com/
  4259. * @author zz85 / http://www.lab4games.net/zz85/blog
  4260. */
  4261. function Vector2( x, y ) {
  4262. this.x = x || 0;
  4263. this.y = y || 0;
  4264. }
  4265. Object.defineProperties( Vector2.prototype, {
  4266. "width": {
  4267. get: function () {
  4268. return this.x;
  4269. },
  4270. set: function ( value ) {
  4271. this.x = value;
  4272. }
  4273. },
  4274. "height": {
  4275. get: function () {
  4276. return this.y;
  4277. },
  4278. set: function ( value ) {
  4279. this.y = value;
  4280. }
  4281. }
  4282. } );
  4283. Object.assign( Vector2.prototype, {
  4284. isVector2: true,
  4285. set: function ( x, y ) {
  4286. this.x = x;
  4287. this.y = y;
  4288. return this;
  4289. },
  4290. setScalar: function ( scalar ) {
  4291. this.x = scalar;
  4292. this.y = scalar;
  4293. return this;
  4294. },
  4295. setX: function ( x ) {
  4296. this.x = x;
  4297. return this;
  4298. },
  4299. setY: function ( y ) {
  4300. this.y = y;
  4301. return this;
  4302. },
  4303. setComponent: function ( index, value ) {
  4304. switch ( index ) {
  4305. case 0: this.x = value; break;
  4306. case 1: this.y = value; break;
  4307. default: throw new Error( 'index is out of range: ' + index );
  4308. }
  4309. return this;
  4310. },
  4311. getComponent: function ( index ) {
  4312. switch ( index ) {
  4313. case 0: return this.x;
  4314. case 1: return this.y;
  4315. default: throw new Error( 'index is out of range: ' + index );
  4316. }
  4317. },
  4318. clone: function () {
  4319. return new this.constructor( this.x, this.y );
  4320. },
  4321. copy: function ( v ) {
  4322. this.x = v.x;
  4323. this.y = v.y;
  4324. return this;
  4325. },
  4326. add: function ( v, w ) {
  4327. if ( w !== undefined ) {
  4328. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  4329. return this.addVectors( v, w );
  4330. }
  4331. this.x += v.x;
  4332. this.y += v.y;
  4333. return this;
  4334. },
  4335. addScalar: function ( s ) {
  4336. this.x += s;
  4337. this.y += s;
  4338. return this;
  4339. },
  4340. addVectors: function ( a, b ) {
  4341. this.x = a.x + b.x;
  4342. this.y = a.y + b.y;
  4343. return this;
  4344. },
  4345. addScaledVector: function ( v, s ) {
  4346. this.x += v.x * s;
  4347. this.y += v.y * s;
  4348. return this;
  4349. },
  4350. sub: function ( v, w ) {
  4351. if ( w !== undefined ) {
  4352. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  4353. return this.subVectors( v, w );
  4354. }
  4355. this.x -= v.x;
  4356. this.y -= v.y;
  4357. return this;
  4358. },
  4359. subScalar: function ( s ) {
  4360. this.x -= s;
  4361. this.y -= s;
  4362. return this;
  4363. },
  4364. subVectors: function ( a, b ) {
  4365. this.x = a.x - b.x;
  4366. this.y = a.y - b.y;
  4367. return this;
  4368. },
  4369. multiply: function ( v ) {
  4370. this.x *= v.x;
  4371. this.y *= v.y;
  4372. return this;
  4373. },
  4374. multiplyScalar: function ( scalar ) {
  4375. this.x *= scalar;
  4376. this.y *= scalar;
  4377. return this;
  4378. },
  4379. divide: function ( v ) {
  4380. this.x /= v.x;
  4381. this.y /= v.y;
  4382. return this;
  4383. },
  4384. divideScalar: function ( scalar ) {
  4385. return this.multiplyScalar( 1 / scalar );
  4386. },
  4387. applyMatrix3: function ( m ) {
  4388. var x = this.x, y = this.y;
  4389. var e = m.elements;
  4390. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  4391. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  4392. return this;
  4393. },
  4394. min: function ( v ) {
  4395. this.x = Math.min( this.x, v.x );
  4396. this.y = Math.min( this.y, v.y );
  4397. return this;
  4398. },
  4399. max: function ( v ) {
  4400. this.x = Math.max( this.x, v.x );
  4401. this.y = Math.max( this.y, v.y );
  4402. return this;
  4403. },
  4404. clamp: function ( min, max ) {
  4405. // assumes min < max, componentwise
  4406. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  4407. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  4408. return this;
  4409. },
  4410. clampScalar: function () {
  4411. var min = new Vector2();
  4412. var max = new Vector2();
  4413. return function clampScalar( minVal, maxVal ) {
  4414. min.set( minVal, minVal );
  4415. max.set( maxVal, maxVal );
  4416. return this.clamp( min, max );
  4417. };
  4418. }(),
  4419. clampLength: function ( min, max ) {
  4420. var length = this.length();
  4421. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  4422. },
  4423. floor: function () {
  4424. this.x = Math.floor( this.x );
  4425. this.y = Math.floor( this.y );
  4426. return this;
  4427. },
  4428. ceil: function () {
  4429. this.x = Math.ceil( this.x );
  4430. this.y = Math.ceil( this.y );
  4431. return this;
  4432. },
  4433. round: function () {
  4434. this.x = Math.round( this.x );
  4435. this.y = Math.round( this.y );
  4436. return this;
  4437. },
  4438. roundToZero: function () {
  4439. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  4440. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  4441. return this;
  4442. },
  4443. negate: function () {
  4444. this.x = - this.x;
  4445. this.y = - this.y;
  4446. return this;
  4447. },
  4448. dot: function ( v ) {
  4449. return this.x * v.x + this.y * v.y;
  4450. },
  4451. cross: function ( v ) {
  4452. return this.x * v.y - this.y * v.x;
  4453. },
  4454. lengthSq: function () {
  4455. return this.x * this.x + this.y * this.y;
  4456. },
  4457. length: function () {
  4458. return Math.sqrt( this.x * this.x + this.y * this.y );
  4459. },
  4460. manhattanLength: function () {
  4461. return Math.abs( this.x ) + Math.abs( this.y );
  4462. },
  4463. normalize: function () {
  4464. return this.divideScalar( this.length() || 1 );
  4465. },
  4466. angle: function () {
  4467. // computes the angle in radians with respect to the positive x-axis
  4468. var angle = Math.atan2( this.y, this.x );
  4469. if ( angle < 0 ) angle += 2 * Math.PI;
  4470. return angle;
  4471. },
  4472. distanceTo: function ( v ) {
  4473. return Math.sqrt( this.distanceToSquared( v ) );
  4474. },
  4475. distanceToSquared: function ( v ) {
  4476. var dx = this.x - v.x, dy = this.y - v.y;
  4477. return dx * dx + dy * dy;
  4478. },
  4479. manhattanDistanceTo: function ( v ) {
  4480. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  4481. },
  4482. setLength: function ( length ) {
  4483. return this.normalize().multiplyScalar( length );
  4484. },
  4485. lerp: function ( v, alpha ) {
  4486. this.x += ( v.x - this.x ) * alpha;
  4487. this.y += ( v.y - this.y ) * alpha;
  4488. return this;
  4489. },
  4490. lerpVectors: function ( v1, v2, alpha ) {
  4491. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  4492. },
  4493. equals: function ( v ) {
  4494. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  4495. },
  4496. fromArray: function ( array, offset ) {
  4497. if ( offset === undefined ) offset = 0;
  4498. this.x = array[ offset ];
  4499. this.y = array[ offset + 1 ];
  4500. return this;
  4501. },
  4502. toArray: function ( array, offset ) {
  4503. if ( array === undefined ) array = [];
  4504. if ( offset === undefined ) offset = 0;
  4505. array[ offset ] = this.x;
  4506. array[ offset + 1 ] = this.y;
  4507. return array;
  4508. },
  4509. fromBufferAttribute: function ( attribute, index, offset ) {
  4510. if ( offset !== undefined ) {
  4511. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  4512. }
  4513. this.x = attribute.getX( index );
  4514. this.y = attribute.getY( index );
  4515. return this;
  4516. },
  4517. rotateAround: function ( center, angle ) {
  4518. var c = Math.cos( angle ), s = Math.sin( angle );
  4519. var x = this.x - center.x;
  4520. var y = this.y - center.y;
  4521. this.x = x * c - y * s + center.x;
  4522. this.y = x * s + y * c + center.y;
  4523. return this;
  4524. }
  4525. } );
  4526. /**
  4527. * @author mrdoob / http://mrdoob.com/
  4528. * @author supereggbert / http://www.paulbrunt.co.uk/
  4529. * @author philogb / http://blog.thejit.org/
  4530. * @author jordi_ros / http://plattsoft.com
  4531. * @author D1plo1d / http://github.com/D1plo1d
  4532. * @author alteredq / http://alteredqualia.com/
  4533. * @author mikael emtinger / http://gomo.se/
  4534. * @author timknip / http://www.floorplanner.com/
  4535. * @author bhouston / http://clara.io
  4536. * @author WestLangley / http://github.com/WestLangley
  4537. */
  4538. function Matrix4() {
  4539. this.elements = [
  4540. 1, 0, 0, 0,
  4541. 0, 1, 0, 0,
  4542. 0, 0, 1, 0,
  4543. 0, 0, 0, 1
  4544. ];
  4545. if ( arguments.length > 0 ) {
  4546. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  4547. }
  4548. }
  4549. Object.assign( Matrix4.prototype, {
  4550. isMatrix4: true,
  4551. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  4552. var te = this.elements;
  4553. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  4554. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  4555. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  4556. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  4557. return this;
  4558. },
  4559. identity: function () {
  4560. this.set(
  4561. 1, 0, 0, 0,
  4562. 0, 1, 0, 0,
  4563. 0, 0, 1, 0,
  4564. 0, 0, 0, 1
  4565. );
  4566. return this;
  4567. },
  4568. clone: function () {
  4569. return new Matrix4().fromArray( this.elements );
  4570. },
  4571. copy: function ( m ) {
  4572. var te = this.elements;
  4573. var me = m.elements;
  4574. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  4575. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  4576. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  4577. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  4578. return this;
  4579. },
  4580. copyPosition: function ( m ) {
  4581. var te = this.elements, me = m.elements;
  4582. te[ 12 ] = me[ 12 ];
  4583. te[ 13 ] = me[ 13 ];
  4584. te[ 14 ] = me[ 14 ];
  4585. return this;
  4586. },
  4587. extractBasis: function ( xAxis, yAxis, zAxis ) {
  4588. xAxis.setFromMatrixColumn( this, 0 );
  4589. yAxis.setFromMatrixColumn( this, 1 );
  4590. zAxis.setFromMatrixColumn( this, 2 );
  4591. return this;
  4592. },
  4593. makeBasis: function ( xAxis, yAxis, zAxis ) {
  4594. this.set(
  4595. xAxis.x, yAxis.x, zAxis.x, 0,
  4596. xAxis.y, yAxis.y, zAxis.y, 0,
  4597. xAxis.z, yAxis.z, zAxis.z, 0,
  4598. 0, 0, 0, 1
  4599. );
  4600. return this;
  4601. },
  4602. extractRotation: function () {
  4603. var v1 = new Vector3();
  4604. return function extractRotation( m ) {
  4605. // this method does not support reflection matrices
  4606. var te = this.elements;
  4607. var me = m.elements;
  4608. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  4609. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  4610. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  4611. te[ 0 ] = me[ 0 ] * scaleX;
  4612. te[ 1 ] = me[ 1 ] * scaleX;
  4613. te[ 2 ] = me[ 2 ] * scaleX;
  4614. te[ 3 ] = 0;
  4615. te[ 4 ] = me[ 4 ] * scaleY;
  4616. te[ 5 ] = me[ 5 ] * scaleY;
  4617. te[ 6 ] = me[ 6 ] * scaleY;
  4618. te[ 7 ] = 0;
  4619. te[ 8 ] = me[ 8 ] * scaleZ;
  4620. te[ 9 ] = me[ 9 ] * scaleZ;
  4621. te[ 10 ] = me[ 10 ] * scaleZ;
  4622. te[ 11 ] = 0;
  4623. te[ 12 ] = 0;
  4624. te[ 13 ] = 0;
  4625. te[ 14 ] = 0;
  4626. te[ 15 ] = 1;
  4627. return this;
  4628. };
  4629. }(),
  4630. makeRotationFromEuler: function ( euler ) {
  4631. if ( ! ( euler && euler.isEuler ) ) {
  4632. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  4633. }
  4634. var te = this.elements;
  4635. var x = euler.x, y = euler.y, z = euler.z;
  4636. var a = Math.cos( x ), b = Math.sin( x );
  4637. var c = Math.cos( y ), d = Math.sin( y );
  4638. var e = Math.cos( z ), f = Math.sin( z );
  4639. if ( euler.order === 'XYZ' ) {
  4640. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  4641. te[ 0 ] = c * e;
  4642. te[ 4 ] = - c * f;
  4643. te[ 8 ] = d;
  4644. te[ 1 ] = af + be * d;
  4645. te[ 5 ] = ae - bf * d;
  4646. te[ 9 ] = - b * c;
  4647. te[ 2 ] = bf - ae * d;
  4648. te[ 6 ] = be + af * d;
  4649. te[ 10 ] = a * c;
  4650. } else if ( euler.order === 'YXZ' ) {
  4651. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  4652. te[ 0 ] = ce + df * b;
  4653. te[ 4 ] = de * b - cf;
  4654. te[ 8 ] = a * d;
  4655. te[ 1 ] = a * f;
  4656. te[ 5 ] = a * e;
  4657. te[ 9 ] = - b;
  4658. te[ 2 ] = cf * b - de;
  4659. te[ 6 ] = df + ce * b;
  4660. te[ 10 ] = a * c;
  4661. } else if ( euler.order === 'ZXY' ) {
  4662. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  4663. te[ 0 ] = ce - df * b;
  4664. te[ 4 ] = - a * f;
  4665. te[ 8 ] = de + cf * b;
  4666. te[ 1 ] = cf + de * b;
  4667. te[ 5 ] = a * e;
  4668. te[ 9 ] = df - ce * b;
  4669. te[ 2 ] = - a * d;
  4670. te[ 6 ] = b;
  4671. te[ 10 ] = a * c;
  4672. } else if ( euler.order === 'ZYX' ) {
  4673. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  4674. te[ 0 ] = c * e;
  4675. te[ 4 ] = be * d - af;
  4676. te[ 8 ] = ae * d + bf;
  4677. te[ 1 ] = c * f;
  4678. te[ 5 ] = bf * d + ae;
  4679. te[ 9 ] = af * d - be;
  4680. te[ 2 ] = - d;
  4681. te[ 6 ] = b * c;
  4682. te[ 10 ] = a * c;
  4683. } else if ( euler.order === 'YZX' ) {
  4684. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4685. te[ 0 ] = c * e;
  4686. te[ 4 ] = bd - ac * f;
  4687. te[ 8 ] = bc * f + ad;
  4688. te[ 1 ] = f;
  4689. te[ 5 ] = a * e;
  4690. te[ 9 ] = - b * e;
  4691. te[ 2 ] = - d * e;
  4692. te[ 6 ] = ad * f + bc;
  4693. te[ 10 ] = ac - bd * f;
  4694. } else if ( euler.order === 'XZY' ) {
  4695. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4696. te[ 0 ] = c * e;
  4697. te[ 4 ] = - f;
  4698. te[ 8 ] = d * e;
  4699. te[ 1 ] = ac * f + bd;
  4700. te[ 5 ] = a * e;
  4701. te[ 9 ] = ad * f - bc;
  4702. te[ 2 ] = bc * f - ad;
  4703. te[ 6 ] = b * e;
  4704. te[ 10 ] = bd * f + ac;
  4705. }
  4706. // bottom row
  4707. te[ 3 ] = 0;
  4708. te[ 7 ] = 0;
  4709. te[ 11 ] = 0;
  4710. // last column
  4711. te[ 12 ] = 0;
  4712. te[ 13 ] = 0;
  4713. te[ 14 ] = 0;
  4714. te[ 15 ] = 1;
  4715. return this;
  4716. },
  4717. makeRotationFromQuaternion: function () {
  4718. var zero = new Vector3( 0, 0, 0 );
  4719. var one = new Vector3( 1, 1, 1 );
  4720. return function makeRotationFromQuaternion( q ) {
  4721. return this.compose( zero, q, one );
  4722. };
  4723. }(),
  4724. lookAt: function () {
  4725. var x = new Vector3();
  4726. var y = new Vector3();
  4727. var z = new Vector3();
  4728. return function lookAt( eye, target, up ) {
  4729. var te = this.elements;
  4730. z.subVectors( eye, target );
  4731. if ( z.lengthSq() === 0 ) {
  4732. // eye and target are in the same position
  4733. z.z = 1;
  4734. }
  4735. z.normalize();
  4736. x.crossVectors( up, z );
  4737. if ( x.lengthSq() === 0 ) {
  4738. // up and z are parallel
  4739. if ( Math.abs( up.z ) === 1 ) {
  4740. z.x += 0.0001;
  4741. } else {
  4742. z.z += 0.0001;
  4743. }
  4744. z.normalize();
  4745. x.crossVectors( up, z );
  4746. }
  4747. x.normalize();
  4748. y.crossVectors( z, x );
  4749. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  4750. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  4751. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  4752. return this;
  4753. };
  4754. }(),
  4755. multiply: function ( m, n ) {
  4756. if ( n !== undefined ) {
  4757. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  4758. return this.multiplyMatrices( m, n );
  4759. }
  4760. return this.multiplyMatrices( this, m );
  4761. },
  4762. premultiply: function ( m ) {
  4763. return this.multiplyMatrices( m, this );
  4764. },
  4765. multiplyMatrices: function ( a, b ) {
  4766. var ae = a.elements;
  4767. var be = b.elements;
  4768. var te = this.elements;
  4769. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  4770. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  4771. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  4772. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  4773. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  4774. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  4775. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  4776. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  4777. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4778. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4779. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4780. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4781. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4782. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4783. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4784. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4785. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4786. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4787. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4788. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4789. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4790. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4791. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4792. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4793. return this;
  4794. },
  4795. multiplyScalar: function ( s ) {
  4796. var te = this.elements;
  4797. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  4798. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  4799. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  4800. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  4801. return this;
  4802. },
  4803. applyToBufferAttribute: function () {
  4804. var v1 = new Vector3();
  4805. return function applyToBufferAttribute( attribute ) {
  4806. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4807. v1.x = attribute.getX( i );
  4808. v1.y = attribute.getY( i );
  4809. v1.z = attribute.getZ( i );
  4810. v1.applyMatrix4( this );
  4811. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  4812. }
  4813. return attribute;
  4814. };
  4815. }(),
  4816. determinant: function () {
  4817. var te = this.elements;
  4818. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  4819. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  4820. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  4821. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  4822. //TODO: make this more efficient
  4823. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4824. return (
  4825. n41 * (
  4826. + n14 * n23 * n32
  4827. - n13 * n24 * n32
  4828. - n14 * n22 * n33
  4829. + n12 * n24 * n33
  4830. + n13 * n22 * n34
  4831. - n12 * n23 * n34
  4832. ) +
  4833. n42 * (
  4834. + n11 * n23 * n34
  4835. - n11 * n24 * n33
  4836. + n14 * n21 * n33
  4837. - n13 * n21 * n34
  4838. + n13 * n24 * n31
  4839. - n14 * n23 * n31
  4840. ) +
  4841. n43 * (
  4842. + n11 * n24 * n32
  4843. - n11 * n22 * n34
  4844. - n14 * n21 * n32
  4845. + n12 * n21 * n34
  4846. + n14 * n22 * n31
  4847. - n12 * n24 * n31
  4848. ) +
  4849. n44 * (
  4850. - n13 * n22 * n31
  4851. - n11 * n23 * n32
  4852. + n11 * n22 * n33
  4853. + n13 * n21 * n32
  4854. - n12 * n21 * n33
  4855. + n12 * n23 * n31
  4856. )
  4857. );
  4858. },
  4859. transpose: function () {
  4860. var te = this.elements;
  4861. var tmp;
  4862. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4863. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4864. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4865. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4866. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4867. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4868. return this;
  4869. },
  4870. setPosition: function ( v ) {
  4871. var te = this.elements;
  4872. te[ 12 ] = v.x;
  4873. te[ 13 ] = v.y;
  4874. te[ 14 ] = v.z;
  4875. return this;
  4876. },
  4877. getInverse: function ( m, throwOnDegenerate ) {
  4878. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4879. var te = this.elements,
  4880. me = m.elements,
  4881. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  4882. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  4883. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  4884. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  4885. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4886. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4887. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4888. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4889. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4890. if ( det === 0 ) {
  4891. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  4892. if ( throwOnDegenerate === true ) {
  4893. throw new Error( msg );
  4894. } else {
  4895. console.warn( msg );
  4896. }
  4897. return this.identity();
  4898. }
  4899. var detInv = 1 / det;
  4900. te[ 0 ] = t11 * detInv;
  4901. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4902. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4903. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4904. te[ 4 ] = t12 * detInv;
  4905. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4906. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4907. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4908. te[ 8 ] = t13 * detInv;
  4909. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4910. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4911. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4912. te[ 12 ] = t14 * detInv;
  4913. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4914. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4915. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4916. return this;
  4917. },
  4918. scale: function ( v ) {
  4919. var te = this.elements;
  4920. var x = v.x, y = v.y, z = v.z;
  4921. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4922. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4923. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4924. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4925. return this;
  4926. },
  4927. getMaxScaleOnAxis: function () {
  4928. var te = this.elements;
  4929. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4930. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4931. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4932. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4933. },
  4934. makeTranslation: function ( x, y, z ) {
  4935. this.set(
  4936. 1, 0, 0, x,
  4937. 0, 1, 0, y,
  4938. 0, 0, 1, z,
  4939. 0, 0, 0, 1
  4940. );
  4941. return this;
  4942. },
  4943. makeRotationX: function ( theta ) {
  4944. var c = Math.cos( theta ), s = Math.sin( theta );
  4945. this.set(
  4946. 1, 0, 0, 0,
  4947. 0, c, - s, 0,
  4948. 0, s, c, 0,
  4949. 0, 0, 0, 1
  4950. );
  4951. return this;
  4952. },
  4953. makeRotationY: function ( theta ) {
  4954. var c = Math.cos( theta ), s = Math.sin( theta );
  4955. this.set(
  4956. c, 0, s, 0,
  4957. 0, 1, 0, 0,
  4958. - s, 0, c, 0,
  4959. 0, 0, 0, 1
  4960. );
  4961. return this;
  4962. },
  4963. makeRotationZ: function ( theta ) {
  4964. var c = Math.cos( theta ), s = Math.sin( theta );
  4965. this.set(
  4966. c, - s, 0, 0,
  4967. s, c, 0, 0,
  4968. 0, 0, 1, 0,
  4969. 0, 0, 0, 1
  4970. );
  4971. return this;
  4972. },
  4973. makeRotationAxis: function ( axis, angle ) {
  4974. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4975. var c = Math.cos( angle );
  4976. var s = Math.sin( angle );
  4977. var t = 1 - c;
  4978. var x = axis.x, y = axis.y, z = axis.z;
  4979. var tx = t * x, ty = t * y;
  4980. this.set(
  4981. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4982. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4983. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4984. 0, 0, 0, 1
  4985. );
  4986. return this;
  4987. },
  4988. makeScale: function ( x, y, z ) {
  4989. this.set(
  4990. x, 0, 0, 0,
  4991. 0, y, 0, 0,
  4992. 0, 0, z, 0,
  4993. 0, 0, 0, 1
  4994. );
  4995. return this;
  4996. },
  4997. makeShear: function ( x, y, z ) {
  4998. this.set(
  4999. 1, y, z, 0,
  5000. x, 1, z, 0,
  5001. x, y, 1, 0,
  5002. 0, 0, 0, 1
  5003. );
  5004. return this;
  5005. },
  5006. compose: function ( position, quaternion, scale ) {
  5007. var te = this.elements;
  5008. var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  5009. var x2 = x + x, y2 = y + y, z2 = z + z;
  5010. var xx = x * x2, xy = x * y2, xz = x * z2;
  5011. var yy = y * y2, yz = y * z2, zz = z * z2;
  5012. var wx = w * x2, wy = w * y2, wz = w * z2;
  5013. var sx = scale.x, sy = scale.y, sz = scale.z;
  5014. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  5015. te[ 1 ] = ( xy + wz ) * sx;
  5016. te[ 2 ] = ( xz - wy ) * sx;
  5017. te[ 3 ] = 0;
  5018. te[ 4 ] = ( xy - wz ) * sy;
  5019. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  5020. te[ 6 ] = ( yz + wx ) * sy;
  5021. te[ 7 ] = 0;
  5022. te[ 8 ] = ( xz + wy ) * sz;
  5023. te[ 9 ] = ( yz - wx ) * sz;
  5024. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  5025. te[ 11 ] = 0;
  5026. te[ 12 ] = position.x;
  5027. te[ 13 ] = position.y;
  5028. te[ 14 ] = position.z;
  5029. te[ 15 ] = 1;
  5030. return this;
  5031. },
  5032. decompose: function () {
  5033. var vector = new Vector3();
  5034. var matrix = new Matrix4();
  5035. return function decompose( position, quaternion, scale ) {
  5036. var te = this.elements;
  5037. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  5038. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  5039. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  5040. // if determine is negative, we need to invert one scale
  5041. var det = this.determinant();
  5042. if ( det < 0 ) sx = - sx;
  5043. position.x = te[ 12 ];
  5044. position.y = te[ 13 ];
  5045. position.z = te[ 14 ];
  5046. // scale the rotation part
  5047. matrix.copy( this );
  5048. var invSX = 1 / sx;
  5049. var invSY = 1 / sy;
  5050. var invSZ = 1 / sz;
  5051. matrix.elements[ 0 ] *= invSX;
  5052. matrix.elements[ 1 ] *= invSX;
  5053. matrix.elements[ 2 ] *= invSX;
  5054. matrix.elements[ 4 ] *= invSY;
  5055. matrix.elements[ 5 ] *= invSY;
  5056. matrix.elements[ 6 ] *= invSY;
  5057. matrix.elements[ 8 ] *= invSZ;
  5058. matrix.elements[ 9 ] *= invSZ;
  5059. matrix.elements[ 10 ] *= invSZ;
  5060. quaternion.setFromRotationMatrix( matrix );
  5061. scale.x = sx;
  5062. scale.y = sy;
  5063. scale.z = sz;
  5064. return this;
  5065. };
  5066. }(),
  5067. makePerspective: function ( left, right, top, bottom, near, far ) {
  5068. if ( far === undefined ) {
  5069. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  5070. }
  5071. var te = this.elements;
  5072. var x = 2 * near / ( right - left );
  5073. var y = 2 * near / ( top - bottom );
  5074. var a = ( right + left ) / ( right - left );
  5075. var b = ( top + bottom ) / ( top - bottom );
  5076. var c = - ( far + near ) / ( far - near );
  5077. var d = - 2 * far * near / ( far - near );
  5078. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  5079. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  5080. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  5081. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  5082. return this;
  5083. },
  5084. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  5085. var te = this.elements;
  5086. var w = 1.0 / ( right - left );
  5087. var h = 1.0 / ( top - bottom );
  5088. var p = 1.0 / ( far - near );
  5089. var x = ( right + left ) * w;
  5090. var y = ( top + bottom ) * h;
  5091. var z = ( far + near ) * p;
  5092. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  5093. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  5094. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  5095. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  5096. return this;
  5097. },
  5098. equals: function ( matrix ) {
  5099. var te = this.elements;
  5100. var me = matrix.elements;
  5101. for ( var i = 0; i < 16; i ++ ) {
  5102. if ( te[ i ] !== me[ i ] ) return false;
  5103. }
  5104. return true;
  5105. },
  5106. fromArray: function ( array, offset ) {
  5107. if ( offset === undefined ) offset = 0;
  5108. for ( var i = 0; i < 16; i ++ ) {
  5109. this.elements[ i ] = array[ i + offset ];
  5110. }
  5111. return this;
  5112. },
  5113. toArray: function ( array, offset ) {
  5114. if ( array === undefined ) array = [];
  5115. if ( offset === undefined ) offset = 0;
  5116. var te = this.elements;
  5117. array[ offset ] = te[ 0 ];
  5118. array[ offset + 1 ] = te[ 1 ];
  5119. array[ offset + 2 ] = te[ 2 ];
  5120. array[ offset + 3 ] = te[ 3 ];
  5121. array[ offset + 4 ] = te[ 4 ];
  5122. array[ offset + 5 ] = te[ 5 ];
  5123. array[ offset + 6 ] = te[ 6 ];
  5124. array[ offset + 7 ] = te[ 7 ];
  5125. array[ offset + 8 ] = te[ 8 ];
  5126. array[ offset + 9 ] = te[ 9 ];
  5127. array[ offset + 10 ] = te[ 10 ];
  5128. array[ offset + 11 ] = te[ 11 ];
  5129. array[ offset + 12 ] = te[ 12 ];
  5130. array[ offset + 13 ] = te[ 13 ];
  5131. array[ offset + 14 ] = te[ 14 ];
  5132. array[ offset + 15 ] = te[ 15 ];
  5133. return array;
  5134. }
  5135. } );
  5136. /**
  5137. * @author mikael emtinger / http://gomo.se/
  5138. * @author alteredq / http://alteredqualia.com/
  5139. * @author WestLangley / http://github.com/WestLangley
  5140. * @author bhouston / http://clara.io
  5141. */
  5142. function Quaternion( x, y, z, w ) {
  5143. this._x = x || 0;
  5144. this._y = y || 0;
  5145. this._z = z || 0;
  5146. this._w = ( w !== undefined ) ? w : 1;
  5147. }
  5148. Object.assign( Quaternion, {
  5149. slerp: function ( qa, qb, qm, t ) {
  5150. return qm.copy( qa ).slerp( qb, t );
  5151. },
  5152. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5153. // fuzz-free, array-based Quaternion SLERP operation
  5154. var x0 = src0[ srcOffset0 + 0 ],
  5155. y0 = src0[ srcOffset0 + 1 ],
  5156. z0 = src0[ srcOffset0 + 2 ],
  5157. w0 = src0[ srcOffset0 + 3 ],
  5158. x1 = src1[ srcOffset1 + 0 ],
  5159. y1 = src1[ srcOffset1 + 1 ],
  5160. z1 = src1[ srcOffset1 + 2 ],
  5161. w1 = src1[ srcOffset1 + 3 ];
  5162. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5163. var s = 1 - t,
  5164. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5165. dir = ( cos >= 0 ? 1 : - 1 ),
  5166. sqrSin = 1 - cos * cos;
  5167. // Skip the Slerp for tiny steps to avoid numeric problems:
  5168. if ( sqrSin > Number.EPSILON ) {
  5169. var sin = Math.sqrt( sqrSin ),
  5170. len = Math.atan2( sin, cos * dir );
  5171. s = Math.sin( s * len ) / sin;
  5172. t = Math.sin( t * len ) / sin;
  5173. }
  5174. var tDir = t * dir;
  5175. x0 = x0 * s + x1 * tDir;
  5176. y0 = y0 * s + y1 * tDir;
  5177. z0 = z0 * s + z1 * tDir;
  5178. w0 = w0 * s + w1 * tDir;
  5179. // Normalize in case we just did a lerp:
  5180. if ( s === 1 - t ) {
  5181. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5182. x0 *= f;
  5183. y0 *= f;
  5184. z0 *= f;
  5185. w0 *= f;
  5186. }
  5187. }
  5188. dst[ dstOffset ] = x0;
  5189. dst[ dstOffset + 1 ] = y0;
  5190. dst[ dstOffset + 2 ] = z0;
  5191. dst[ dstOffset + 3 ] = w0;
  5192. }
  5193. } );
  5194. Object.defineProperties( Quaternion.prototype, {
  5195. x: {
  5196. get: function () {
  5197. return this._x;
  5198. },
  5199. set: function ( value ) {
  5200. this._x = value;
  5201. this.onChangeCallback();
  5202. }
  5203. },
  5204. y: {
  5205. get: function () {
  5206. return this._y;
  5207. },
  5208. set: function ( value ) {
  5209. this._y = value;
  5210. this.onChangeCallback();
  5211. }
  5212. },
  5213. z: {
  5214. get: function () {
  5215. return this._z;
  5216. },
  5217. set: function ( value ) {
  5218. this._z = value;
  5219. this.onChangeCallback();
  5220. }
  5221. },
  5222. w: {
  5223. get: function () {
  5224. return this._w;
  5225. },
  5226. set: function ( value ) {
  5227. this._w = value;
  5228. this.onChangeCallback();
  5229. }
  5230. }
  5231. } );
  5232. Object.assign( Quaternion.prototype, {
  5233. set: function ( x, y, z, w ) {
  5234. this._x = x;
  5235. this._y = y;
  5236. this._z = z;
  5237. this._w = w;
  5238. this.onChangeCallback();
  5239. return this;
  5240. },
  5241. clone: function () {
  5242. return new this.constructor( this._x, this._y, this._z, this._w );
  5243. },
  5244. copy: function ( quaternion ) {
  5245. this._x = quaternion.x;
  5246. this._y = quaternion.y;
  5247. this._z = quaternion.z;
  5248. this._w = quaternion.w;
  5249. this.onChangeCallback();
  5250. return this;
  5251. },
  5252. setFromEuler: function ( euler, update ) {
  5253. if ( ! ( euler && euler.isEuler ) ) {
  5254. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5255. }
  5256. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  5257. // http://www.mathworks.com/matlabcentral/fileexchange/
  5258. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  5259. // content/SpinCalc.m
  5260. var cos = Math.cos;
  5261. var sin = Math.sin;
  5262. var c1 = cos( x / 2 );
  5263. var c2 = cos( y / 2 );
  5264. var c3 = cos( z / 2 );
  5265. var s1 = sin( x / 2 );
  5266. var s2 = sin( y / 2 );
  5267. var s3 = sin( z / 2 );
  5268. if ( order === 'XYZ' ) {
  5269. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5270. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5271. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5272. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5273. } else if ( order === 'YXZ' ) {
  5274. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5275. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5276. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5277. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5278. } else if ( order === 'ZXY' ) {
  5279. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5280. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5281. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5282. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5283. } else if ( order === 'ZYX' ) {
  5284. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5285. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5286. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5287. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5288. } else if ( order === 'YZX' ) {
  5289. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5290. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5291. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5292. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5293. } else if ( order === 'XZY' ) {
  5294. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5295. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5296. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5297. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5298. }
  5299. if ( update !== false ) this.onChangeCallback();
  5300. return this;
  5301. },
  5302. setFromAxisAngle: function ( axis, angle ) {
  5303. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  5304. // assumes axis is normalized
  5305. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  5306. this._x = axis.x * s;
  5307. this._y = axis.y * s;
  5308. this._z = axis.z * s;
  5309. this._w = Math.cos( halfAngle );
  5310. this.onChangeCallback();
  5311. return this;
  5312. },
  5313. setFromRotationMatrix: function ( m ) {
  5314. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  5315. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5316. var te = m.elements,
  5317. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5318. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5319. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  5320. trace = m11 + m22 + m33,
  5321. s;
  5322. if ( trace > 0 ) {
  5323. s = 0.5 / Math.sqrt( trace + 1.0 );
  5324. this._w = 0.25 / s;
  5325. this._x = ( m32 - m23 ) * s;
  5326. this._y = ( m13 - m31 ) * s;
  5327. this._z = ( m21 - m12 ) * s;
  5328. } else if ( m11 > m22 && m11 > m33 ) {
  5329. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  5330. this._w = ( m32 - m23 ) / s;
  5331. this._x = 0.25 * s;
  5332. this._y = ( m12 + m21 ) / s;
  5333. this._z = ( m13 + m31 ) / s;
  5334. } else if ( m22 > m33 ) {
  5335. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  5336. this._w = ( m13 - m31 ) / s;
  5337. this._x = ( m12 + m21 ) / s;
  5338. this._y = 0.25 * s;
  5339. this._z = ( m23 + m32 ) / s;
  5340. } else {
  5341. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  5342. this._w = ( m21 - m12 ) / s;
  5343. this._x = ( m13 + m31 ) / s;
  5344. this._y = ( m23 + m32 ) / s;
  5345. this._z = 0.25 * s;
  5346. }
  5347. this.onChangeCallback();
  5348. return this;
  5349. },
  5350. setFromUnitVectors: function () {
  5351. // assumes direction vectors vFrom and vTo are normalized
  5352. var v1 = new Vector3();
  5353. var r;
  5354. var EPS = 0.000001;
  5355. return function setFromUnitVectors( vFrom, vTo ) {
  5356. if ( v1 === undefined ) v1 = new Vector3();
  5357. r = vFrom.dot( vTo ) + 1;
  5358. if ( r < EPS ) {
  5359. r = 0;
  5360. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  5361. v1.set( - vFrom.y, vFrom.x, 0 );
  5362. } else {
  5363. v1.set( 0, - vFrom.z, vFrom.y );
  5364. }
  5365. } else {
  5366. v1.crossVectors( vFrom, vTo );
  5367. }
  5368. this._x = v1.x;
  5369. this._y = v1.y;
  5370. this._z = v1.z;
  5371. this._w = r;
  5372. return this.normalize();
  5373. };
  5374. }(),
  5375. angleTo: function ( q ) {
  5376. return 2 * Math.acos( Math.abs( _Math.clamp( this.dot( q ), - 1, 1 ) ) );
  5377. },
  5378. rotateTowards: function ( q, step ) {
  5379. var angle = this.angleTo( q );
  5380. if ( angle === 0 ) return this;
  5381. var t = Math.min( 1, step / angle );
  5382. this.slerp( q, t );
  5383. return this;
  5384. },
  5385. inverse: function () {
  5386. // quaternion is assumed to have unit length
  5387. return this.conjugate();
  5388. },
  5389. conjugate: function () {
  5390. this._x *= - 1;
  5391. this._y *= - 1;
  5392. this._z *= - 1;
  5393. this.onChangeCallback();
  5394. return this;
  5395. },
  5396. dot: function ( v ) {
  5397. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  5398. },
  5399. lengthSq: function () {
  5400. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  5401. },
  5402. length: function () {
  5403. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  5404. },
  5405. normalize: function () {
  5406. var l = this.length();
  5407. if ( l === 0 ) {
  5408. this._x = 0;
  5409. this._y = 0;
  5410. this._z = 0;
  5411. this._w = 1;
  5412. } else {
  5413. l = 1 / l;
  5414. this._x = this._x * l;
  5415. this._y = this._y * l;
  5416. this._z = this._z * l;
  5417. this._w = this._w * l;
  5418. }
  5419. this.onChangeCallback();
  5420. return this;
  5421. },
  5422. multiply: function ( q, p ) {
  5423. if ( p !== undefined ) {
  5424. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  5425. return this.multiplyQuaternions( q, p );
  5426. }
  5427. return this.multiplyQuaternions( this, q );
  5428. },
  5429. premultiply: function ( q ) {
  5430. return this.multiplyQuaternions( q, this );
  5431. },
  5432. multiplyQuaternions: function ( a, b ) {
  5433. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  5434. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  5435. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  5436. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  5437. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  5438. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  5439. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  5440. this.onChangeCallback();
  5441. return this;
  5442. },
  5443. slerp: function ( qb, t ) {
  5444. if ( t === 0 ) return this;
  5445. if ( t === 1 ) return this.copy( qb );
  5446. var x = this._x, y = this._y, z = this._z, w = this._w;
  5447. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  5448. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  5449. if ( cosHalfTheta < 0 ) {
  5450. this._w = - qb._w;
  5451. this._x = - qb._x;
  5452. this._y = - qb._y;
  5453. this._z = - qb._z;
  5454. cosHalfTheta = - cosHalfTheta;
  5455. } else {
  5456. this.copy( qb );
  5457. }
  5458. if ( cosHalfTheta >= 1.0 ) {
  5459. this._w = w;
  5460. this._x = x;
  5461. this._y = y;
  5462. this._z = z;
  5463. return this;
  5464. }
  5465. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  5466. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  5467. var s = 1 - t;
  5468. this._w = s * w + t * this._w;
  5469. this._x = s * x + t * this._x;
  5470. this._y = s * y + t * this._y;
  5471. this._z = s * z + t * this._z;
  5472. return this.normalize();
  5473. }
  5474. var sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  5475. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  5476. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  5477. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  5478. this._w = ( w * ratioA + this._w * ratioB );
  5479. this._x = ( x * ratioA + this._x * ratioB );
  5480. this._y = ( y * ratioA + this._y * ratioB );
  5481. this._z = ( z * ratioA + this._z * ratioB );
  5482. this.onChangeCallback();
  5483. return this;
  5484. },
  5485. equals: function ( quaternion ) {
  5486. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  5487. },
  5488. fromArray: function ( array, offset ) {
  5489. if ( offset === undefined ) offset = 0;
  5490. this._x = array[ offset ];
  5491. this._y = array[ offset + 1 ];
  5492. this._z = array[ offset + 2 ];
  5493. this._w = array[ offset + 3 ];
  5494. this.onChangeCallback();
  5495. return this;
  5496. },
  5497. toArray: function ( array, offset ) {
  5498. if ( array === undefined ) array = [];
  5499. if ( offset === undefined ) offset = 0;
  5500. array[ offset ] = this._x;
  5501. array[ offset + 1 ] = this._y;
  5502. array[ offset + 2 ] = this._z;
  5503. array[ offset + 3 ] = this._w;
  5504. return array;
  5505. },
  5506. onChange: function ( callback ) {
  5507. this.onChangeCallback = callback;
  5508. return this;
  5509. },
  5510. onChangeCallback: function () {}
  5511. } );
  5512. /**
  5513. * @author mrdoob / http://mrdoob.com/
  5514. * @author kile / http://kile.stravaganza.org/
  5515. * @author philogb / http://blog.thejit.org/
  5516. * @author mikael emtinger / http://gomo.se/
  5517. * @author egraether / http://egraether.com/
  5518. * @author WestLangley / http://github.com/WestLangley
  5519. */
  5520. function Vector3( x, y, z ) {
  5521. this.x = x || 0;
  5522. this.y = y || 0;
  5523. this.z = z || 0;
  5524. }
  5525. Object.assign( Vector3.prototype, {
  5526. isVector3: true,
  5527. set: function ( x, y, z ) {
  5528. this.x = x;
  5529. this.y = y;
  5530. this.z = z;
  5531. return this;
  5532. },
  5533. setScalar: function ( scalar ) {
  5534. this.x = scalar;
  5535. this.y = scalar;
  5536. this.z = scalar;
  5537. return this;
  5538. },
  5539. setX: function ( x ) {
  5540. this.x = x;
  5541. return this;
  5542. },
  5543. setY: function ( y ) {
  5544. this.y = y;
  5545. return this;
  5546. },
  5547. setZ: function ( z ) {
  5548. this.z = z;
  5549. return this;
  5550. },
  5551. setComponent: function ( index, value ) {
  5552. switch ( index ) {
  5553. case 0: this.x = value; break;
  5554. case 1: this.y = value; break;
  5555. case 2: this.z = value; break;
  5556. default: throw new Error( 'index is out of range: ' + index );
  5557. }
  5558. return this;
  5559. },
  5560. getComponent: function ( index ) {
  5561. switch ( index ) {
  5562. case 0: return this.x;
  5563. case 1: return this.y;
  5564. case 2: return this.z;
  5565. default: throw new Error( 'index is out of range: ' + index );
  5566. }
  5567. },
  5568. clone: function () {
  5569. return new this.constructor( this.x, this.y, this.z );
  5570. },
  5571. copy: function ( v ) {
  5572. this.x = v.x;
  5573. this.y = v.y;
  5574. this.z = v.z;
  5575. return this;
  5576. },
  5577. add: function ( v, w ) {
  5578. if ( w !== undefined ) {
  5579. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  5580. return this.addVectors( v, w );
  5581. }
  5582. this.x += v.x;
  5583. this.y += v.y;
  5584. this.z += v.z;
  5585. return this;
  5586. },
  5587. addScalar: function ( s ) {
  5588. this.x += s;
  5589. this.y += s;
  5590. this.z += s;
  5591. return this;
  5592. },
  5593. addVectors: function ( a, b ) {
  5594. this.x = a.x + b.x;
  5595. this.y = a.y + b.y;
  5596. this.z = a.z + b.z;
  5597. return this;
  5598. },
  5599. addScaledVector: function ( v, s ) {
  5600. this.x += v.x * s;
  5601. this.y += v.y * s;
  5602. this.z += v.z * s;
  5603. return this;
  5604. },
  5605. sub: function ( v, w ) {
  5606. if ( w !== undefined ) {
  5607. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  5608. return this.subVectors( v, w );
  5609. }
  5610. this.x -= v.x;
  5611. this.y -= v.y;
  5612. this.z -= v.z;
  5613. return this;
  5614. },
  5615. subScalar: function ( s ) {
  5616. this.x -= s;
  5617. this.y -= s;
  5618. this.z -= s;
  5619. return this;
  5620. },
  5621. subVectors: function ( a, b ) {
  5622. this.x = a.x - b.x;
  5623. this.y = a.y - b.y;
  5624. this.z = a.z - b.z;
  5625. return this;
  5626. },
  5627. multiply: function ( v, w ) {
  5628. if ( w !== undefined ) {
  5629. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  5630. return this.multiplyVectors( v, w );
  5631. }
  5632. this.x *= v.x;
  5633. this.y *= v.y;
  5634. this.z *= v.z;
  5635. return this;
  5636. },
  5637. multiplyScalar: function ( scalar ) {
  5638. this.x *= scalar;
  5639. this.y *= scalar;
  5640. this.z *= scalar;
  5641. return this;
  5642. },
  5643. multiplyVectors: function ( a, b ) {
  5644. this.x = a.x * b.x;
  5645. this.y = a.y * b.y;
  5646. this.z = a.z * b.z;
  5647. return this;
  5648. },
  5649. applyEuler: function () {
  5650. var quaternion = new Quaternion();
  5651. return function applyEuler( euler ) {
  5652. if ( ! ( euler && euler.isEuler ) ) {
  5653. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5654. }
  5655. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  5656. };
  5657. }(),
  5658. applyAxisAngle: function () {
  5659. var quaternion = new Quaternion();
  5660. return function applyAxisAngle( axis, angle ) {
  5661. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  5662. };
  5663. }(),
  5664. applyMatrix3: function ( m ) {
  5665. var x = this.x, y = this.y, z = this.z;
  5666. var e = m.elements;
  5667. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  5668. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  5669. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  5670. return this;
  5671. },
  5672. applyMatrix4: function ( m ) {
  5673. var x = this.x, y = this.y, z = this.z;
  5674. var e = m.elements;
  5675. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  5676. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  5677. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  5678. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  5679. return this;
  5680. },
  5681. applyQuaternion: function ( q ) {
  5682. var x = this.x, y = this.y, z = this.z;
  5683. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  5684. // calculate quat * vector
  5685. var ix = qw * x + qy * z - qz * y;
  5686. var iy = qw * y + qz * x - qx * z;
  5687. var iz = qw * z + qx * y - qy * x;
  5688. var iw = - qx * x - qy * y - qz * z;
  5689. // calculate result * inverse quat
  5690. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  5691. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  5692. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  5693. return this;
  5694. },
  5695. project: function () {
  5696. var matrix = new Matrix4();
  5697. return function project( camera ) {
  5698. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  5699. return this.applyMatrix4( matrix );
  5700. };
  5701. }(),
  5702. unproject: function () {
  5703. var matrix = new Matrix4();
  5704. return function unproject( camera ) {
  5705. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  5706. return this.applyMatrix4( matrix );
  5707. };
  5708. }(),
  5709. transformDirection: function ( m ) {
  5710. // input: THREE.Matrix4 affine matrix
  5711. // vector interpreted as a direction
  5712. var x = this.x, y = this.y, z = this.z;
  5713. var e = m.elements;
  5714. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  5715. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  5716. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  5717. return this.normalize();
  5718. },
  5719. divide: function ( v ) {
  5720. this.x /= v.x;
  5721. this.y /= v.y;
  5722. this.z /= v.z;
  5723. return this;
  5724. },
  5725. divideScalar: function ( scalar ) {
  5726. return this.multiplyScalar( 1 / scalar );
  5727. },
  5728. min: function ( v ) {
  5729. this.x = Math.min( this.x, v.x );
  5730. this.y = Math.min( this.y, v.y );
  5731. this.z = Math.min( this.z, v.z );
  5732. return this;
  5733. },
  5734. max: function ( v ) {
  5735. this.x = Math.max( this.x, v.x );
  5736. this.y = Math.max( this.y, v.y );
  5737. this.z = Math.max( this.z, v.z );
  5738. return this;
  5739. },
  5740. clamp: function ( min, max ) {
  5741. // assumes min < max, componentwise
  5742. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  5743. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  5744. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  5745. return this;
  5746. },
  5747. clampScalar: function () {
  5748. var min = new Vector3();
  5749. var max = new Vector3();
  5750. return function clampScalar( minVal, maxVal ) {
  5751. min.set( minVal, minVal, minVal );
  5752. max.set( maxVal, maxVal, maxVal );
  5753. return this.clamp( min, max );
  5754. };
  5755. }(),
  5756. clampLength: function ( min, max ) {
  5757. var length = this.length();
  5758. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  5759. },
  5760. floor: function () {
  5761. this.x = Math.floor( this.x );
  5762. this.y = Math.floor( this.y );
  5763. this.z = Math.floor( this.z );
  5764. return this;
  5765. },
  5766. ceil: function () {
  5767. this.x = Math.ceil( this.x );
  5768. this.y = Math.ceil( this.y );
  5769. this.z = Math.ceil( this.z );
  5770. return this;
  5771. },
  5772. round: function () {
  5773. this.x = Math.round( this.x );
  5774. this.y = Math.round( this.y );
  5775. this.z = Math.round( this.z );
  5776. return this;
  5777. },
  5778. roundToZero: function () {
  5779. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  5780. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  5781. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  5782. return this;
  5783. },
  5784. negate: function () {
  5785. this.x = - this.x;
  5786. this.y = - this.y;
  5787. this.z = - this.z;
  5788. return this;
  5789. },
  5790. dot: function ( v ) {
  5791. return this.x * v.x + this.y * v.y + this.z * v.z;
  5792. },
  5793. // TODO lengthSquared?
  5794. lengthSq: function () {
  5795. return this.x * this.x + this.y * this.y + this.z * this.z;
  5796. },
  5797. length: function () {
  5798. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  5799. },
  5800. manhattanLength: function () {
  5801. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  5802. },
  5803. normalize: function () {
  5804. return this.divideScalar( this.length() || 1 );
  5805. },
  5806. setLength: function ( length ) {
  5807. return this.normalize().multiplyScalar( length );
  5808. },
  5809. lerp: function ( v, alpha ) {
  5810. this.x += ( v.x - this.x ) * alpha;
  5811. this.y += ( v.y - this.y ) * alpha;
  5812. this.z += ( v.z - this.z ) * alpha;
  5813. return this;
  5814. },
  5815. lerpVectors: function ( v1, v2, alpha ) {
  5816. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  5817. },
  5818. cross: function ( v, w ) {
  5819. if ( w !== undefined ) {
  5820. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  5821. return this.crossVectors( v, w );
  5822. }
  5823. return this.crossVectors( this, v );
  5824. },
  5825. crossVectors: function ( a, b ) {
  5826. var ax = a.x, ay = a.y, az = a.z;
  5827. var bx = b.x, by = b.y, bz = b.z;
  5828. this.x = ay * bz - az * by;
  5829. this.y = az * bx - ax * bz;
  5830. this.z = ax * by - ay * bx;
  5831. return this;
  5832. },
  5833. projectOnVector: function ( vector ) {
  5834. var scalar = vector.dot( this ) / vector.lengthSq();
  5835. return this.copy( vector ).multiplyScalar( scalar );
  5836. },
  5837. projectOnPlane: function () {
  5838. var v1 = new Vector3();
  5839. return function projectOnPlane( planeNormal ) {
  5840. v1.copy( this ).projectOnVector( planeNormal );
  5841. return this.sub( v1 );
  5842. };
  5843. }(),
  5844. reflect: function () {
  5845. // reflect incident vector off plane orthogonal to normal
  5846. // normal is assumed to have unit length
  5847. var v1 = new Vector3();
  5848. return function reflect( normal ) {
  5849. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  5850. };
  5851. }(),
  5852. angleTo: function ( v ) {
  5853. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  5854. // clamp, to handle numerical problems
  5855. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  5856. },
  5857. distanceTo: function ( v ) {
  5858. return Math.sqrt( this.distanceToSquared( v ) );
  5859. },
  5860. distanceToSquared: function ( v ) {
  5861. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  5862. return dx * dx + dy * dy + dz * dz;
  5863. },
  5864. manhattanDistanceTo: function ( v ) {
  5865. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  5866. },
  5867. setFromSpherical: function ( s ) {
  5868. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  5869. this.x = sinPhiRadius * Math.sin( s.theta );
  5870. this.y = Math.cos( s.phi ) * s.radius;
  5871. this.z = sinPhiRadius * Math.cos( s.theta );
  5872. return this;
  5873. },
  5874. setFromCylindrical: function ( c ) {
  5875. this.x = c.radius * Math.sin( c.theta );
  5876. this.y = c.y;
  5877. this.z = c.radius * Math.cos( c.theta );
  5878. return this;
  5879. },
  5880. setFromMatrixPosition: function ( m ) {
  5881. var e = m.elements;
  5882. this.x = e[ 12 ];
  5883. this.y = e[ 13 ];
  5884. this.z = e[ 14 ];
  5885. return this;
  5886. },
  5887. setFromMatrixScale: function ( m ) {
  5888. var sx = this.setFromMatrixColumn( m, 0 ).length();
  5889. var sy = this.setFromMatrixColumn( m, 1 ).length();
  5890. var sz = this.setFromMatrixColumn( m, 2 ).length();
  5891. this.x = sx;
  5892. this.y = sy;
  5893. this.z = sz;
  5894. return this;
  5895. },
  5896. setFromMatrixColumn: function ( m, index ) {
  5897. return this.fromArray( m.elements, index * 4 );
  5898. },
  5899. equals: function ( v ) {
  5900. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  5901. },
  5902. fromArray: function ( array, offset ) {
  5903. if ( offset === undefined ) offset = 0;
  5904. this.x = array[ offset ];
  5905. this.y = array[ offset + 1 ];
  5906. this.z = array[ offset + 2 ];
  5907. return this;
  5908. },
  5909. toArray: function ( array, offset ) {
  5910. if ( array === undefined ) array = [];
  5911. if ( offset === undefined ) offset = 0;
  5912. array[ offset ] = this.x;
  5913. array[ offset + 1 ] = this.y;
  5914. array[ offset + 2 ] = this.z;
  5915. return array;
  5916. },
  5917. fromBufferAttribute: function ( attribute, index, offset ) {
  5918. if ( offset !== undefined ) {
  5919. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  5920. }
  5921. this.x = attribute.getX( index );
  5922. this.y = attribute.getY( index );
  5923. this.z = attribute.getZ( index );
  5924. return this;
  5925. }
  5926. } );
  5927. /**
  5928. * @author alteredq / http://alteredqualia.com/
  5929. * @author WestLangley / http://github.com/WestLangley
  5930. * @author bhouston / http://clara.io
  5931. * @author tschw
  5932. */
  5933. function Matrix3() {
  5934. this.elements = [
  5935. 1, 0, 0,
  5936. 0, 1, 0,
  5937. 0, 0, 1
  5938. ];
  5939. if ( arguments.length > 0 ) {
  5940. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5941. }
  5942. }
  5943. Object.assign( Matrix3.prototype, {
  5944. isMatrix3: true,
  5945. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5946. var te = this.elements;
  5947. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5948. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5949. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5950. return this;
  5951. },
  5952. identity: function () {
  5953. this.set(
  5954. 1, 0, 0,
  5955. 0, 1, 0,
  5956. 0, 0, 1
  5957. );
  5958. return this;
  5959. },
  5960. clone: function () {
  5961. return new this.constructor().fromArray( this.elements );
  5962. },
  5963. copy: function ( m ) {
  5964. var te = this.elements;
  5965. var me = m.elements;
  5966. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  5967. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  5968. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  5969. return this;
  5970. },
  5971. setFromMatrix4: function ( m ) {
  5972. var me = m.elements;
  5973. this.set(
  5974. me[ 0 ], me[ 4 ], me[ 8 ],
  5975. me[ 1 ], me[ 5 ], me[ 9 ],
  5976. me[ 2 ], me[ 6 ], me[ 10 ]
  5977. );
  5978. return this;
  5979. },
  5980. applyToBufferAttribute: function () {
  5981. var v1 = new Vector3();
  5982. return function applyToBufferAttribute( attribute ) {
  5983. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5984. v1.x = attribute.getX( i );
  5985. v1.y = attribute.getY( i );
  5986. v1.z = attribute.getZ( i );
  5987. v1.applyMatrix3( this );
  5988. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5989. }
  5990. return attribute;
  5991. };
  5992. }(),
  5993. multiply: function ( m ) {
  5994. return this.multiplyMatrices( this, m );
  5995. },
  5996. premultiply: function ( m ) {
  5997. return this.multiplyMatrices( m, this );
  5998. },
  5999. multiplyMatrices: function ( a, b ) {
  6000. var ae = a.elements;
  6001. var be = b.elements;
  6002. var te = this.elements;
  6003. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  6004. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  6005. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  6006. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  6007. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  6008. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  6009. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  6010. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  6011. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  6012. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  6013. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  6014. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  6015. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  6016. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  6017. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  6018. return this;
  6019. },
  6020. multiplyScalar: function ( s ) {
  6021. var te = this.elements;
  6022. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  6023. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  6024. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  6025. return this;
  6026. },
  6027. determinant: function () {
  6028. var te = this.elements;
  6029. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  6030. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  6031. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  6032. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  6033. },
  6034. getInverse: function ( matrix, throwOnDegenerate ) {
  6035. if ( matrix && matrix.isMatrix4 ) {
  6036. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  6037. }
  6038. var me = matrix.elements,
  6039. te = this.elements,
  6040. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  6041. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  6042. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  6043. t11 = n33 * n22 - n32 * n23,
  6044. t12 = n32 * n13 - n33 * n12,
  6045. t13 = n23 * n12 - n22 * n13,
  6046. det = n11 * t11 + n21 * t12 + n31 * t13;
  6047. if ( det === 0 ) {
  6048. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  6049. if ( throwOnDegenerate === true ) {
  6050. throw new Error( msg );
  6051. } else {
  6052. console.warn( msg );
  6053. }
  6054. return this.identity();
  6055. }
  6056. var detInv = 1 / det;
  6057. te[ 0 ] = t11 * detInv;
  6058. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  6059. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  6060. te[ 3 ] = t12 * detInv;
  6061. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  6062. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  6063. te[ 6 ] = t13 * detInv;
  6064. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  6065. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  6066. return this;
  6067. },
  6068. transpose: function () {
  6069. var tmp, m = this.elements;
  6070. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  6071. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  6072. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  6073. return this;
  6074. },
  6075. getNormalMatrix: function ( matrix4 ) {
  6076. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  6077. },
  6078. transposeIntoArray: function ( r ) {
  6079. var m = this.elements;
  6080. r[ 0 ] = m[ 0 ];
  6081. r[ 1 ] = m[ 3 ];
  6082. r[ 2 ] = m[ 6 ];
  6083. r[ 3 ] = m[ 1 ];
  6084. r[ 4 ] = m[ 4 ];
  6085. r[ 5 ] = m[ 7 ];
  6086. r[ 6 ] = m[ 2 ];
  6087. r[ 7 ] = m[ 5 ];
  6088. r[ 8 ] = m[ 8 ];
  6089. return this;
  6090. },
  6091. setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {
  6092. var c = Math.cos( rotation );
  6093. var s = Math.sin( rotation );
  6094. this.set(
  6095. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  6096. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  6097. 0, 0, 1
  6098. );
  6099. },
  6100. scale: function ( sx, sy ) {
  6101. var te = this.elements;
  6102. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  6103. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  6104. return this;
  6105. },
  6106. rotate: function ( theta ) {
  6107. var c = Math.cos( theta );
  6108. var s = Math.sin( theta );
  6109. var te = this.elements;
  6110. var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  6111. var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  6112. te[ 0 ] = c * a11 + s * a21;
  6113. te[ 3 ] = c * a12 + s * a22;
  6114. te[ 6 ] = c * a13 + s * a23;
  6115. te[ 1 ] = - s * a11 + c * a21;
  6116. te[ 4 ] = - s * a12 + c * a22;
  6117. te[ 7 ] = - s * a13 + c * a23;
  6118. return this;
  6119. },
  6120. translate: function ( tx, ty ) {
  6121. var te = this.elements;
  6122. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  6123. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  6124. return this;
  6125. },
  6126. equals: function ( matrix ) {
  6127. var te = this.elements;
  6128. var me = matrix.elements;
  6129. for ( var i = 0; i < 9; i ++ ) {
  6130. if ( te[ i ] !== me[ i ] ) return false;
  6131. }
  6132. return true;
  6133. },
  6134. fromArray: function ( array, offset ) {
  6135. if ( offset === undefined ) offset = 0;
  6136. for ( var i = 0; i < 9; i ++ ) {
  6137. this.elements[ i ] = array[ i + offset ];
  6138. }
  6139. return this;
  6140. },
  6141. toArray: function ( array, offset ) {
  6142. if ( array === undefined ) array = [];
  6143. if ( offset === undefined ) offset = 0;
  6144. var te = this.elements;
  6145. array[ offset ] = te[ 0 ];
  6146. array[ offset + 1 ] = te[ 1 ];
  6147. array[ offset + 2 ] = te[ 2 ];
  6148. array[ offset + 3 ] = te[ 3 ];
  6149. array[ offset + 4 ] = te[ 4 ];
  6150. array[ offset + 5 ] = te[ 5 ];
  6151. array[ offset + 6 ] = te[ 6 ];
  6152. array[ offset + 7 ] = te[ 7 ];
  6153. array[ offset + 8 ] = te[ 8 ];
  6154. return array;
  6155. }
  6156. } );
  6157. /**
  6158. * @author mrdoob / http://mrdoob.com/
  6159. * @author alteredq / http://alteredqualia.com/
  6160. * @author szimek / https://github.com/szimek/
  6161. */
  6162. var ImageUtils = {
  6163. getDataURL: function ( image ) {
  6164. var canvas;
  6165. if ( image instanceof HTMLCanvasElement ) {
  6166. canvas = image;
  6167. } else {
  6168. if ( typeof OffscreenCanvas !== 'undefined' ) {
  6169. canvas = new OffscreenCanvas( image.width, image.height );
  6170. } else {
  6171. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  6172. canvas.width = image.width;
  6173. canvas.height = image.height;
  6174. }
  6175. var context = canvas.getContext( '2d' );
  6176. if ( image instanceof ImageData ) {
  6177. context.putImageData( image, 0, 0 );
  6178. } else {
  6179. context.drawImage( image, 0, 0, image.width, image.height );
  6180. }
  6181. }
  6182. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  6183. return canvas.toDataURL( 'image/jpeg', 0.6 );
  6184. } else {
  6185. return canvas.toDataURL( 'image/png' );
  6186. }
  6187. }
  6188. };
  6189. /**
  6190. * @author mrdoob / http://mrdoob.com/
  6191. * @author alteredq / http://alteredqualia.com/
  6192. * @author szimek / https://github.com/szimek/
  6193. */
  6194. var textureId = 0;
  6195. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  6196. Object.defineProperty( this, 'id', { value: textureId ++ } );
  6197. this.uuid = _Math.generateUUID();
  6198. this.name = '';
  6199. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  6200. this.mipmaps = [];
  6201. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  6202. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  6203. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  6204. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  6205. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  6206. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6207. this.format = format !== undefined ? format : RGBAFormat;
  6208. this.type = type !== undefined ? type : UnsignedByteType;
  6209. this.offset = new Vector2( 0, 0 );
  6210. this.repeat = new Vector2( 1, 1 );
  6211. this.center = new Vector2( 0, 0 );
  6212. this.rotation = 0;
  6213. this.matrixAutoUpdate = true;
  6214. this.matrix = new Matrix3();
  6215. this.generateMipmaps = true;
  6216. this.premultiplyAlpha = false;
  6217. this.flipY = true;
  6218. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  6219. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  6220. //
  6221. // Also changing the encoding after already used by a Material will not automatically make the Material
  6222. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  6223. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  6224. this.version = 0;
  6225. this.onUpdate = null;
  6226. }
  6227. Texture.DEFAULT_IMAGE = undefined;
  6228. Texture.DEFAULT_MAPPING = UVMapping;
  6229. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6230. constructor: Texture,
  6231. isTexture: true,
  6232. updateMatrix: function () {
  6233. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  6234. },
  6235. clone: function () {
  6236. return new this.constructor().copy( this );
  6237. },
  6238. copy: function ( source ) {
  6239. this.name = source.name;
  6240. this.image = source.image;
  6241. this.mipmaps = source.mipmaps.slice( 0 );
  6242. this.mapping = source.mapping;
  6243. this.wrapS = source.wrapS;
  6244. this.wrapT = source.wrapT;
  6245. this.magFilter = source.magFilter;
  6246. this.minFilter = source.minFilter;
  6247. this.anisotropy = source.anisotropy;
  6248. this.format = source.format;
  6249. this.type = source.type;
  6250. this.offset.copy( source.offset );
  6251. this.repeat.copy( source.repeat );
  6252. this.center.copy( source.center );
  6253. this.rotation = source.rotation;
  6254. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6255. this.matrix.copy( source.matrix );
  6256. this.generateMipmaps = source.generateMipmaps;
  6257. this.premultiplyAlpha = source.premultiplyAlpha;
  6258. this.flipY = source.flipY;
  6259. this.unpackAlignment = source.unpackAlignment;
  6260. this.encoding = source.encoding;
  6261. return this;
  6262. },
  6263. toJSON: function ( meta ) {
  6264. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  6265. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6266. return meta.textures[ this.uuid ];
  6267. }
  6268. var output = {
  6269. metadata: {
  6270. version: 4.5,
  6271. type: 'Texture',
  6272. generator: 'Texture.toJSON'
  6273. },
  6274. uuid: this.uuid,
  6275. name: this.name,
  6276. mapping: this.mapping,
  6277. repeat: [ this.repeat.x, this.repeat.y ],
  6278. offset: [ this.offset.x, this.offset.y ],
  6279. center: [ this.center.x, this.center.y ],
  6280. rotation: this.rotation,
  6281. wrap: [ this.wrapS, this.wrapT ],
  6282. format: this.format,
  6283. minFilter: this.minFilter,
  6284. magFilter: this.magFilter,
  6285. anisotropy: this.anisotropy,
  6286. flipY: this.flipY
  6287. };
  6288. if ( this.image !== undefined ) {
  6289. // TODO: Move to THREE.Image
  6290. var image = this.image;
  6291. if ( image.uuid === undefined ) {
  6292. image.uuid = _Math.generateUUID(); // UGH
  6293. }
  6294. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  6295. var url;
  6296. if ( Array.isArray( image ) ) {
  6297. // process array of images e.g. CubeTexture
  6298. url = [];
  6299. for ( var i = 0, l = image.length; i < l; i ++ ) {
  6300. url.push( ImageUtils.getDataURL( image[ i ] ) );
  6301. }
  6302. } else {
  6303. // process single image
  6304. url = ImageUtils.getDataURL( image );
  6305. }
  6306. meta.images[ image.uuid ] = {
  6307. uuid: image.uuid,
  6308. url: url
  6309. };
  6310. }
  6311. output.image = image.uuid;
  6312. }
  6313. if ( ! isRootObject ) {
  6314. meta.textures[ this.uuid ] = output;
  6315. }
  6316. return output;
  6317. },
  6318. dispose: function () {
  6319. this.dispatchEvent( { type: 'dispose' } );
  6320. },
  6321. transformUv: function ( uv ) {
  6322. if ( this.mapping !== UVMapping ) return;
  6323. uv.applyMatrix3( this.matrix );
  6324. if ( uv.x < 0 || uv.x > 1 ) {
  6325. switch ( this.wrapS ) {
  6326. case RepeatWrapping:
  6327. uv.x = uv.x - Math.floor( uv.x );
  6328. break;
  6329. case ClampToEdgeWrapping:
  6330. uv.x = uv.x < 0 ? 0 : 1;
  6331. break;
  6332. case MirroredRepeatWrapping:
  6333. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6334. uv.x = Math.ceil( uv.x ) - uv.x;
  6335. } else {
  6336. uv.x = uv.x - Math.floor( uv.x );
  6337. }
  6338. break;
  6339. }
  6340. }
  6341. if ( uv.y < 0 || uv.y > 1 ) {
  6342. switch ( this.wrapT ) {
  6343. case RepeatWrapping:
  6344. uv.y = uv.y - Math.floor( uv.y );
  6345. break;
  6346. case ClampToEdgeWrapping:
  6347. uv.y = uv.y < 0 ? 0 : 1;
  6348. break;
  6349. case MirroredRepeatWrapping:
  6350. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6351. uv.y = Math.ceil( uv.y ) - uv.y;
  6352. } else {
  6353. uv.y = uv.y - Math.floor( uv.y );
  6354. }
  6355. break;
  6356. }
  6357. }
  6358. if ( this.flipY ) {
  6359. uv.y = 1 - uv.y;
  6360. }
  6361. }
  6362. } );
  6363. Object.defineProperty( Texture.prototype, "needsUpdate", {
  6364. set: function ( value ) {
  6365. if ( value === true ) this.version ++;
  6366. }
  6367. } );
  6368. /**
  6369. * @author supereggbert / http://www.paulbrunt.co.uk/
  6370. * @author philogb / http://blog.thejit.org/
  6371. * @author mikael emtinger / http://gomo.se/
  6372. * @author egraether / http://egraether.com/
  6373. * @author WestLangley / http://github.com/WestLangley
  6374. */
  6375. function Vector4( x, y, z, w ) {
  6376. this.x = x || 0;
  6377. this.y = y || 0;
  6378. this.z = z || 0;
  6379. this.w = ( w !== undefined ) ? w : 1;
  6380. }
  6381. Object.assign( Vector4.prototype, {
  6382. isVector4: true,
  6383. set: function ( x, y, z, w ) {
  6384. this.x = x;
  6385. this.y = y;
  6386. this.z = z;
  6387. this.w = w;
  6388. return this;
  6389. },
  6390. setScalar: function ( scalar ) {
  6391. this.x = scalar;
  6392. this.y = scalar;
  6393. this.z = scalar;
  6394. this.w = scalar;
  6395. return this;
  6396. },
  6397. setX: function ( x ) {
  6398. this.x = x;
  6399. return this;
  6400. },
  6401. setY: function ( y ) {
  6402. this.y = y;
  6403. return this;
  6404. },
  6405. setZ: function ( z ) {
  6406. this.z = z;
  6407. return this;
  6408. },
  6409. setW: function ( w ) {
  6410. this.w = w;
  6411. return this;
  6412. },
  6413. setComponent: function ( index, value ) {
  6414. switch ( index ) {
  6415. case 0: this.x = value; break;
  6416. case 1: this.y = value; break;
  6417. case 2: this.z = value; break;
  6418. case 3: this.w = value; break;
  6419. default: throw new Error( 'index is out of range: ' + index );
  6420. }
  6421. return this;
  6422. },
  6423. getComponent: function ( index ) {
  6424. switch ( index ) {
  6425. case 0: return this.x;
  6426. case 1: return this.y;
  6427. case 2: return this.z;
  6428. case 3: return this.w;
  6429. default: throw new Error( 'index is out of range: ' + index );
  6430. }
  6431. },
  6432. clone: function () {
  6433. return new this.constructor( this.x, this.y, this.z, this.w );
  6434. },
  6435. copy: function ( v ) {
  6436. this.x = v.x;
  6437. this.y = v.y;
  6438. this.z = v.z;
  6439. this.w = ( v.w !== undefined ) ? v.w : 1;
  6440. return this;
  6441. },
  6442. add: function ( v, w ) {
  6443. if ( w !== undefined ) {
  6444. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6445. return this.addVectors( v, w );
  6446. }
  6447. this.x += v.x;
  6448. this.y += v.y;
  6449. this.z += v.z;
  6450. this.w += v.w;
  6451. return this;
  6452. },
  6453. addScalar: function ( s ) {
  6454. this.x += s;
  6455. this.y += s;
  6456. this.z += s;
  6457. this.w += s;
  6458. return this;
  6459. },
  6460. addVectors: function ( a, b ) {
  6461. this.x = a.x + b.x;
  6462. this.y = a.y + b.y;
  6463. this.z = a.z + b.z;
  6464. this.w = a.w + b.w;
  6465. return this;
  6466. },
  6467. addScaledVector: function ( v, s ) {
  6468. this.x += v.x * s;
  6469. this.y += v.y * s;
  6470. this.z += v.z * s;
  6471. this.w += v.w * s;
  6472. return this;
  6473. },
  6474. sub: function ( v, w ) {
  6475. if ( w !== undefined ) {
  6476. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6477. return this.subVectors( v, w );
  6478. }
  6479. this.x -= v.x;
  6480. this.y -= v.y;
  6481. this.z -= v.z;
  6482. this.w -= v.w;
  6483. return this;
  6484. },
  6485. subScalar: function ( s ) {
  6486. this.x -= s;
  6487. this.y -= s;
  6488. this.z -= s;
  6489. this.w -= s;
  6490. return this;
  6491. },
  6492. subVectors: function ( a, b ) {
  6493. this.x = a.x - b.x;
  6494. this.y = a.y - b.y;
  6495. this.z = a.z - b.z;
  6496. this.w = a.w - b.w;
  6497. return this;
  6498. },
  6499. multiplyScalar: function ( scalar ) {
  6500. this.x *= scalar;
  6501. this.y *= scalar;
  6502. this.z *= scalar;
  6503. this.w *= scalar;
  6504. return this;
  6505. },
  6506. applyMatrix4: function ( m ) {
  6507. var x = this.x, y = this.y, z = this.z, w = this.w;
  6508. var e = m.elements;
  6509. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6510. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6511. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6512. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6513. return this;
  6514. },
  6515. divideScalar: function ( scalar ) {
  6516. return this.multiplyScalar( 1 / scalar );
  6517. },
  6518. setAxisAngleFromQuaternion: function ( q ) {
  6519. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6520. // q is assumed to be normalized
  6521. this.w = 2 * Math.acos( q.w );
  6522. var s = Math.sqrt( 1 - q.w * q.w );
  6523. if ( s < 0.0001 ) {
  6524. this.x = 1;
  6525. this.y = 0;
  6526. this.z = 0;
  6527. } else {
  6528. this.x = q.x / s;
  6529. this.y = q.y / s;
  6530. this.z = q.z / s;
  6531. }
  6532. return this;
  6533. },
  6534. setAxisAngleFromRotationMatrix: function ( m ) {
  6535. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6536. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6537. var angle, x, y, z, // variables for result
  6538. epsilon = 0.01, // margin to allow for rounding errors
  6539. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6540. te = m.elements,
  6541. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6542. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6543. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6544. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6545. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6546. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6547. // singularity found
  6548. // first check for identity matrix which must have +1 for all terms
  6549. // in leading diagonal and zero in other terms
  6550. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6551. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6552. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6553. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6554. // this singularity is identity matrix so angle = 0
  6555. this.set( 1, 0, 0, 0 );
  6556. return this; // zero angle, arbitrary axis
  6557. }
  6558. // otherwise this singularity is angle = 180
  6559. angle = Math.PI;
  6560. var xx = ( m11 + 1 ) / 2;
  6561. var yy = ( m22 + 1 ) / 2;
  6562. var zz = ( m33 + 1 ) / 2;
  6563. var xy = ( m12 + m21 ) / 4;
  6564. var xz = ( m13 + m31 ) / 4;
  6565. var yz = ( m23 + m32 ) / 4;
  6566. if ( ( xx > yy ) && ( xx > zz ) ) {
  6567. // m11 is the largest diagonal term
  6568. if ( xx < epsilon ) {
  6569. x = 0;
  6570. y = 0.707106781;
  6571. z = 0.707106781;
  6572. } else {
  6573. x = Math.sqrt( xx );
  6574. y = xy / x;
  6575. z = xz / x;
  6576. }
  6577. } else if ( yy > zz ) {
  6578. // m22 is the largest diagonal term
  6579. if ( yy < epsilon ) {
  6580. x = 0.707106781;
  6581. y = 0;
  6582. z = 0.707106781;
  6583. } else {
  6584. y = Math.sqrt( yy );
  6585. x = xy / y;
  6586. z = yz / y;
  6587. }
  6588. } else {
  6589. // m33 is the largest diagonal term so base result on this
  6590. if ( zz < epsilon ) {
  6591. x = 0.707106781;
  6592. y = 0.707106781;
  6593. z = 0;
  6594. } else {
  6595. z = Math.sqrt( zz );
  6596. x = xz / z;
  6597. y = yz / z;
  6598. }
  6599. }
  6600. this.set( x, y, z, angle );
  6601. return this; // return 180 deg rotation
  6602. }
  6603. // as we have reached here there are no singularities so we can handle normally
  6604. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6605. ( m13 - m31 ) * ( m13 - m31 ) +
  6606. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6607. if ( Math.abs( s ) < 0.001 ) s = 1;
  6608. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6609. // caught by singularity test above, but I've left it in just in case
  6610. this.x = ( m32 - m23 ) / s;
  6611. this.y = ( m13 - m31 ) / s;
  6612. this.z = ( m21 - m12 ) / s;
  6613. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6614. return this;
  6615. },
  6616. min: function ( v ) {
  6617. this.x = Math.min( this.x, v.x );
  6618. this.y = Math.min( this.y, v.y );
  6619. this.z = Math.min( this.z, v.z );
  6620. this.w = Math.min( this.w, v.w );
  6621. return this;
  6622. },
  6623. max: function ( v ) {
  6624. this.x = Math.max( this.x, v.x );
  6625. this.y = Math.max( this.y, v.y );
  6626. this.z = Math.max( this.z, v.z );
  6627. this.w = Math.max( this.w, v.w );
  6628. return this;
  6629. },
  6630. clamp: function ( min, max ) {
  6631. // assumes min < max, componentwise
  6632. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6633. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6634. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6635. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  6636. return this;
  6637. },
  6638. clampScalar: function () {
  6639. var min, max;
  6640. return function clampScalar( minVal, maxVal ) {
  6641. if ( min === undefined ) {
  6642. min = new Vector4();
  6643. max = new Vector4();
  6644. }
  6645. min.set( minVal, minVal, minVal, minVal );
  6646. max.set( maxVal, maxVal, maxVal, maxVal );
  6647. return this.clamp( min, max );
  6648. };
  6649. }(),
  6650. clampLength: function ( min, max ) {
  6651. var length = this.length();
  6652. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6653. },
  6654. floor: function () {
  6655. this.x = Math.floor( this.x );
  6656. this.y = Math.floor( this.y );
  6657. this.z = Math.floor( this.z );
  6658. this.w = Math.floor( this.w );
  6659. return this;
  6660. },
  6661. ceil: function () {
  6662. this.x = Math.ceil( this.x );
  6663. this.y = Math.ceil( this.y );
  6664. this.z = Math.ceil( this.z );
  6665. this.w = Math.ceil( this.w );
  6666. return this;
  6667. },
  6668. round: function () {
  6669. this.x = Math.round( this.x );
  6670. this.y = Math.round( this.y );
  6671. this.z = Math.round( this.z );
  6672. this.w = Math.round( this.w );
  6673. return this;
  6674. },
  6675. roundToZero: function () {
  6676. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6677. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6678. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  6679. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  6680. return this;
  6681. },
  6682. negate: function () {
  6683. this.x = - this.x;
  6684. this.y = - this.y;
  6685. this.z = - this.z;
  6686. this.w = - this.w;
  6687. return this;
  6688. },
  6689. dot: function ( v ) {
  6690. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6691. },
  6692. lengthSq: function () {
  6693. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6694. },
  6695. length: function () {
  6696. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6697. },
  6698. manhattanLength: function () {
  6699. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6700. },
  6701. normalize: function () {
  6702. return this.divideScalar( this.length() || 1 );
  6703. },
  6704. setLength: function ( length ) {
  6705. return this.normalize().multiplyScalar( length );
  6706. },
  6707. lerp: function ( v, alpha ) {
  6708. this.x += ( v.x - this.x ) * alpha;
  6709. this.y += ( v.y - this.y ) * alpha;
  6710. this.z += ( v.z - this.z ) * alpha;
  6711. this.w += ( v.w - this.w ) * alpha;
  6712. return this;
  6713. },
  6714. lerpVectors: function ( v1, v2, alpha ) {
  6715. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6716. },
  6717. equals: function ( v ) {
  6718. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6719. },
  6720. fromArray: function ( array, offset ) {
  6721. if ( offset === undefined ) offset = 0;
  6722. this.x = array[ offset ];
  6723. this.y = array[ offset + 1 ];
  6724. this.z = array[ offset + 2 ];
  6725. this.w = array[ offset + 3 ];
  6726. return this;
  6727. },
  6728. toArray: function ( array, offset ) {
  6729. if ( array === undefined ) array = [];
  6730. if ( offset === undefined ) offset = 0;
  6731. array[ offset ] = this.x;
  6732. array[ offset + 1 ] = this.y;
  6733. array[ offset + 2 ] = this.z;
  6734. array[ offset + 3 ] = this.w;
  6735. return array;
  6736. },
  6737. fromBufferAttribute: function ( attribute, index, offset ) {
  6738. if ( offset !== undefined ) {
  6739. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  6740. }
  6741. this.x = attribute.getX( index );
  6742. this.y = attribute.getY( index );
  6743. this.z = attribute.getZ( index );
  6744. this.w = attribute.getW( index );
  6745. return this;
  6746. }
  6747. } );
  6748. /**
  6749. * @author szimek / https://github.com/szimek/
  6750. * @author alteredq / http://alteredqualia.com/
  6751. * @author Marius Kintel / https://github.com/kintel
  6752. */
  6753. /*
  6754. In options, we can specify:
  6755. * Texture parameters for an auto-generated target texture
  6756. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  6757. */
  6758. function WebGLRenderTarget( width, height, options ) {
  6759. this.width = width;
  6760. this.height = height;
  6761. this.scissor = new Vector4( 0, 0, width, height );
  6762. this.scissorTest = false;
  6763. this.viewport = new Vector4( 0, 0, width, height );
  6764. options = options || {};
  6765. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  6766. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  6767. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : true;
  6768. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  6769. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  6770. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  6771. }
  6772. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6773. constructor: WebGLRenderTarget,
  6774. isWebGLRenderTarget: true,
  6775. setSize: function ( width, height ) {
  6776. if ( this.width !== width || this.height !== height ) {
  6777. this.width = width;
  6778. this.height = height;
  6779. this.dispose();
  6780. }
  6781. this.viewport.set( 0, 0, width, height );
  6782. this.scissor.set( 0, 0, width, height );
  6783. },
  6784. clone: function () {
  6785. return new this.constructor().copy( this );
  6786. },
  6787. copy: function ( source ) {
  6788. this.width = source.width;
  6789. this.height = source.height;
  6790. this.viewport.copy( source.viewport );
  6791. this.texture = source.texture.clone();
  6792. this.depthBuffer = source.depthBuffer;
  6793. this.stencilBuffer = source.stencilBuffer;
  6794. this.depthTexture = source.depthTexture;
  6795. return this;
  6796. },
  6797. dispose: function () {
  6798. this.dispatchEvent( { type: 'dispose' } );
  6799. }
  6800. } );
  6801. /**
  6802. * @author alteredq / http://alteredqualia.com
  6803. */
  6804. function WebGLRenderTargetCube( width, height, options ) {
  6805. WebGLRenderTarget.call( this, width, height, options );
  6806. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  6807. this.activeMipMapLevel = 0;
  6808. }
  6809. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  6810. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  6811. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  6812. /**
  6813. * @author alteredq / http://alteredqualia.com/
  6814. */
  6815. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  6816. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  6817. this.image = { data: data, width: width, height: height };
  6818. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  6819. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  6820. this.generateMipmaps = false;
  6821. this.flipY = false;
  6822. this.unpackAlignment = 1;
  6823. }
  6824. DataTexture.prototype = Object.create( Texture.prototype );
  6825. DataTexture.prototype.constructor = DataTexture;
  6826. DataTexture.prototype.isDataTexture = true;
  6827. /**
  6828. * @author bhouston / http://clara.io
  6829. * @author WestLangley / http://github.com/WestLangley
  6830. */
  6831. function Box3( min, max ) {
  6832. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  6833. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  6834. }
  6835. Object.assign( Box3.prototype, {
  6836. isBox3: true,
  6837. set: function ( min, max ) {
  6838. this.min.copy( min );
  6839. this.max.copy( max );
  6840. return this;
  6841. },
  6842. setFromArray: function ( array ) {
  6843. var minX = + Infinity;
  6844. var minY = + Infinity;
  6845. var minZ = + Infinity;
  6846. var maxX = - Infinity;
  6847. var maxY = - Infinity;
  6848. var maxZ = - Infinity;
  6849. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  6850. var x = array[ i ];
  6851. var y = array[ i + 1 ];
  6852. var z = array[ i + 2 ];
  6853. if ( x < minX ) minX = x;
  6854. if ( y < minY ) minY = y;
  6855. if ( z < minZ ) minZ = z;
  6856. if ( x > maxX ) maxX = x;
  6857. if ( y > maxY ) maxY = y;
  6858. if ( z > maxZ ) maxZ = z;
  6859. }
  6860. this.min.set( minX, minY, minZ );
  6861. this.max.set( maxX, maxY, maxZ );
  6862. return this;
  6863. },
  6864. setFromBufferAttribute: function ( attribute ) {
  6865. var minX = + Infinity;
  6866. var minY = + Infinity;
  6867. var minZ = + Infinity;
  6868. var maxX = - Infinity;
  6869. var maxY = - Infinity;
  6870. var maxZ = - Infinity;
  6871. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  6872. var x = attribute.getX( i );
  6873. var y = attribute.getY( i );
  6874. var z = attribute.getZ( i );
  6875. if ( x < minX ) minX = x;
  6876. if ( y < minY ) minY = y;
  6877. if ( z < minZ ) minZ = z;
  6878. if ( x > maxX ) maxX = x;
  6879. if ( y > maxY ) maxY = y;
  6880. if ( z > maxZ ) maxZ = z;
  6881. }
  6882. this.min.set( minX, minY, minZ );
  6883. this.max.set( maxX, maxY, maxZ );
  6884. return this;
  6885. },
  6886. setFromPoints: function ( points ) {
  6887. this.makeEmpty();
  6888. for ( var i = 0, il = points.length; i < il; i ++ ) {
  6889. this.expandByPoint( points[ i ] );
  6890. }
  6891. return this;
  6892. },
  6893. setFromCenterAndSize: function () {
  6894. var v1 = new Vector3();
  6895. return function setFromCenterAndSize( center, size ) {
  6896. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  6897. this.min.copy( center ).sub( halfSize );
  6898. this.max.copy( center ).add( halfSize );
  6899. return this;
  6900. };
  6901. }(),
  6902. setFromObject: function ( object ) {
  6903. this.makeEmpty();
  6904. return this.expandByObject( object );
  6905. },
  6906. clone: function () {
  6907. return new this.constructor().copy( this );
  6908. },
  6909. copy: function ( box ) {
  6910. this.min.copy( box.min );
  6911. this.max.copy( box.max );
  6912. return this;
  6913. },
  6914. makeEmpty: function () {
  6915. this.min.x = this.min.y = this.min.z = + Infinity;
  6916. this.max.x = this.max.y = this.max.z = - Infinity;
  6917. return this;
  6918. },
  6919. isEmpty: function () {
  6920. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  6921. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  6922. },
  6923. getCenter: function ( target ) {
  6924. if ( target === undefined ) {
  6925. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  6926. target = new Vector3();
  6927. }
  6928. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  6929. },
  6930. getSize: function ( target ) {
  6931. if ( target === undefined ) {
  6932. console.warn( 'THREE.Box3: .getSize() target is now required' );
  6933. target = new Vector3();
  6934. }
  6935. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  6936. },
  6937. expandByPoint: function ( point ) {
  6938. this.min.min( point );
  6939. this.max.max( point );
  6940. return this;
  6941. },
  6942. expandByVector: function ( vector ) {
  6943. this.min.sub( vector );
  6944. this.max.add( vector );
  6945. return this;
  6946. },
  6947. expandByScalar: function ( scalar ) {
  6948. this.min.addScalar( - scalar );
  6949. this.max.addScalar( scalar );
  6950. return this;
  6951. },
  6952. expandByObject: function () {
  6953. // Computes the world-axis-aligned bounding box of an object (including its children),
  6954. // accounting for both the object's, and children's, world transforms
  6955. var scope, i, l;
  6956. var v1 = new Vector3();
  6957. function traverse( node ) {
  6958. var geometry = node.geometry;
  6959. if ( geometry !== undefined ) {
  6960. if ( geometry.isGeometry ) {
  6961. var vertices = geometry.vertices;
  6962. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  6963. v1.copy( vertices[ i ] );
  6964. v1.applyMatrix4( node.matrixWorld );
  6965. scope.expandByPoint( v1 );
  6966. }
  6967. } else if ( geometry.isBufferGeometry ) {
  6968. var attribute = geometry.attributes.position;
  6969. if ( attribute !== undefined ) {
  6970. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  6971. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  6972. scope.expandByPoint( v1 );
  6973. }
  6974. }
  6975. }
  6976. }
  6977. }
  6978. return function expandByObject( object ) {
  6979. scope = this;
  6980. object.updateMatrixWorld( true );
  6981. object.traverse( traverse );
  6982. return this;
  6983. };
  6984. }(),
  6985. containsPoint: function ( point ) {
  6986. return point.x < this.min.x || point.x > this.max.x ||
  6987. point.y < this.min.y || point.y > this.max.y ||
  6988. point.z < this.min.z || point.z > this.max.z ? false : true;
  6989. },
  6990. containsBox: function ( box ) {
  6991. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  6992. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  6993. this.min.z <= box.min.z && box.max.z <= this.max.z;
  6994. },
  6995. getParameter: function ( point, target ) {
  6996. // This can potentially have a divide by zero if the box
  6997. // has a size dimension of 0.
  6998. if ( target === undefined ) {
  6999. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  7000. target = new Vector3();
  7001. }
  7002. return target.set(
  7003. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7004. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7005. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7006. );
  7007. },
  7008. intersectsBox: function ( box ) {
  7009. // using 6 splitting planes to rule out intersections.
  7010. return box.max.x < this.min.x || box.min.x > this.max.x ||
  7011. box.max.y < this.min.y || box.min.y > this.max.y ||
  7012. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  7013. },
  7014. intersectsSphere: ( function () {
  7015. var closestPoint = new Vector3();
  7016. return function intersectsSphere( sphere ) {
  7017. // Find the point on the AABB closest to the sphere center.
  7018. this.clampPoint( sphere.center, closestPoint );
  7019. // If that point is inside the sphere, the AABB and sphere intersect.
  7020. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7021. };
  7022. } )(),
  7023. intersectsPlane: function ( plane ) {
  7024. // We compute the minimum and maximum dot product values. If those values
  7025. // are on the same side (back or front) of the plane, then there is no intersection.
  7026. var min, max;
  7027. if ( plane.normal.x > 0 ) {
  7028. min = plane.normal.x * this.min.x;
  7029. max = plane.normal.x * this.max.x;
  7030. } else {
  7031. min = plane.normal.x * this.max.x;
  7032. max = plane.normal.x * this.min.x;
  7033. }
  7034. if ( plane.normal.y > 0 ) {
  7035. min += plane.normal.y * this.min.y;
  7036. max += plane.normal.y * this.max.y;
  7037. } else {
  7038. min += plane.normal.y * this.max.y;
  7039. max += plane.normal.y * this.min.y;
  7040. }
  7041. if ( plane.normal.z > 0 ) {
  7042. min += plane.normal.z * this.min.z;
  7043. max += plane.normal.z * this.max.z;
  7044. } else {
  7045. min += plane.normal.z * this.max.z;
  7046. max += plane.normal.z * this.min.z;
  7047. }
  7048. return ( min <= plane.constant && max >= plane.constant );
  7049. },
  7050. intersectsTriangle: ( function () {
  7051. // triangle centered vertices
  7052. var v0 = new Vector3();
  7053. var v1 = new Vector3();
  7054. var v2 = new Vector3();
  7055. // triangle edge vectors
  7056. var f0 = new Vector3();
  7057. var f1 = new Vector3();
  7058. var f2 = new Vector3();
  7059. var testAxis = new Vector3();
  7060. var center = new Vector3();
  7061. var extents = new Vector3();
  7062. var triangleNormal = new Vector3();
  7063. function satForAxes( axes ) {
  7064. var i, j;
  7065. for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7066. testAxis.fromArray( axes, i );
  7067. // project the aabb onto the seperating axis
  7068. var r = extents.x * Math.abs( testAxis.x ) + extents.y * Math.abs( testAxis.y ) + extents.z * Math.abs( testAxis.z );
  7069. // project all 3 vertices of the triangle onto the seperating axis
  7070. var p0 = v0.dot( testAxis );
  7071. var p1 = v1.dot( testAxis );
  7072. var p2 = v2.dot( testAxis );
  7073. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7074. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7075. // points of the projected triangle are outside the projected half-length of the aabb
  7076. // the axis is seperating and we can exit
  7077. return false;
  7078. }
  7079. }
  7080. return true;
  7081. }
  7082. return function intersectsTriangle( triangle ) {
  7083. if ( this.isEmpty() ) {
  7084. return false;
  7085. }
  7086. // compute box center and extents
  7087. this.getCenter( center );
  7088. extents.subVectors( this.max, center );
  7089. // translate triangle to aabb origin
  7090. v0.subVectors( triangle.a, center );
  7091. v1.subVectors( triangle.b, center );
  7092. v2.subVectors( triangle.c, center );
  7093. // compute edge vectors for triangle
  7094. f0.subVectors( v1, v0 );
  7095. f1.subVectors( v2, v1 );
  7096. f2.subVectors( v0, v2 );
  7097. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7098. // 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
  7099. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7100. var axes = [
  7101. 0, - f0.z, f0.y, 0, - f1.z, f1.y, 0, - f2.z, f2.y,
  7102. f0.z, 0, - f0.x, f1.z, 0, - f1.x, f2.z, 0, - f2.x,
  7103. - f0.y, f0.x, 0, - f1.y, f1.x, 0, - f2.y, f2.x, 0
  7104. ];
  7105. if ( ! satForAxes( axes ) ) {
  7106. return false;
  7107. }
  7108. // test 3 face normals from the aabb
  7109. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7110. if ( ! satForAxes( axes ) ) {
  7111. return false;
  7112. }
  7113. // finally testing the face normal of the triangle
  7114. // use already existing triangle edge vectors here
  7115. triangleNormal.crossVectors( f0, f1 );
  7116. axes = [ triangleNormal.x, triangleNormal.y, triangleNormal.z ];
  7117. return satForAxes( axes );
  7118. };
  7119. } )(),
  7120. clampPoint: function ( point, target ) {
  7121. if ( target === undefined ) {
  7122. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  7123. target = new Vector3();
  7124. }
  7125. return target.copy( point ).clamp( this.min, this.max );
  7126. },
  7127. distanceToPoint: function () {
  7128. var v1 = new Vector3();
  7129. return function distanceToPoint( point ) {
  7130. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  7131. return clampedPoint.sub( point ).length();
  7132. };
  7133. }(),
  7134. getBoundingSphere: function () {
  7135. var v1 = new Vector3();
  7136. return function getBoundingSphere( target ) {
  7137. if ( target === undefined ) {
  7138. console.warn( 'THREE.Box3: .getBoundingSphere() target is now required' );
  7139. target = new Sphere();
  7140. }
  7141. this.getCenter( target.center );
  7142. target.radius = this.getSize( v1 ).length() * 0.5;
  7143. return target;
  7144. };
  7145. }(),
  7146. intersect: function ( box ) {
  7147. this.min.max( box.min );
  7148. this.max.min( box.max );
  7149. // 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.
  7150. if ( this.isEmpty() ) this.makeEmpty();
  7151. return this;
  7152. },
  7153. union: function ( box ) {
  7154. this.min.min( box.min );
  7155. this.max.max( box.max );
  7156. return this;
  7157. },
  7158. applyMatrix4: function ( matrix ) {
  7159. // transform of empty box is an empty box.
  7160. if ( this.isEmpty( ) ) return this;
  7161. var m = matrix.elements;
  7162. var xax = m[ 0 ] * this.min.x, xay = m[ 1 ] * this.min.x, xaz = m[ 2 ] * this.min.x;
  7163. var xbx = m[ 0 ] * this.max.x, xby = m[ 1 ] * this.max.x, xbz = m[ 2 ] * this.max.x;
  7164. var yax = m[ 4 ] * this.min.y, yay = m[ 5 ] * this.min.y, yaz = m[ 6 ] * this.min.y;
  7165. var ybx = m[ 4 ] * this.max.y, yby = m[ 5 ] * this.max.y, ybz = m[ 6 ] * this.max.y;
  7166. var zax = m[ 8 ] * this.min.z, zay = m[ 9 ] * this.min.z, zaz = m[ 10 ] * this.min.z;
  7167. var zbx = m[ 8 ] * this.max.z, zby = m[ 9 ] * this.max.z, zbz = m[ 10 ] * this.max.z;
  7168. this.min.x = Math.min( xax, xbx ) + Math.min( yax, ybx ) + Math.min( zax, zbx ) + m[ 12 ];
  7169. this.min.y = Math.min( xay, xby ) + Math.min( yay, yby ) + Math.min( zay, zby ) + m[ 13 ];
  7170. this.min.z = Math.min( xaz, xbz ) + Math.min( yaz, ybz ) + Math.min( zaz, zbz ) + m[ 14 ];
  7171. this.max.x = Math.max( xax, xbx ) + Math.max( yax, ybx ) + Math.max( zax, zbx ) + m[ 12 ];
  7172. this.max.y = Math.max( xay, xby ) + Math.max( yay, yby ) + Math.max( zay, zby ) + m[ 13 ];
  7173. this.max.z = Math.max( xaz, xbz ) + Math.max( yaz, ybz ) + Math.max( zaz, zbz ) + m[ 14 ];
  7174. return this;
  7175. },
  7176. translate: function ( offset ) {
  7177. this.min.add( offset );
  7178. this.max.add( offset );
  7179. return this;
  7180. },
  7181. equals: function ( box ) {
  7182. return box.min.equals( this.min ) && box.max.equals( this.max );
  7183. }
  7184. } );
  7185. /**
  7186. * @author bhouston / http://clara.io
  7187. * @author mrdoob / http://mrdoob.com/
  7188. */
  7189. function Sphere( center, radius ) {
  7190. this.center = ( center !== undefined ) ? center : new Vector3();
  7191. this.radius = ( radius !== undefined ) ? radius : 0;
  7192. }
  7193. Object.assign( Sphere.prototype, {
  7194. set: function ( center, radius ) {
  7195. this.center.copy( center );
  7196. this.radius = radius;
  7197. return this;
  7198. },
  7199. setFromPoints: function () {
  7200. var box = new Box3();
  7201. return function setFromPoints( points, optionalCenter ) {
  7202. var center = this.center;
  7203. if ( optionalCenter !== undefined ) {
  7204. center.copy( optionalCenter );
  7205. } else {
  7206. box.setFromPoints( points ).getCenter( center );
  7207. }
  7208. var maxRadiusSq = 0;
  7209. for ( var i = 0, il = points.length; i < il; i ++ ) {
  7210. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7211. }
  7212. this.radius = Math.sqrt( maxRadiusSq );
  7213. return this;
  7214. };
  7215. }(),
  7216. clone: function () {
  7217. return new this.constructor().copy( this );
  7218. },
  7219. copy: function ( sphere ) {
  7220. this.center.copy( sphere.center );
  7221. this.radius = sphere.radius;
  7222. return this;
  7223. },
  7224. empty: function () {
  7225. return ( this.radius <= 0 );
  7226. },
  7227. containsPoint: function ( point ) {
  7228. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7229. },
  7230. distanceToPoint: function ( point ) {
  7231. return ( point.distanceTo( this.center ) - this.radius );
  7232. },
  7233. intersectsSphere: function ( sphere ) {
  7234. var radiusSum = this.radius + sphere.radius;
  7235. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  7236. },
  7237. intersectsBox: function ( box ) {
  7238. return box.intersectsSphere( this );
  7239. },
  7240. intersectsPlane: function ( plane ) {
  7241. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  7242. },
  7243. clampPoint: function ( point, target ) {
  7244. var deltaLengthSq = this.center.distanceToSquared( point );
  7245. if ( target === undefined ) {
  7246. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  7247. target = new Vector3();
  7248. }
  7249. target.copy( point );
  7250. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  7251. target.sub( this.center ).normalize();
  7252. target.multiplyScalar( this.radius ).add( this.center );
  7253. }
  7254. return target;
  7255. },
  7256. getBoundingBox: function ( target ) {
  7257. if ( target === undefined ) {
  7258. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  7259. target = new Box3();
  7260. }
  7261. target.set( this.center, this.center );
  7262. target.expandByScalar( this.radius );
  7263. return target;
  7264. },
  7265. applyMatrix4: function ( matrix ) {
  7266. this.center.applyMatrix4( matrix );
  7267. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  7268. return this;
  7269. },
  7270. translate: function ( offset ) {
  7271. this.center.add( offset );
  7272. return this;
  7273. },
  7274. equals: function ( sphere ) {
  7275. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  7276. }
  7277. } );
  7278. /**
  7279. * @author bhouston / http://clara.io
  7280. */
  7281. function Plane( normal, constant ) {
  7282. // normal is assumed to be normalized
  7283. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  7284. this.constant = ( constant !== undefined ) ? constant : 0;
  7285. }
  7286. Object.assign( Plane.prototype, {
  7287. set: function ( normal, constant ) {
  7288. this.normal.copy( normal );
  7289. this.constant = constant;
  7290. return this;
  7291. },
  7292. setComponents: function ( x, y, z, w ) {
  7293. this.normal.set( x, y, z );
  7294. this.constant = w;
  7295. return this;
  7296. },
  7297. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  7298. this.normal.copy( normal );
  7299. this.constant = - point.dot( this.normal );
  7300. return this;
  7301. },
  7302. setFromCoplanarPoints: function () {
  7303. var v1 = new Vector3();
  7304. var v2 = new Vector3();
  7305. return function setFromCoplanarPoints( a, b, c ) {
  7306. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  7307. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7308. this.setFromNormalAndCoplanarPoint( normal, a );
  7309. return this;
  7310. };
  7311. }(),
  7312. clone: function () {
  7313. return new this.constructor().copy( this );
  7314. },
  7315. copy: function ( plane ) {
  7316. this.normal.copy( plane.normal );
  7317. this.constant = plane.constant;
  7318. return this;
  7319. },
  7320. normalize: function () {
  7321. // Note: will lead to a divide by zero if the plane is invalid.
  7322. var inverseNormalLength = 1.0 / this.normal.length();
  7323. this.normal.multiplyScalar( inverseNormalLength );
  7324. this.constant *= inverseNormalLength;
  7325. return this;
  7326. },
  7327. negate: function () {
  7328. this.constant *= - 1;
  7329. this.normal.negate();
  7330. return this;
  7331. },
  7332. distanceToPoint: function ( point ) {
  7333. return this.normal.dot( point ) + this.constant;
  7334. },
  7335. distanceToSphere: function ( sphere ) {
  7336. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7337. },
  7338. projectPoint: function ( point, target ) {
  7339. if ( target === undefined ) {
  7340. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  7341. target = new Vector3();
  7342. }
  7343. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7344. },
  7345. intersectLine: function () {
  7346. var v1 = new Vector3();
  7347. return function intersectLine( line, target ) {
  7348. if ( target === undefined ) {
  7349. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  7350. target = new Vector3();
  7351. }
  7352. var direction = line.delta( v1 );
  7353. var denominator = this.normal.dot( direction );
  7354. if ( denominator === 0 ) {
  7355. // line is coplanar, return origin
  7356. if ( this.distanceToPoint( line.start ) === 0 ) {
  7357. return target.copy( line.start );
  7358. }
  7359. // Unsure if this is the correct method to handle this case.
  7360. return undefined;
  7361. }
  7362. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7363. if ( t < 0 || t > 1 ) {
  7364. return undefined;
  7365. }
  7366. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7367. };
  7368. }(),
  7369. intersectsLine: function ( line ) {
  7370. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7371. var startSign = this.distanceToPoint( line.start );
  7372. var endSign = this.distanceToPoint( line.end );
  7373. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7374. },
  7375. intersectsBox: function ( box ) {
  7376. return box.intersectsPlane( this );
  7377. },
  7378. intersectsSphere: function ( sphere ) {
  7379. return sphere.intersectsPlane( this );
  7380. },
  7381. coplanarPoint: function ( target ) {
  7382. if ( target === undefined ) {
  7383. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  7384. target = new Vector3();
  7385. }
  7386. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7387. },
  7388. applyMatrix4: function () {
  7389. var v1 = new Vector3();
  7390. var m1 = new Matrix3();
  7391. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  7392. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  7393. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  7394. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7395. this.constant = - referencePoint.dot( normal );
  7396. return this;
  7397. };
  7398. }(),
  7399. translate: function ( offset ) {
  7400. this.constant -= offset.dot( this.normal );
  7401. return this;
  7402. },
  7403. equals: function ( plane ) {
  7404. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7405. }
  7406. } );
  7407. /**
  7408. * @author mrdoob / http://mrdoob.com/
  7409. * @author alteredq / http://alteredqualia.com/
  7410. * @author bhouston / http://clara.io
  7411. */
  7412. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  7413. this.planes = [
  7414. ( p0 !== undefined ) ? p0 : new Plane(),
  7415. ( p1 !== undefined ) ? p1 : new Plane(),
  7416. ( p2 !== undefined ) ? p2 : new Plane(),
  7417. ( p3 !== undefined ) ? p3 : new Plane(),
  7418. ( p4 !== undefined ) ? p4 : new Plane(),
  7419. ( p5 !== undefined ) ? p5 : new Plane()
  7420. ];
  7421. }
  7422. Object.assign( Frustum.prototype, {
  7423. set: function ( p0, p1, p2, p3, p4, p5 ) {
  7424. var planes = this.planes;
  7425. planes[ 0 ].copy( p0 );
  7426. planes[ 1 ].copy( p1 );
  7427. planes[ 2 ].copy( p2 );
  7428. planes[ 3 ].copy( p3 );
  7429. planes[ 4 ].copy( p4 );
  7430. planes[ 5 ].copy( p5 );
  7431. return this;
  7432. },
  7433. clone: function () {
  7434. return new this.constructor().copy( this );
  7435. },
  7436. copy: function ( frustum ) {
  7437. var planes = this.planes;
  7438. for ( var i = 0; i < 6; i ++ ) {
  7439. planes[ i ].copy( frustum.planes[ i ] );
  7440. }
  7441. return this;
  7442. },
  7443. setFromMatrix: function ( m ) {
  7444. var planes = this.planes;
  7445. var me = m.elements;
  7446. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7447. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7448. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7449. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7450. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7451. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7452. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7453. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7454. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7455. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7456. return this;
  7457. },
  7458. intersectsObject: function () {
  7459. var sphere = new Sphere();
  7460. return function intersectsObject( object ) {
  7461. var geometry = object.geometry;
  7462. if ( geometry.boundingSphere === null )
  7463. geometry.computeBoundingSphere();
  7464. sphere.copy( geometry.boundingSphere )
  7465. .applyMatrix4( object.matrixWorld );
  7466. return this.intersectsSphere( sphere );
  7467. };
  7468. }(),
  7469. intersectsSprite: function () {
  7470. var sphere = new Sphere();
  7471. return function intersectsSprite( sprite ) {
  7472. sphere.center.set( 0, 0, 0 );
  7473. sphere.radius = 0.7071067811865476;
  7474. sphere.applyMatrix4( sprite.matrixWorld );
  7475. return this.intersectsSphere( sphere );
  7476. };
  7477. }(),
  7478. intersectsSphere: function ( sphere ) {
  7479. var planes = this.planes;
  7480. var center = sphere.center;
  7481. var negRadius = - sphere.radius;
  7482. for ( var i = 0; i < 6; i ++ ) {
  7483. var distance = planes[ i ].distanceToPoint( center );
  7484. if ( distance < negRadius ) {
  7485. return false;
  7486. }
  7487. }
  7488. return true;
  7489. },
  7490. intersectsBox: function () {
  7491. var p = new Vector3();
  7492. return function intersectsBox( box ) {
  7493. var planes = this.planes;
  7494. for ( var i = 0; i < 6; i ++ ) {
  7495. var plane = planes[ i ];
  7496. // corner at max distance
  7497. p.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7498. p.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7499. p.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7500. if ( plane.distanceToPoint( p ) < 0 ) {
  7501. return false;
  7502. }
  7503. }
  7504. return true;
  7505. };
  7506. }(),
  7507. containsPoint: function ( point ) {
  7508. var planes = this.planes;
  7509. for ( var i = 0; i < 6; i ++ ) {
  7510. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7511. return false;
  7512. }
  7513. }
  7514. return true;
  7515. }
  7516. } );
  7517. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  7518. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  7519. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  7520. 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\n";
  7521. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7522. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  7523. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  7524. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\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\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\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";
  7525. 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\n";
  7526. 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\n";
  7527. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";
  7528. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  7529. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  7530. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7531. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  7532. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  7533. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  7534. 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}\n";
  7535. 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\n";
  7536. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n";
  7537. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  7538. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  7539. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";
  7540. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  7541. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  7542. 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.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\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.w );\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.w );\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.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, 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.x, 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 = value.rgb * cLogLuvM;\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 = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  7543. 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\n";
  7544. 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\n";
  7545. 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\n";
  7546. 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\n";
  7547. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  7548. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  7549. 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\n";
  7550. 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\n";
  7551. 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\n";
  7552. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  7553. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7554. 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 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = 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\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n";
  7555. 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\n";
  7556. 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\n";
  7557. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  7558. 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)\n";
  7559. 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\n";
  7560. 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\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, 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\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\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}\n";
  7561. 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\n";
  7562. 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\n";
  7563. 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, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  7564. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  7565. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n";
  7566. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif";
  7567. 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\n";
  7568. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  7569. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  7570. 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\n";
  7571. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif\n";
  7572. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";
  7573. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7574. 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\n";
  7575. 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";
  7576. 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\n";
  7577. 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#endif\n";
  7578. 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\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  7579. 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\n";
  7580. 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}\n";
  7581. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  7582. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n";
  7583. var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";
  7584. 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\n";
  7585. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";
  7586. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7587. 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\n";
  7588. 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\n";
  7589. 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\n";
  7590. 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}\n";
  7591. 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";
  7592. 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\n";
  7593. 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\n";
  7594. 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#endif\n";
  7595. 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";
  7596. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7597. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  7598. 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}\n";
  7599. 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";
  7600. 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\n";
  7601. 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";
  7602. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7603. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  7604. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  7605. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n";
  7606. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  7607. var cube_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}\n";
  7608. 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}\n";
  7609. 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}\n";
  7610. 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}\n";
  7611. 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}\n";
  7612. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\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\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  7613. var equirect_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  7614. 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}\n";
  7615. 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}\n";
  7616. 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}\n";
  7617. 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}\n";
  7618. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\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#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}\n";
  7619. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\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}\n";
  7620. 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}\n";
  7621. 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}\n";
  7622. 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#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}\n";
  7623. var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  7624. 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#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}\n";
  7625. 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#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#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}\n";
  7626. 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}\n";
  7627. 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\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\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}\n";
  7628. 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}\n";
  7629. 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}\n";
  7630. 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}\n";
  7631. 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\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\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\tvec4 mvPosition;\n\tmvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\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}\n";
  7632. var ShaderChunk = {
  7633. alphamap_fragment: alphamap_fragment,
  7634. alphamap_pars_fragment: alphamap_pars_fragment,
  7635. alphatest_fragment: alphatest_fragment,
  7636. aomap_fragment: aomap_fragment,
  7637. aomap_pars_fragment: aomap_pars_fragment,
  7638. begin_vertex: begin_vertex,
  7639. beginnormal_vertex: beginnormal_vertex,
  7640. bsdfs: bsdfs,
  7641. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7642. clipping_planes_fragment: clipping_planes_fragment,
  7643. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7644. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7645. clipping_planes_vertex: clipping_planes_vertex,
  7646. color_fragment: color_fragment,
  7647. color_pars_fragment: color_pars_fragment,
  7648. color_pars_vertex: color_pars_vertex,
  7649. color_vertex: color_vertex,
  7650. common: common,
  7651. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7652. defaultnormal_vertex: defaultnormal_vertex,
  7653. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7654. displacementmap_vertex: displacementmap_vertex,
  7655. emissivemap_fragment: emissivemap_fragment,
  7656. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7657. encodings_fragment: encodings_fragment,
  7658. encodings_pars_fragment: encodings_pars_fragment,
  7659. envmap_fragment: envmap_fragment,
  7660. envmap_pars_fragment: envmap_pars_fragment,
  7661. envmap_pars_vertex: envmap_pars_vertex,
  7662. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7663. envmap_vertex: envmap_vertex,
  7664. fog_vertex: fog_vertex,
  7665. fog_pars_vertex: fog_pars_vertex,
  7666. fog_fragment: fog_fragment,
  7667. fog_pars_fragment: fog_pars_fragment,
  7668. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7669. lightmap_fragment: lightmap_fragment,
  7670. lightmap_pars_fragment: lightmap_pars_fragment,
  7671. lights_lambert_vertex: lights_lambert_vertex,
  7672. lights_pars_begin: lights_pars_begin,
  7673. lights_phong_fragment: lights_phong_fragment,
  7674. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7675. lights_physical_fragment: lights_physical_fragment,
  7676. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7677. lights_fragment_begin: lights_fragment_begin,
  7678. lights_fragment_maps: lights_fragment_maps,
  7679. lights_fragment_end: lights_fragment_end,
  7680. logdepthbuf_fragment: logdepthbuf_fragment,
  7681. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7682. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7683. logdepthbuf_vertex: logdepthbuf_vertex,
  7684. map_fragment: map_fragment,
  7685. map_pars_fragment: map_pars_fragment,
  7686. map_particle_fragment: map_particle_fragment,
  7687. map_particle_pars_fragment: map_particle_pars_fragment,
  7688. metalnessmap_fragment: metalnessmap_fragment,
  7689. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7690. morphnormal_vertex: morphnormal_vertex,
  7691. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7692. morphtarget_vertex: morphtarget_vertex,
  7693. normal_fragment_begin: normal_fragment_begin,
  7694. normal_fragment_maps: normal_fragment_maps,
  7695. normalmap_pars_fragment: normalmap_pars_fragment,
  7696. packing: packing,
  7697. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7698. project_vertex: project_vertex,
  7699. dithering_fragment: dithering_fragment,
  7700. dithering_pars_fragment: dithering_pars_fragment,
  7701. roughnessmap_fragment: roughnessmap_fragment,
  7702. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7703. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7704. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7705. shadowmap_vertex: shadowmap_vertex,
  7706. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7707. skinbase_vertex: skinbase_vertex,
  7708. skinning_pars_vertex: skinning_pars_vertex,
  7709. skinning_vertex: skinning_vertex,
  7710. skinnormal_vertex: skinnormal_vertex,
  7711. specularmap_fragment: specularmap_fragment,
  7712. specularmap_pars_fragment: specularmap_pars_fragment,
  7713. tonemapping_fragment: tonemapping_fragment,
  7714. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7715. uv_pars_fragment: uv_pars_fragment,
  7716. uv_pars_vertex: uv_pars_vertex,
  7717. uv_vertex: uv_vertex,
  7718. uv2_pars_fragment: uv2_pars_fragment,
  7719. uv2_pars_vertex: uv2_pars_vertex,
  7720. uv2_vertex: uv2_vertex,
  7721. worldpos_vertex: worldpos_vertex,
  7722. cube_frag: cube_frag,
  7723. cube_vert: cube_vert,
  7724. depth_frag: depth_frag,
  7725. depth_vert: depth_vert,
  7726. distanceRGBA_frag: distanceRGBA_frag,
  7727. distanceRGBA_vert: distanceRGBA_vert,
  7728. equirect_frag: equirect_frag,
  7729. equirect_vert: equirect_vert,
  7730. linedashed_frag: linedashed_frag,
  7731. linedashed_vert: linedashed_vert,
  7732. meshbasic_frag: meshbasic_frag,
  7733. meshbasic_vert: meshbasic_vert,
  7734. meshlambert_frag: meshlambert_frag,
  7735. meshlambert_vert: meshlambert_vert,
  7736. meshphong_frag: meshphong_frag,
  7737. meshphong_vert: meshphong_vert,
  7738. meshphysical_frag: meshphysical_frag,
  7739. meshphysical_vert: meshphysical_vert,
  7740. normal_frag: normal_frag,
  7741. normal_vert: normal_vert,
  7742. points_frag: points_frag,
  7743. points_vert: points_vert,
  7744. shadow_frag: shadow_frag,
  7745. shadow_vert: shadow_vert,
  7746. sprite_frag: sprite_frag,
  7747. sprite_vert: sprite_vert
  7748. };
  7749. /**
  7750. * Uniform Utilities
  7751. */
  7752. var UniformsUtils = {
  7753. merge: function ( uniforms ) {
  7754. var merged = {};
  7755. for ( var u = 0; u < uniforms.length; u ++ ) {
  7756. var tmp = this.clone( uniforms[ u ] );
  7757. for ( var p in tmp ) {
  7758. merged[ p ] = tmp[ p ];
  7759. }
  7760. }
  7761. return merged;
  7762. },
  7763. clone: function ( uniforms_src ) {
  7764. var uniforms_dst = {};
  7765. for ( var u in uniforms_src ) {
  7766. uniforms_dst[ u ] = {};
  7767. for ( var p in uniforms_src[ u ] ) {
  7768. var parameter_src = uniforms_src[ u ][ p ];
  7769. if ( parameter_src && ( parameter_src.isColor ||
  7770. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  7771. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  7772. parameter_src.isTexture ) ) {
  7773. uniforms_dst[ u ][ p ] = parameter_src.clone();
  7774. } else if ( Array.isArray( parameter_src ) ) {
  7775. uniforms_dst[ u ][ p ] = parameter_src.slice();
  7776. } else {
  7777. uniforms_dst[ u ][ p ] = parameter_src;
  7778. }
  7779. }
  7780. }
  7781. return uniforms_dst;
  7782. }
  7783. };
  7784. /**
  7785. * @author mrdoob / http://mrdoob.com/
  7786. */
  7787. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  7788. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  7789. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  7790. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  7791. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  7792. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  7793. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  7794. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  7795. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  7796. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  7797. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  7798. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  7799. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  7800. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  7801. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  7802. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  7803. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  7804. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  7805. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  7806. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  7807. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  7808. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  7809. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  7810. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  7811. function Color( r, g, b ) {
  7812. if ( g === undefined && b === undefined ) {
  7813. // r is THREE.Color, hex or string
  7814. return this.set( r );
  7815. }
  7816. return this.setRGB( r, g, b );
  7817. }
  7818. Object.assign( Color.prototype, {
  7819. isColor: true,
  7820. r: 1, g: 1, b: 1,
  7821. set: function ( value ) {
  7822. if ( value && value.isColor ) {
  7823. this.copy( value );
  7824. } else if ( typeof value === 'number' ) {
  7825. this.setHex( value );
  7826. } else if ( typeof value === 'string' ) {
  7827. this.setStyle( value );
  7828. }
  7829. return this;
  7830. },
  7831. setScalar: function ( scalar ) {
  7832. this.r = scalar;
  7833. this.g = scalar;
  7834. this.b = scalar;
  7835. return this;
  7836. },
  7837. setHex: function ( hex ) {
  7838. hex = Math.floor( hex );
  7839. this.r = ( hex >> 16 & 255 ) / 255;
  7840. this.g = ( hex >> 8 & 255 ) / 255;
  7841. this.b = ( hex & 255 ) / 255;
  7842. return this;
  7843. },
  7844. setRGB: function ( r, g, b ) {
  7845. this.r = r;
  7846. this.g = g;
  7847. this.b = b;
  7848. return this;
  7849. },
  7850. setHSL: function () {
  7851. function hue2rgb( p, q, t ) {
  7852. if ( t < 0 ) t += 1;
  7853. if ( t > 1 ) t -= 1;
  7854. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  7855. if ( t < 1 / 2 ) return q;
  7856. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  7857. return p;
  7858. }
  7859. return function setHSL( h, s, l ) {
  7860. // h,s,l ranges are in 0.0 - 1.0
  7861. h = _Math.euclideanModulo( h, 1 );
  7862. s = _Math.clamp( s, 0, 1 );
  7863. l = _Math.clamp( l, 0, 1 );
  7864. if ( s === 0 ) {
  7865. this.r = this.g = this.b = l;
  7866. } else {
  7867. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  7868. var q = ( 2 * l ) - p;
  7869. this.r = hue2rgb( q, p, h + 1 / 3 );
  7870. this.g = hue2rgb( q, p, h );
  7871. this.b = hue2rgb( q, p, h - 1 / 3 );
  7872. }
  7873. return this;
  7874. };
  7875. }(),
  7876. setStyle: function ( style ) {
  7877. function handleAlpha( string ) {
  7878. if ( string === undefined ) return;
  7879. if ( parseFloat( string ) < 1 ) {
  7880. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  7881. }
  7882. }
  7883. var m;
  7884. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  7885. // rgb / hsl
  7886. var color;
  7887. var name = m[ 1 ];
  7888. var components = m[ 2 ];
  7889. switch ( name ) {
  7890. case 'rgb':
  7891. case 'rgba':
  7892. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7893. // rgb(255,0,0) rgba(255,0,0,0.5)
  7894. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  7895. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  7896. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  7897. handleAlpha( color[ 5 ] );
  7898. return this;
  7899. }
  7900. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7901. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  7902. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  7903. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  7904. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  7905. handleAlpha( color[ 5 ] );
  7906. return this;
  7907. }
  7908. break;
  7909. case 'hsl':
  7910. case 'hsla':
  7911. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7912. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  7913. var h = parseFloat( color[ 1 ] ) / 360;
  7914. var s = parseInt( color[ 2 ], 10 ) / 100;
  7915. var l = parseInt( color[ 3 ], 10 ) / 100;
  7916. handleAlpha( color[ 5 ] );
  7917. return this.setHSL( h, s, l );
  7918. }
  7919. break;
  7920. }
  7921. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  7922. // hex color
  7923. var hex = m[ 1 ];
  7924. var size = hex.length;
  7925. if ( size === 3 ) {
  7926. // #ff0
  7927. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  7928. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  7929. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  7930. return this;
  7931. } else if ( size === 6 ) {
  7932. // #ff0000
  7933. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  7934. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  7935. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  7936. return this;
  7937. }
  7938. }
  7939. if ( style && style.length > 0 ) {
  7940. // color keywords
  7941. var hex = ColorKeywords[ style ];
  7942. if ( hex !== undefined ) {
  7943. // red
  7944. this.setHex( hex );
  7945. } else {
  7946. // unknown color
  7947. console.warn( 'THREE.Color: Unknown color ' + style );
  7948. }
  7949. }
  7950. return this;
  7951. },
  7952. clone: function () {
  7953. return new this.constructor( this.r, this.g, this.b );
  7954. },
  7955. copy: function ( color ) {
  7956. this.r = color.r;
  7957. this.g = color.g;
  7958. this.b = color.b;
  7959. return this;
  7960. },
  7961. copyGammaToLinear: function ( color, gammaFactor ) {
  7962. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7963. this.r = Math.pow( color.r, gammaFactor );
  7964. this.g = Math.pow( color.g, gammaFactor );
  7965. this.b = Math.pow( color.b, gammaFactor );
  7966. return this;
  7967. },
  7968. copyLinearToGamma: function ( color, gammaFactor ) {
  7969. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7970. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  7971. this.r = Math.pow( color.r, safeInverse );
  7972. this.g = Math.pow( color.g, safeInverse );
  7973. this.b = Math.pow( color.b, safeInverse );
  7974. return this;
  7975. },
  7976. convertGammaToLinear: function ( gammaFactor ) {
  7977. this.copyGammaToLinear( this, gammaFactor );
  7978. return this;
  7979. },
  7980. convertLinearToGamma: function ( gammaFactor ) {
  7981. this.copyLinearToGamma( this, gammaFactor );
  7982. return this;
  7983. },
  7984. copySRGBToLinear: function () {
  7985. function SRGBToLinear( c ) {
  7986. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  7987. }
  7988. return function copySRGBToLinear( color ) {
  7989. this.r = SRGBToLinear( color.r );
  7990. this.g = SRGBToLinear( color.g );
  7991. this.b = SRGBToLinear( color.b );
  7992. return this;
  7993. };
  7994. }(),
  7995. copyLinearToSRGB: function () {
  7996. function LinearToSRGB( c ) {
  7997. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  7998. }
  7999. return function copyLinearToSRGB( color ) {
  8000. this.r = LinearToSRGB( color.r );
  8001. this.g = LinearToSRGB( color.g );
  8002. this.b = LinearToSRGB( color.b );
  8003. return this;
  8004. };
  8005. }(),
  8006. convertSRGBToLinear: function () {
  8007. this.copySRGBToLinear( this );
  8008. return this;
  8009. },
  8010. convertLinearToSRGB: function () {
  8011. this.copyLinearToSRGB( this );
  8012. return this;
  8013. },
  8014. getHex: function () {
  8015. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  8016. },
  8017. getHexString: function () {
  8018. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  8019. },
  8020. getHSL: function ( target ) {
  8021. // h,s,l ranges are in 0.0 - 1.0
  8022. if ( target === undefined ) {
  8023. console.warn( 'THREE.Color: .getHSL() target is now required' );
  8024. target = { h: 0, s: 0, l: 0 };
  8025. }
  8026. var r = this.r, g = this.g, b = this.b;
  8027. var max = Math.max( r, g, b );
  8028. var min = Math.min( r, g, b );
  8029. var hue, saturation;
  8030. var lightness = ( min + max ) / 2.0;
  8031. if ( min === max ) {
  8032. hue = 0;
  8033. saturation = 0;
  8034. } else {
  8035. var delta = max - min;
  8036. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  8037. switch ( max ) {
  8038. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  8039. case g: hue = ( b - r ) / delta + 2; break;
  8040. case b: hue = ( r - g ) / delta + 4; break;
  8041. }
  8042. hue /= 6;
  8043. }
  8044. target.h = hue;
  8045. target.s = saturation;
  8046. target.l = lightness;
  8047. return target;
  8048. },
  8049. getStyle: function () {
  8050. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  8051. },
  8052. offsetHSL: function () {
  8053. var hsl = {};
  8054. return function ( h, s, l ) {
  8055. this.getHSL( hsl );
  8056. hsl.h += h; hsl.s += s; hsl.l += l;
  8057. this.setHSL( hsl.h, hsl.s, hsl.l );
  8058. return this;
  8059. };
  8060. }(),
  8061. add: function ( color ) {
  8062. this.r += color.r;
  8063. this.g += color.g;
  8064. this.b += color.b;
  8065. return this;
  8066. },
  8067. addColors: function ( color1, color2 ) {
  8068. this.r = color1.r + color2.r;
  8069. this.g = color1.g + color2.g;
  8070. this.b = color1.b + color2.b;
  8071. return this;
  8072. },
  8073. addScalar: function ( s ) {
  8074. this.r += s;
  8075. this.g += s;
  8076. this.b += s;
  8077. return this;
  8078. },
  8079. sub: function ( color ) {
  8080. this.r = Math.max( 0, this.r - color.r );
  8081. this.g = Math.max( 0, this.g - color.g );
  8082. this.b = Math.max( 0, this.b - color.b );
  8083. return this;
  8084. },
  8085. multiply: function ( color ) {
  8086. this.r *= color.r;
  8087. this.g *= color.g;
  8088. this.b *= color.b;
  8089. return this;
  8090. },
  8091. multiplyScalar: function ( s ) {
  8092. this.r *= s;
  8093. this.g *= s;
  8094. this.b *= s;
  8095. return this;
  8096. },
  8097. lerp: function ( color, alpha ) {
  8098. this.r += ( color.r - this.r ) * alpha;
  8099. this.g += ( color.g - this.g ) * alpha;
  8100. this.b += ( color.b - this.b ) * alpha;
  8101. return this;
  8102. },
  8103. equals: function ( c ) {
  8104. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  8105. },
  8106. fromArray: function ( array, offset ) {
  8107. if ( offset === undefined ) offset = 0;
  8108. this.r = array[ offset ];
  8109. this.g = array[ offset + 1 ];
  8110. this.b = array[ offset + 2 ];
  8111. return this;
  8112. },
  8113. toArray: function ( array, offset ) {
  8114. if ( array === undefined ) array = [];
  8115. if ( offset === undefined ) offset = 0;
  8116. array[ offset ] = this.r;
  8117. array[ offset + 1 ] = this.g;
  8118. array[ offset + 2 ] = this.b;
  8119. return array;
  8120. },
  8121. toJSON: function () {
  8122. return this.getHex();
  8123. }
  8124. } );
  8125. /**
  8126. * Uniforms library for shared webgl shaders
  8127. */
  8128. var UniformsLib = {
  8129. common: {
  8130. diffuse: { value: new Color( 0xeeeeee ) },
  8131. opacity: { value: 1.0 },
  8132. map: { value: null },
  8133. uvTransform: { value: new Matrix3() },
  8134. alphaMap: { value: null },
  8135. },
  8136. specularmap: {
  8137. specularMap: { value: null },
  8138. },
  8139. envmap: {
  8140. envMap: { value: null },
  8141. flipEnvMap: { value: - 1 },
  8142. reflectivity: { value: 1.0 },
  8143. refractionRatio: { value: 0.98 },
  8144. maxMipLevel: { value: 0 }
  8145. },
  8146. aomap: {
  8147. aoMap: { value: null },
  8148. aoMapIntensity: { value: 1 }
  8149. },
  8150. lightmap: {
  8151. lightMap: { value: null },
  8152. lightMapIntensity: { value: 1 }
  8153. },
  8154. emissivemap: {
  8155. emissiveMap: { value: null }
  8156. },
  8157. bumpmap: {
  8158. bumpMap: { value: null },
  8159. bumpScale: { value: 1 }
  8160. },
  8161. normalmap: {
  8162. normalMap: { value: null },
  8163. normalScale: { value: new Vector2( 1, 1 ) }
  8164. },
  8165. displacementmap: {
  8166. displacementMap: { value: null },
  8167. displacementScale: { value: 1 },
  8168. displacementBias: { value: 0 }
  8169. },
  8170. roughnessmap: {
  8171. roughnessMap: { value: null }
  8172. },
  8173. metalnessmap: {
  8174. metalnessMap: { value: null }
  8175. },
  8176. gradientmap: {
  8177. gradientMap: { value: null }
  8178. },
  8179. fog: {
  8180. fogDensity: { value: 0.00025 },
  8181. fogNear: { value: 1 },
  8182. fogFar: { value: 2000 },
  8183. fogColor: { value: new Color( 0xffffff ) }
  8184. },
  8185. lights: {
  8186. ambientLightColor: { value: [] },
  8187. directionalLights: { value: [], properties: {
  8188. direction: {},
  8189. color: {},
  8190. shadow: {},
  8191. shadowBias: {},
  8192. shadowRadius: {},
  8193. shadowMapSize: {}
  8194. } },
  8195. directionalShadowMap: { value: [] },
  8196. directionalShadowMatrix: { value: [] },
  8197. spotLights: { value: [], properties: {
  8198. color: {},
  8199. position: {},
  8200. direction: {},
  8201. distance: {},
  8202. coneCos: {},
  8203. penumbraCos: {},
  8204. decay: {},
  8205. shadow: {},
  8206. shadowBias: {},
  8207. shadowRadius: {},
  8208. shadowMapSize: {}
  8209. } },
  8210. spotShadowMap: { value: [] },
  8211. spotShadowMatrix: { value: [] },
  8212. pointLights: { value: [], properties: {
  8213. color: {},
  8214. position: {},
  8215. decay: {},
  8216. distance: {},
  8217. shadow: {},
  8218. shadowBias: {},
  8219. shadowRadius: {},
  8220. shadowMapSize: {},
  8221. shadowCameraNear: {},
  8222. shadowCameraFar: {}
  8223. } },
  8224. pointShadowMap: { value: [] },
  8225. pointShadowMatrix: { value: [] },
  8226. hemisphereLights: { value: [], properties: {
  8227. direction: {},
  8228. skyColor: {},
  8229. groundColor: {}
  8230. } },
  8231. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8232. rectAreaLights: { value: [], properties: {
  8233. color: {},
  8234. position: {},
  8235. width: {},
  8236. height: {}
  8237. } }
  8238. },
  8239. points: {
  8240. diffuse: { value: new Color( 0xeeeeee ) },
  8241. opacity: { value: 1.0 },
  8242. size: { value: 1.0 },
  8243. scale: { value: 1.0 },
  8244. map: { value: null },
  8245. uvTransform: { value: new Matrix3() }
  8246. },
  8247. sprite: {
  8248. diffuse: { value: new Color( 0xeeeeee ) },
  8249. opacity: { value: 1.0 },
  8250. center: { value: new Vector2( 0.5, 0.5 ) },
  8251. rotation: { value: 0.0 },
  8252. map: { value: null },
  8253. uvTransform: { value: new Matrix3() }
  8254. }
  8255. };
  8256. /**
  8257. * @author alteredq / http://alteredqualia.com/
  8258. * @author mrdoob / http://mrdoob.com/
  8259. * @author mikael emtinger / http://gomo.se/
  8260. */
  8261. var ShaderLib = {
  8262. basic: {
  8263. uniforms: UniformsUtils.merge( [
  8264. UniformsLib.common,
  8265. UniformsLib.specularmap,
  8266. UniformsLib.envmap,
  8267. UniformsLib.aomap,
  8268. UniformsLib.lightmap,
  8269. UniformsLib.fog
  8270. ] ),
  8271. vertexShader: ShaderChunk.meshbasic_vert,
  8272. fragmentShader: ShaderChunk.meshbasic_frag
  8273. },
  8274. lambert: {
  8275. uniforms: UniformsUtils.merge( [
  8276. UniformsLib.common,
  8277. UniformsLib.specularmap,
  8278. UniformsLib.envmap,
  8279. UniformsLib.aomap,
  8280. UniformsLib.lightmap,
  8281. UniformsLib.emissivemap,
  8282. UniformsLib.fog,
  8283. UniformsLib.lights,
  8284. {
  8285. emissive: { value: new Color( 0x000000 ) }
  8286. }
  8287. ] ),
  8288. vertexShader: ShaderChunk.meshlambert_vert,
  8289. fragmentShader: ShaderChunk.meshlambert_frag
  8290. },
  8291. phong: {
  8292. uniforms: UniformsUtils.merge( [
  8293. UniformsLib.common,
  8294. UniformsLib.specularmap,
  8295. UniformsLib.envmap,
  8296. UniformsLib.aomap,
  8297. UniformsLib.lightmap,
  8298. UniformsLib.emissivemap,
  8299. UniformsLib.bumpmap,
  8300. UniformsLib.normalmap,
  8301. UniformsLib.displacementmap,
  8302. UniformsLib.gradientmap,
  8303. UniformsLib.fog,
  8304. UniformsLib.lights,
  8305. {
  8306. emissive: { value: new Color( 0x000000 ) },
  8307. specular: { value: new Color( 0x111111 ) },
  8308. shininess: { value: 30 }
  8309. }
  8310. ] ),
  8311. vertexShader: ShaderChunk.meshphong_vert,
  8312. fragmentShader: ShaderChunk.meshphong_frag
  8313. },
  8314. standard: {
  8315. uniforms: UniformsUtils.merge( [
  8316. UniformsLib.common,
  8317. UniformsLib.envmap,
  8318. UniformsLib.aomap,
  8319. UniformsLib.lightmap,
  8320. UniformsLib.emissivemap,
  8321. UniformsLib.bumpmap,
  8322. UniformsLib.normalmap,
  8323. UniformsLib.displacementmap,
  8324. UniformsLib.roughnessmap,
  8325. UniformsLib.metalnessmap,
  8326. UniformsLib.fog,
  8327. UniformsLib.lights,
  8328. {
  8329. emissive: { value: new Color( 0x000000 ) },
  8330. roughness: { value: 0.5 },
  8331. metalness: { value: 0.5 },
  8332. envMapIntensity: { value: 1 } // temporary
  8333. }
  8334. ] ),
  8335. vertexShader: ShaderChunk.meshphysical_vert,
  8336. fragmentShader: ShaderChunk.meshphysical_frag
  8337. },
  8338. points: {
  8339. uniforms: UniformsUtils.merge( [
  8340. UniformsLib.points,
  8341. UniformsLib.fog
  8342. ] ),
  8343. vertexShader: ShaderChunk.points_vert,
  8344. fragmentShader: ShaderChunk.points_frag
  8345. },
  8346. dashed: {
  8347. uniforms: UniformsUtils.merge( [
  8348. UniformsLib.common,
  8349. UniformsLib.fog,
  8350. {
  8351. scale: { value: 1 },
  8352. dashSize: { value: 1 },
  8353. totalSize: { value: 2 }
  8354. }
  8355. ] ),
  8356. vertexShader: ShaderChunk.linedashed_vert,
  8357. fragmentShader: ShaderChunk.linedashed_frag
  8358. },
  8359. depth: {
  8360. uniforms: UniformsUtils.merge( [
  8361. UniformsLib.common,
  8362. UniformsLib.displacementmap
  8363. ] ),
  8364. vertexShader: ShaderChunk.depth_vert,
  8365. fragmentShader: ShaderChunk.depth_frag
  8366. },
  8367. normal: {
  8368. uniforms: UniformsUtils.merge( [
  8369. UniformsLib.common,
  8370. UniformsLib.bumpmap,
  8371. UniformsLib.normalmap,
  8372. UniformsLib.displacementmap,
  8373. {
  8374. opacity: { value: 1.0 }
  8375. }
  8376. ] ),
  8377. vertexShader: ShaderChunk.normal_vert,
  8378. fragmentShader: ShaderChunk.normal_frag
  8379. },
  8380. sprite: {
  8381. uniforms: UniformsUtils.merge( [
  8382. UniformsLib.sprite,
  8383. UniformsLib.fog
  8384. ] ),
  8385. vertexShader: ShaderChunk.sprite_vert,
  8386. fragmentShader: ShaderChunk.sprite_frag
  8387. },
  8388. /* -------------------------------------------------------------------------
  8389. // Cube map shader
  8390. ------------------------------------------------------------------------- */
  8391. cube: {
  8392. uniforms: {
  8393. tCube: { value: null },
  8394. tFlip: { value: - 1 },
  8395. opacity: { value: 1.0 }
  8396. },
  8397. vertexShader: ShaderChunk.cube_vert,
  8398. fragmentShader: ShaderChunk.cube_frag
  8399. },
  8400. equirect: {
  8401. uniforms: {
  8402. tEquirect: { value: null },
  8403. },
  8404. vertexShader: ShaderChunk.equirect_vert,
  8405. fragmentShader: ShaderChunk.equirect_frag
  8406. },
  8407. distanceRGBA: {
  8408. uniforms: UniformsUtils.merge( [
  8409. UniformsLib.common,
  8410. UniformsLib.displacementmap,
  8411. {
  8412. referencePosition: { value: new Vector3() },
  8413. nearDistance: { value: 1 },
  8414. farDistance: { value: 1000 }
  8415. }
  8416. ] ),
  8417. vertexShader: ShaderChunk.distanceRGBA_vert,
  8418. fragmentShader: ShaderChunk.distanceRGBA_frag
  8419. },
  8420. shadow: {
  8421. uniforms: UniformsUtils.merge( [
  8422. UniformsLib.lights,
  8423. UniformsLib.fog,
  8424. {
  8425. color: { value: new Color( 0x00000 ) },
  8426. opacity: { value: 1.0 }
  8427. },
  8428. ] ),
  8429. vertexShader: ShaderChunk.shadow_vert,
  8430. fragmentShader: ShaderChunk.shadow_frag
  8431. }
  8432. };
  8433. ShaderLib.physical = {
  8434. uniforms: UniformsUtils.merge( [
  8435. ShaderLib.standard.uniforms,
  8436. {
  8437. clearCoat: { value: 0 },
  8438. clearCoatRoughness: { value: 0 }
  8439. }
  8440. ] ),
  8441. vertexShader: ShaderChunk.meshphysical_vert,
  8442. fragmentShader: ShaderChunk.meshphysical_frag
  8443. };
  8444. /**
  8445. * @author mrdoob / http://mrdoob.com/
  8446. */
  8447. function WebGLAnimation() {
  8448. var context = null;
  8449. var isAnimating = false;
  8450. var animationLoop = null;
  8451. function onAnimationFrame( time, frame ) {
  8452. if ( isAnimating === false ) return;
  8453. animationLoop( time, frame );
  8454. context.requestAnimationFrame( onAnimationFrame );
  8455. }
  8456. return {
  8457. start: function () {
  8458. if ( isAnimating === true ) return;
  8459. if ( animationLoop === null ) return;
  8460. context.requestAnimationFrame( onAnimationFrame );
  8461. isAnimating = true;
  8462. },
  8463. stop: function () {
  8464. isAnimating = false;
  8465. },
  8466. setAnimationLoop: function ( callback ) {
  8467. animationLoop = callback;
  8468. },
  8469. setContext: function ( value ) {
  8470. context = value;
  8471. }
  8472. };
  8473. }
  8474. /**
  8475. * @author mrdoob / http://mrdoob.com/
  8476. */
  8477. function WebGLAttributes( gl ) {
  8478. var buffers = new WeakMap();
  8479. function createBuffer( attribute, bufferType ) {
  8480. var array = attribute.array;
  8481. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  8482. var buffer = gl.createBuffer();
  8483. gl.bindBuffer( bufferType, buffer );
  8484. gl.bufferData( bufferType, array, usage );
  8485. attribute.onUploadCallback();
  8486. var type = gl.FLOAT;
  8487. if ( array instanceof Float32Array ) {
  8488. type = gl.FLOAT;
  8489. } else if ( array instanceof Float64Array ) {
  8490. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  8491. } else if ( array instanceof Uint16Array ) {
  8492. type = gl.UNSIGNED_SHORT;
  8493. } else if ( array instanceof Int16Array ) {
  8494. type = gl.SHORT;
  8495. } else if ( array instanceof Uint32Array ) {
  8496. type = gl.UNSIGNED_INT;
  8497. } else if ( array instanceof Int32Array ) {
  8498. type = gl.INT;
  8499. } else if ( array instanceof Int8Array ) {
  8500. type = gl.BYTE;
  8501. } else if ( array instanceof Uint8Array ) {
  8502. type = gl.UNSIGNED_BYTE;
  8503. }
  8504. return {
  8505. buffer: buffer,
  8506. type: type,
  8507. bytesPerElement: array.BYTES_PER_ELEMENT,
  8508. version: attribute.version
  8509. };
  8510. }
  8511. function updateBuffer( buffer, attribute, bufferType ) {
  8512. var array = attribute.array;
  8513. var updateRange = attribute.updateRange;
  8514. gl.bindBuffer( bufferType, buffer );
  8515. if ( attribute.dynamic === false ) {
  8516. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  8517. } else if ( updateRange.count === - 1 ) {
  8518. // Not using update ranges
  8519. gl.bufferSubData( bufferType, 0, array );
  8520. } else if ( updateRange.count === 0 ) {
  8521. 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.' );
  8522. } else {
  8523. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8524. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8525. updateRange.count = - 1; // reset range
  8526. }
  8527. }
  8528. //
  8529. function get( attribute ) {
  8530. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8531. return buffers.get( attribute );
  8532. }
  8533. function remove( attribute ) {
  8534. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8535. var data = buffers.get( attribute );
  8536. if ( data ) {
  8537. gl.deleteBuffer( data.buffer );
  8538. buffers.delete( attribute );
  8539. }
  8540. }
  8541. function update( attribute, bufferType ) {
  8542. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8543. var data = buffers.get( attribute );
  8544. if ( data === undefined ) {
  8545. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8546. } else if ( data.version < attribute.version ) {
  8547. updateBuffer( data.buffer, attribute, bufferType );
  8548. data.version = attribute.version;
  8549. }
  8550. }
  8551. return {
  8552. get: get,
  8553. remove: remove,
  8554. update: update
  8555. };
  8556. }
  8557. /**
  8558. * @author mrdoob / http://mrdoob.com/
  8559. * @author WestLangley / http://github.com/WestLangley
  8560. * @author bhouston / http://clara.io
  8561. */
  8562. function Euler( x, y, z, order ) {
  8563. this._x = x || 0;
  8564. this._y = y || 0;
  8565. this._z = z || 0;
  8566. this._order = order || Euler.DefaultOrder;
  8567. }
  8568. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  8569. Euler.DefaultOrder = 'XYZ';
  8570. Object.defineProperties( Euler.prototype, {
  8571. x: {
  8572. get: function () {
  8573. return this._x;
  8574. },
  8575. set: function ( value ) {
  8576. this._x = value;
  8577. this.onChangeCallback();
  8578. }
  8579. },
  8580. y: {
  8581. get: function () {
  8582. return this._y;
  8583. },
  8584. set: function ( value ) {
  8585. this._y = value;
  8586. this.onChangeCallback();
  8587. }
  8588. },
  8589. z: {
  8590. get: function () {
  8591. return this._z;
  8592. },
  8593. set: function ( value ) {
  8594. this._z = value;
  8595. this.onChangeCallback();
  8596. }
  8597. },
  8598. order: {
  8599. get: function () {
  8600. return this._order;
  8601. },
  8602. set: function ( value ) {
  8603. this._order = value;
  8604. this.onChangeCallback();
  8605. }
  8606. }
  8607. } );
  8608. Object.assign( Euler.prototype, {
  8609. isEuler: true,
  8610. set: function ( x, y, z, order ) {
  8611. this._x = x;
  8612. this._y = y;
  8613. this._z = z;
  8614. this._order = order || this._order;
  8615. this.onChangeCallback();
  8616. return this;
  8617. },
  8618. clone: function () {
  8619. return new this.constructor( this._x, this._y, this._z, this._order );
  8620. },
  8621. copy: function ( euler ) {
  8622. this._x = euler._x;
  8623. this._y = euler._y;
  8624. this._z = euler._z;
  8625. this._order = euler._order;
  8626. this.onChangeCallback();
  8627. return this;
  8628. },
  8629. setFromRotationMatrix: function ( m, order, update ) {
  8630. var clamp = _Math.clamp;
  8631. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8632. var te = m.elements;
  8633. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  8634. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  8635. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  8636. order = order || this._order;
  8637. if ( order === 'XYZ' ) {
  8638. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  8639. if ( Math.abs( m13 ) < 0.99999 ) {
  8640. this._x = Math.atan2( - m23, m33 );
  8641. this._z = Math.atan2( - m12, m11 );
  8642. } else {
  8643. this._x = Math.atan2( m32, m22 );
  8644. this._z = 0;
  8645. }
  8646. } else if ( order === 'YXZ' ) {
  8647. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  8648. if ( Math.abs( m23 ) < 0.99999 ) {
  8649. this._y = Math.atan2( m13, m33 );
  8650. this._z = Math.atan2( m21, m22 );
  8651. } else {
  8652. this._y = Math.atan2( - m31, m11 );
  8653. this._z = 0;
  8654. }
  8655. } else if ( order === 'ZXY' ) {
  8656. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  8657. if ( Math.abs( m32 ) < 0.99999 ) {
  8658. this._y = Math.atan2( - m31, m33 );
  8659. this._z = Math.atan2( - m12, m22 );
  8660. } else {
  8661. this._y = 0;
  8662. this._z = Math.atan2( m21, m11 );
  8663. }
  8664. } else if ( order === 'ZYX' ) {
  8665. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  8666. if ( Math.abs( m31 ) < 0.99999 ) {
  8667. this._x = Math.atan2( m32, m33 );
  8668. this._z = Math.atan2( m21, m11 );
  8669. } else {
  8670. this._x = 0;
  8671. this._z = Math.atan2( - m12, m22 );
  8672. }
  8673. } else if ( order === 'YZX' ) {
  8674. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  8675. if ( Math.abs( m21 ) < 0.99999 ) {
  8676. this._x = Math.atan2( - m23, m22 );
  8677. this._y = Math.atan2( - m31, m11 );
  8678. } else {
  8679. this._x = 0;
  8680. this._y = Math.atan2( m13, m33 );
  8681. }
  8682. } else if ( order === 'XZY' ) {
  8683. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  8684. if ( Math.abs( m12 ) < 0.99999 ) {
  8685. this._x = Math.atan2( m32, m22 );
  8686. this._y = Math.atan2( m13, m11 );
  8687. } else {
  8688. this._x = Math.atan2( - m23, m33 );
  8689. this._y = 0;
  8690. }
  8691. } else {
  8692. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  8693. }
  8694. this._order = order;
  8695. if ( update !== false ) this.onChangeCallback();
  8696. return this;
  8697. },
  8698. setFromQuaternion: function () {
  8699. var matrix = new Matrix4();
  8700. return function setFromQuaternion( q, order, update ) {
  8701. matrix.makeRotationFromQuaternion( q );
  8702. return this.setFromRotationMatrix( matrix, order, update );
  8703. };
  8704. }(),
  8705. setFromVector3: function ( v, order ) {
  8706. return this.set( v.x, v.y, v.z, order || this._order );
  8707. },
  8708. reorder: function () {
  8709. // WARNING: this discards revolution information -bhouston
  8710. var q = new Quaternion();
  8711. return function reorder( newOrder ) {
  8712. q.setFromEuler( this );
  8713. return this.setFromQuaternion( q, newOrder );
  8714. };
  8715. }(),
  8716. equals: function ( euler ) {
  8717. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  8718. },
  8719. fromArray: function ( array ) {
  8720. this._x = array[ 0 ];
  8721. this._y = array[ 1 ];
  8722. this._z = array[ 2 ];
  8723. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  8724. this.onChangeCallback();
  8725. return this;
  8726. },
  8727. toArray: function ( array, offset ) {
  8728. if ( array === undefined ) array = [];
  8729. if ( offset === undefined ) offset = 0;
  8730. array[ offset ] = this._x;
  8731. array[ offset + 1 ] = this._y;
  8732. array[ offset + 2 ] = this._z;
  8733. array[ offset + 3 ] = this._order;
  8734. return array;
  8735. },
  8736. toVector3: function ( optionalResult ) {
  8737. if ( optionalResult ) {
  8738. return optionalResult.set( this._x, this._y, this._z );
  8739. } else {
  8740. return new Vector3( this._x, this._y, this._z );
  8741. }
  8742. },
  8743. onChange: function ( callback ) {
  8744. this.onChangeCallback = callback;
  8745. return this;
  8746. },
  8747. onChangeCallback: function () {}
  8748. } );
  8749. /**
  8750. * @author mrdoob / http://mrdoob.com/
  8751. */
  8752. function Layers() {
  8753. this.mask = 1 | 0;
  8754. }
  8755. Object.assign( Layers.prototype, {
  8756. set: function ( channel ) {
  8757. this.mask = 1 << channel | 0;
  8758. },
  8759. enable: function ( channel ) {
  8760. this.mask |= 1 << channel | 0;
  8761. },
  8762. toggle: function ( channel ) {
  8763. this.mask ^= 1 << channel | 0;
  8764. },
  8765. disable: function ( channel ) {
  8766. this.mask &= ~ ( 1 << channel | 0 );
  8767. },
  8768. test: function ( layers ) {
  8769. return ( this.mask & layers.mask ) !== 0;
  8770. }
  8771. } );
  8772. /**
  8773. * @author mrdoob / http://mrdoob.com/
  8774. * @author mikael emtinger / http://gomo.se/
  8775. * @author alteredq / http://alteredqualia.com/
  8776. * @author WestLangley / http://github.com/WestLangley
  8777. * @author elephantatwork / www.elephantatwork.ch
  8778. */
  8779. var object3DId = 0;
  8780. function Object3D() {
  8781. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  8782. this.uuid = _Math.generateUUID();
  8783. this.name = '';
  8784. this.type = 'Object3D';
  8785. this.parent = null;
  8786. this.children = [];
  8787. this.up = Object3D.DefaultUp.clone();
  8788. var position = new Vector3();
  8789. var rotation = new Euler();
  8790. var quaternion = new Quaternion();
  8791. var scale = new Vector3( 1, 1, 1 );
  8792. function onRotationChange() {
  8793. quaternion.setFromEuler( rotation, false );
  8794. }
  8795. function onQuaternionChange() {
  8796. rotation.setFromQuaternion( quaternion, undefined, false );
  8797. }
  8798. rotation.onChange( onRotationChange );
  8799. quaternion.onChange( onQuaternionChange );
  8800. Object.defineProperties( this, {
  8801. position: {
  8802. enumerable: true,
  8803. value: position
  8804. },
  8805. rotation: {
  8806. enumerable: true,
  8807. value: rotation
  8808. },
  8809. quaternion: {
  8810. enumerable: true,
  8811. value: quaternion
  8812. },
  8813. scale: {
  8814. enumerable: true,
  8815. value: scale
  8816. },
  8817. modelViewMatrix: {
  8818. value: new Matrix4()
  8819. },
  8820. normalMatrix: {
  8821. value: new Matrix3()
  8822. }
  8823. } );
  8824. this.matrix = new Matrix4();
  8825. this.matrixWorld = new Matrix4();
  8826. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  8827. this.matrixWorldNeedsUpdate = false;
  8828. this.layers = new Layers();
  8829. this.visible = true;
  8830. this.castShadow = false;
  8831. this.receiveShadow = false;
  8832. this.frustumCulled = true;
  8833. this.renderOrder = 0;
  8834. this.userData = {};
  8835. }
  8836. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  8837. Object3D.DefaultMatrixAutoUpdate = true;
  8838. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  8839. constructor: Object3D,
  8840. isObject3D: true,
  8841. onBeforeRender: function () {},
  8842. onAfterRender: function () {},
  8843. applyMatrix: function ( matrix ) {
  8844. this.matrix.multiplyMatrices( matrix, this.matrix );
  8845. this.matrix.decompose( this.position, this.quaternion, this.scale );
  8846. },
  8847. applyQuaternion: function ( q ) {
  8848. this.quaternion.premultiply( q );
  8849. return this;
  8850. },
  8851. setRotationFromAxisAngle: function ( axis, angle ) {
  8852. // assumes axis is normalized
  8853. this.quaternion.setFromAxisAngle( axis, angle );
  8854. },
  8855. setRotationFromEuler: function ( euler ) {
  8856. this.quaternion.setFromEuler( euler, true );
  8857. },
  8858. setRotationFromMatrix: function ( m ) {
  8859. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8860. this.quaternion.setFromRotationMatrix( m );
  8861. },
  8862. setRotationFromQuaternion: function ( q ) {
  8863. // assumes q is normalized
  8864. this.quaternion.copy( q );
  8865. },
  8866. rotateOnAxis: function () {
  8867. // rotate object on axis in object space
  8868. // axis is assumed to be normalized
  8869. var q1 = new Quaternion();
  8870. return function rotateOnAxis( axis, angle ) {
  8871. q1.setFromAxisAngle( axis, angle );
  8872. this.quaternion.multiply( q1 );
  8873. return this;
  8874. };
  8875. }(),
  8876. rotateOnWorldAxis: function () {
  8877. // rotate object on axis in world space
  8878. // axis is assumed to be normalized
  8879. // method assumes no rotated parent
  8880. var q1 = new Quaternion();
  8881. return function rotateOnWorldAxis( axis, angle ) {
  8882. q1.setFromAxisAngle( axis, angle );
  8883. this.quaternion.premultiply( q1 );
  8884. return this;
  8885. };
  8886. }(),
  8887. rotateX: function () {
  8888. var v1 = new Vector3( 1, 0, 0 );
  8889. return function rotateX( angle ) {
  8890. return this.rotateOnAxis( v1, angle );
  8891. };
  8892. }(),
  8893. rotateY: function () {
  8894. var v1 = new Vector3( 0, 1, 0 );
  8895. return function rotateY( angle ) {
  8896. return this.rotateOnAxis( v1, angle );
  8897. };
  8898. }(),
  8899. rotateZ: function () {
  8900. var v1 = new Vector3( 0, 0, 1 );
  8901. return function rotateZ( angle ) {
  8902. return this.rotateOnAxis( v1, angle );
  8903. };
  8904. }(),
  8905. translateOnAxis: function () {
  8906. // translate object by distance along axis in object space
  8907. // axis is assumed to be normalized
  8908. var v1 = new Vector3();
  8909. return function translateOnAxis( axis, distance ) {
  8910. v1.copy( axis ).applyQuaternion( this.quaternion );
  8911. this.position.add( v1.multiplyScalar( distance ) );
  8912. return this;
  8913. };
  8914. }(),
  8915. translateX: function () {
  8916. var v1 = new Vector3( 1, 0, 0 );
  8917. return function translateX( distance ) {
  8918. return this.translateOnAxis( v1, distance );
  8919. };
  8920. }(),
  8921. translateY: function () {
  8922. var v1 = new Vector3( 0, 1, 0 );
  8923. return function translateY( distance ) {
  8924. return this.translateOnAxis( v1, distance );
  8925. };
  8926. }(),
  8927. translateZ: function () {
  8928. var v1 = new Vector3( 0, 0, 1 );
  8929. return function translateZ( distance ) {
  8930. return this.translateOnAxis( v1, distance );
  8931. };
  8932. }(),
  8933. localToWorld: function ( vector ) {
  8934. return vector.applyMatrix4( this.matrixWorld );
  8935. },
  8936. worldToLocal: function () {
  8937. var m1 = new Matrix4();
  8938. return function worldToLocal( vector ) {
  8939. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  8940. };
  8941. }(),
  8942. lookAt: function () {
  8943. // This method does not support objects with rotated and/or translated parent(s)
  8944. var m1 = new Matrix4();
  8945. var vector = new Vector3();
  8946. return function lookAt( x, y, z ) {
  8947. if ( x.isVector3 ) {
  8948. vector.copy( x );
  8949. } else {
  8950. vector.set( x, y, z );
  8951. }
  8952. if ( this.isCamera ) {
  8953. m1.lookAt( this.position, vector, this.up );
  8954. } else {
  8955. m1.lookAt( vector, this.position, this.up );
  8956. }
  8957. this.quaternion.setFromRotationMatrix( m1 );
  8958. };
  8959. }(),
  8960. add: function ( object ) {
  8961. if ( arguments.length > 1 ) {
  8962. for ( var i = 0; i < arguments.length; i ++ ) {
  8963. this.add( arguments[ i ] );
  8964. }
  8965. return this;
  8966. }
  8967. if ( object === this ) {
  8968. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  8969. return this;
  8970. }
  8971. if ( ( object && object.isObject3D ) ) {
  8972. if ( object.parent !== null ) {
  8973. object.parent.remove( object );
  8974. }
  8975. object.parent = this;
  8976. object.dispatchEvent( { type: 'added' } );
  8977. this.children.push( object );
  8978. } else {
  8979. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  8980. }
  8981. return this;
  8982. },
  8983. remove: function ( object ) {
  8984. if ( arguments.length > 1 ) {
  8985. for ( var i = 0; i < arguments.length; i ++ ) {
  8986. this.remove( arguments[ i ] );
  8987. }
  8988. return this;
  8989. }
  8990. var index = this.children.indexOf( object );
  8991. if ( index !== - 1 ) {
  8992. object.parent = null;
  8993. object.dispatchEvent( { type: 'removed' } );
  8994. this.children.splice( index, 1 );
  8995. }
  8996. return this;
  8997. },
  8998. getObjectById: function ( id ) {
  8999. return this.getObjectByProperty( 'id', id );
  9000. },
  9001. getObjectByName: function ( name ) {
  9002. return this.getObjectByProperty( 'name', name );
  9003. },
  9004. getObjectByProperty: function ( name, value ) {
  9005. if ( this[ name ] === value ) return this;
  9006. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9007. var child = this.children[ i ];
  9008. var object = child.getObjectByProperty( name, value );
  9009. if ( object !== undefined ) {
  9010. return object;
  9011. }
  9012. }
  9013. return undefined;
  9014. },
  9015. getWorldPosition: function ( target ) {
  9016. if ( target === undefined ) {
  9017. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  9018. target = new Vector3();
  9019. }
  9020. this.updateMatrixWorld( true );
  9021. return target.setFromMatrixPosition( this.matrixWorld );
  9022. },
  9023. getWorldQuaternion: function () {
  9024. var position = new Vector3();
  9025. var scale = new Vector3();
  9026. return function getWorldQuaternion( target ) {
  9027. if ( target === undefined ) {
  9028. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  9029. target = new Quaternion();
  9030. }
  9031. this.updateMatrixWorld( true );
  9032. this.matrixWorld.decompose( position, target, scale );
  9033. return target;
  9034. };
  9035. }(),
  9036. getWorldScale: function () {
  9037. var position = new Vector3();
  9038. var quaternion = new Quaternion();
  9039. return function getWorldScale( target ) {
  9040. if ( target === undefined ) {
  9041. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  9042. target = new Vector3();
  9043. }
  9044. this.updateMatrixWorld( true );
  9045. this.matrixWorld.decompose( position, quaternion, target );
  9046. return target;
  9047. };
  9048. }(),
  9049. getWorldDirection: function () {
  9050. var quaternion = new Quaternion();
  9051. return function getWorldDirection( target ) {
  9052. if ( target === undefined ) {
  9053. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  9054. target = new Vector3();
  9055. }
  9056. this.getWorldQuaternion( quaternion );
  9057. return target.set( 0, 0, 1 ).applyQuaternion( quaternion );
  9058. };
  9059. }(),
  9060. raycast: function () {},
  9061. traverse: function ( callback ) {
  9062. callback( this );
  9063. var children = this.children;
  9064. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9065. children[ i ].traverse( callback );
  9066. }
  9067. },
  9068. traverseVisible: function ( callback ) {
  9069. if ( this.visible === false ) return;
  9070. callback( this );
  9071. var children = this.children;
  9072. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9073. children[ i ].traverseVisible( callback );
  9074. }
  9075. },
  9076. traverseAncestors: function ( callback ) {
  9077. var parent = this.parent;
  9078. if ( parent !== null ) {
  9079. callback( parent );
  9080. parent.traverseAncestors( callback );
  9081. }
  9082. },
  9083. updateMatrix: function () {
  9084. this.matrix.compose( this.position, this.quaternion, this.scale );
  9085. this.matrixWorldNeedsUpdate = true;
  9086. },
  9087. updateMatrixWorld: function ( force ) {
  9088. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9089. if ( this.matrixWorldNeedsUpdate || force ) {
  9090. if ( this.parent === null ) {
  9091. this.matrixWorld.copy( this.matrix );
  9092. } else {
  9093. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9094. }
  9095. this.matrixWorldNeedsUpdate = false;
  9096. force = true;
  9097. }
  9098. // update children
  9099. var children = this.children;
  9100. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9101. children[ i ].updateMatrixWorld( force );
  9102. }
  9103. },
  9104. toJSON: function ( meta ) {
  9105. // meta is a string when called from JSON.stringify
  9106. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  9107. var output = {};
  9108. // meta is a hash used to collect geometries, materials.
  9109. // not providing it implies that this is the root object
  9110. // being serialized.
  9111. if ( isRootObject ) {
  9112. // initialize meta obj
  9113. meta = {
  9114. geometries: {},
  9115. materials: {},
  9116. textures: {},
  9117. images: {},
  9118. shapes: {}
  9119. };
  9120. output.metadata = {
  9121. version: 4.5,
  9122. type: 'Object',
  9123. generator: 'Object3D.toJSON'
  9124. };
  9125. }
  9126. // standard Object3D serialization
  9127. var object = {};
  9128. object.uuid = this.uuid;
  9129. object.type = this.type;
  9130. if ( this.name !== '' ) object.name = this.name;
  9131. if ( this.castShadow === true ) object.castShadow = true;
  9132. if ( this.receiveShadow === true ) object.receiveShadow = true;
  9133. if ( this.visible === false ) object.visible = false;
  9134. if ( this.frustumCulled === false ) object.frustumCulled = false;
  9135. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  9136. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  9137. object.layers = this.layers.mask;
  9138. object.matrix = this.matrix.toArray();
  9139. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  9140. //
  9141. function serialize( library, element ) {
  9142. if ( library[ element.uuid ] === undefined ) {
  9143. library[ element.uuid ] = element.toJSON( meta );
  9144. }
  9145. return element.uuid;
  9146. }
  9147. if ( this.isMesh || this.isLine || this.isPoints ) {
  9148. object.geometry = serialize( meta.geometries, this.geometry );
  9149. var parameters = this.geometry.parameters;
  9150. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  9151. var shapes = parameters.shapes;
  9152. if ( Array.isArray( shapes ) ) {
  9153. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  9154. var shape = shapes[ i ];
  9155. serialize( meta.shapes, shape );
  9156. }
  9157. } else {
  9158. serialize( meta.shapes, shapes );
  9159. }
  9160. }
  9161. }
  9162. if ( this.material !== undefined ) {
  9163. if ( Array.isArray( this.material ) ) {
  9164. var uuids = [];
  9165. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  9166. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  9167. }
  9168. object.material = uuids;
  9169. } else {
  9170. object.material = serialize( meta.materials, this.material );
  9171. }
  9172. }
  9173. //
  9174. if ( this.children.length > 0 ) {
  9175. object.children = [];
  9176. for ( var i = 0; i < this.children.length; i ++ ) {
  9177. object.children.push( this.children[ i ].toJSON( meta ).object );
  9178. }
  9179. }
  9180. if ( isRootObject ) {
  9181. var geometries = extractFromCache( meta.geometries );
  9182. var materials = extractFromCache( meta.materials );
  9183. var textures = extractFromCache( meta.textures );
  9184. var images = extractFromCache( meta.images );
  9185. var shapes = extractFromCache( meta.shapes );
  9186. if ( geometries.length > 0 ) output.geometries = geometries;
  9187. if ( materials.length > 0 ) output.materials = materials;
  9188. if ( textures.length > 0 ) output.textures = textures;
  9189. if ( images.length > 0 ) output.images = images;
  9190. if ( shapes.length > 0 ) output.shapes = shapes;
  9191. }
  9192. output.object = object;
  9193. return output;
  9194. // extract data from the cache hash
  9195. // remove metadata on each item
  9196. // and return as array
  9197. function extractFromCache( cache ) {
  9198. var values = [];
  9199. for ( var key in cache ) {
  9200. var data = cache[ key ];
  9201. delete data.metadata;
  9202. values.push( data );
  9203. }
  9204. return values;
  9205. }
  9206. },
  9207. clone: function ( recursive ) {
  9208. return new this.constructor().copy( this, recursive );
  9209. },
  9210. copy: function ( source, recursive ) {
  9211. if ( recursive === undefined ) recursive = true;
  9212. this.name = source.name;
  9213. this.up.copy( source.up );
  9214. this.position.copy( source.position );
  9215. this.quaternion.copy( source.quaternion );
  9216. this.scale.copy( source.scale );
  9217. this.matrix.copy( source.matrix );
  9218. this.matrixWorld.copy( source.matrixWorld );
  9219. this.matrixAutoUpdate = source.matrixAutoUpdate;
  9220. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  9221. this.layers.mask = source.layers.mask;
  9222. this.visible = source.visible;
  9223. this.castShadow = source.castShadow;
  9224. this.receiveShadow = source.receiveShadow;
  9225. this.frustumCulled = source.frustumCulled;
  9226. this.renderOrder = source.renderOrder;
  9227. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  9228. if ( recursive === true ) {
  9229. for ( var i = 0; i < source.children.length; i ++ ) {
  9230. var child = source.children[ i ];
  9231. this.add( child.clone() );
  9232. }
  9233. }
  9234. return this;
  9235. }
  9236. } );
  9237. /**
  9238. * @author mrdoob / http://mrdoob.com/
  9239. * @author mikael emtinger / http://gomo.se/
  9240. * @author WestLangley / http://github.com/WestLangley
  9241. */
  9242. function Camera() {
  9243. Object3D.call( this );
  9244. this.type = 'Camera';
  9245. this.matrixWorldInverse = new Matrix4();
  9246. this.projectionMatrix = new Matrix4();
  9247. }
  9248. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9249. constructor: Camera,
  9250. isCamera: true,
  9251. copy: function ( source, recursive ) {
  9252. Object3D.prototype.copy.call( this, source, recursive );
  9253. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9254. this.projectionMatrix.copy( source.projectionMatrix );
  9255. return this;
  9256. },
  9257. getWorldDirection: function () {
  9258. var quaternion = new Quaternion();
  9259. return function getWorldDirection( target ) {
  9260. if ( target === undefined ) {
  9261. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  9262. target = new Vector3();
  9263. }
  9264. this.getWorldQuaternion( quaternion );
  9265. return target.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9266. };
  9267. }(),
  9268. updateMatrixWorld: function ( force ) {
  9269. Object3D.prototype.updateMatrixWorld.call( this, force );
  9270. this.matrixWorldInverse.getInverse( this.matrixWorld );
  9271. },
  9272. clone: function () {
  9273. return new this.constructor().copy( this );
  9274. }
  9275. } );
  9276. /**
  9277. * @author alteredq / http://alteredqualia.com/
  9278. * @author arose / http://github.com/arose
  9279. */
  9280. function OrthographicCamera( left, right, top, bottom, near, far ) {
  9281. Camera.call( this );
  9282. this.type = 'OrthographicCamera';
  9283. this.zoom = 1;
  9284. this.view = null;
  9285. this.left = left;
  9286. this.right = right;
  9287. this.top = top;
  9288. this.bottom = bottom;
  9289. this.near = ( near !== undefined ) ? near : 0.1;
  9290. this.far = ( far !== undefined ) ? far : 2000;
  9291. this.updateProjectionMatrix();
  9292. }
  9293. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9294. constructor: OrthographicCamera,
  9295. isOrthographicCamera: true,
  9296. copy: function ( source, recursive ) {
  9297. Camera.prototype.copy.call( this, source, recursive );
  9298. this.left = source.left;
  9299. this.right = source.right;
  9300. this.top = source.top;
  9301. this.bottom = source.bottom;
  9302. this.near = source.near;
  9303. this.far = source.far;
  9304. this.zoom = source.zoom;
  9305. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9306. return this;
  9307. },
  9308. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  9309. if ( this.view === null ) {
  9310. this.view = {
  9311. enabled: true,
  9312. fullWidth: 1,
  9313. fullHeight: 1,
  9314. offsetX: 0,
  9315. offsetY: 0,
  9316. width: 1,
  9317. height: 1
  9318. };
  9319. }
  9320. this.view.enabled = true;
  9321. this.view.fullWidth = fullWidth;
  9322. this.view.fullHeight = fullHeight;
  9323. this.view.offsetX = x;
  9324. this.view.offsetY = y;
  9325. this.view.width = width;
  9326. this.view.height = height;
  9327. this.updateProjectionMatrix();
  9328. },
  9329. clearViewOffset: function () {
  9330. if ( this.view !== null ) {
  9331. this.view.enabled = false;
  9332. }
  9333. this.updateProjectionMatrix();
  9334. },
  9335. updateProjectionMatrix: function () {
  9336. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9337. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9338. var cx = ( this.right + this.left ) / 2;
  9339. var cy = ( this.top + this.bottom ) / 2;
  9340. var left = cx - dx;
  9341. var right = cx + dx;
  9342. var top = cy + dy;
  9343. var bottom = cy - dy;
  9344. if ( this.view !== null && this.view.enabled ) {
  9345. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  9346. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  9347. var scaleW = ( this.right - this.left ) / this.view.width;
  9348. var scaleH = ( this.top - this.bottom ) / this.view.height;
  9349. left += scaleW * ( this.view.offsetX / zoomW );
  9350. right = left + scaleW * ( this.view.width / zoomW );
  9351. top -= scaleH * ( this.view.offsetY / zoomH );
  9352. bottom = top - scaleH * ( this.view.height / zoomH );
  9353. }
  9354. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9355. },
  9356. toJSON: function ( meta ) {
  9357. var data = Object3D.prototype.toJSON.call( this, meta );
  9358. data.object.zoom = this.zoom;
  9359. data.object.left = this.left;
  9360. data.object.right = this.right;
  9361. data.object.top = this.top;
  9362. data.object.bottom = this.bottom;
  9363. data.object.near = this.near;
  9364. data.object.far = this.far;
  9365. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9366. return data;
  9367. }
  9368. } );
  9369. /**
  9370. * @author mrdoob / http://mrdoob.com/
  9371. * @author alteredq / http://alteredqualia.com/
  9372. */
  9373. function Face3( a, b, c, normal, color, materialIndex ) {
  9374. this.a = a;
  9375. this.b = b;
  9376. this.c = c;
  9377. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  9378. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  9379. this.color = ( color && color.isColor ) ? color : new Color();
  9380. this.vertexColors = Array.isArray( color ) ? color : [];
  9381. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  9382. }
  9383. Object.assign( Face3.prototype, {
  9384. clone: function () {
  9385. return new this.constructor().copy( this );
  9386. },
  9387. copy: function ( source ) {
  9388. this.a = source.a;
  9389. this.b = source.b;
  9390. this.c = source.c;
  9391. this.normal.copy( source.normal );
  9392. this.color.copy( source.color );
  9393. this.materialIndex = source.materialIndex;
  9394. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  9395. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  9396. }
  9397. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  9398. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  9399. }
  9400. return this;
  9401. }
  9402. } );
  9403. /**
  9404. * @author mrdoob / http://mrdoob.com/
  9405. * @author kile / http://kile.stravaganza.org/
  9406. * @author alteredq / http://alteredqualia.com/
  9407. * @author mikael emtinger / http://gomo.se/
  9408. * @author zz85 / http://www.lab4games.net/zz85/blog
  9409. * @author bhouston / http://clara.io
  9410. */
  9411. var geometryId = 0; // Geometry uses even numbers as Id
  9412. function Geometry() {
  9413. Object.defineProperty( this, 'id', { value: geometryId += 2 } );
  9414. this.uuid = _Math.generateUUID();
  9415. this.name = '';
  9416. this.type = 'Geometry';
  9417. this.vertices = [];
  9418. this.colors = [];
  9419. this.faces = [];
  9420. this.faceVertexUvs = [[]];
  9421. this.morphTargets = [];
  9422. this.morphNormals = [];
  9423. this.skinWeights = [];
  9424. this.skinIndices = [];
  9425. this.lineDistances = [];
  9426. this.boundingBox = null;
  9427. this.boundingSphere = null;
  9428. // update flags
  9429. this.elementsNeedUpdate = false;
  9430. this.verticesNeedUpdate = false;
  9431. this.uvsNeedUpdate = false;
  9432. this.normalsNeedUpdate = false;
  9433. this.colorsNeedUpdate = false;
  9434. this.lineDistancesNeedUpdate = false;
  9435. this.groupsNeedUpdate = false;
  9436. }
  9437. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  9438. constructor: Geometry,
  9439. isGeometry: true,
  9440. applyMatrix: function ( matrix ) {
  9441. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  9442. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  9443. var vertex = this.vertices[ i ];
  9444. vertex.applyMatrix4( matrix );
  9445. }
  9446. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  9447. var face = this.faces[ i ];
  9448. face.normal.applyMatrix3( normalMatrix ).normalize();
  9449. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  9450. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  9451. }
  9452. }
  9453. if ( this.boundingBox !== null ) {
  9454. this.computeBoundingBox();
  9455. }
  9456. if ( this.boundingSphere !== null ) {
  9457. this.computeBoundingSphere();
  9458. }
  9459. this.verticesNeedUpdate = true;
  9460. this.normalsNeedUpdate = true;
  9461. return this;
  9462. },
  9463. rotateX: function () {
  9464. // rotate geometry around world x-axis
  9465. var m1 = new Matrix4();
  9466. return function rotateX( angle ) {
  9467. m1.makeRotationX( angle );
  9468. this.applyMatrix( m1 );
  9469. return this;
  9470. };
  9471. }(),
  9472. rotateY: function () {
  9473. // rotate geometry around world y-axis
  9474. var m1 = new Matrix4();
  9475. return function rotateY( angle ) {
  9476. m1.makeRotationY( angle );
  9477. this.applyMatrix( m1 );
  9478. return this;
  9479. };
  9480. }(),
  9481. rotateZ: function () {
  9482. // rotate geometry around world z-axis
  9483. var m1 = new Matrix4();
  9484. return function rotateZ( angle ) {
  9485. m1.makeRotationZ( angle );
  9486. this.applyMatrix( m1 );
  9487. return this;
  9488. };
  9489. }(),
  9490. translate: function () {
  9491. // translate geometry
  9492. var m1 = new Matrix4();
  9493. return function translate( x, y, z ) {
  9494. m1.makeTranslation( x, y, z );
  9495. this.applyMatrix( m1 );
  9496. return this;
  9497. };
  9498. }(),
  9499. scale: function () {
  9500. // scale geometry
  9501. var m1 = new Matrix4();
  9502. return function scale( x, y, z ) {
  9503. m1.makeScale( x, y, z );
  9504. this.applyMatrix( m1 );
  9505. return this;
  9506. };
  9507. }(),
  9508. lookAt: function () {
  9509. var obj = new Object3D();
  9510. return function lookAt( vector ) {
  9511. obj.lookAt( vector );
  9512. obj.updateMatrix();
  9513. this.applyMatrix( obj.matrix );
  9514. };
  9515. }(),
  9516. fromBufferGeometry: function ( geometry ) {
  9517. var scope = this;
  9518. var indices = geometry.index !== null ? geometry.index.array : undefined;
  9519. var attributes = geometry.attributes;
  9520. var positions = attributes.position.array;
  9521. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  9522. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  9523. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  9524. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  9525. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  9526. var tempNormals = [];
  9527. var tempUVs = [];
  9528. var tempUVs2 = [];
  9529. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  9530. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  9531. if ( normals !== undefined ) {
  9532. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  9533. }
  9534. if ( colors !== undefined ) {
  9535. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  9536. }
  9537. if ( uvs !== undefined ) {
  9538. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  9539. }
  9540. if ( uvs2 !== undefined ) {
  9541. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  9542. }
  9543. }
  9544. function addFace( a, b, c, materialIndex ) {
  9545. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  9546. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  9547. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  9548. scope.faces.push( face );
  9549. if ( uvs !== undefined ) {
  9550. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  9551. }
  9552. if ( uvs2 !== undefined ) {
  9553. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  9554. }
  9555. }
  9556. var groups = geometry.groups;
  9557. if ( groups.length > 0 ) {
  9558. for ( var i = 0; i < groups.length; i ++ ) {
  9559. var group = groups[ i ];
  9560. var start = group.start;
  9561. var count = group.count;
  9562. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  9563. if ( indices !== undefined ) {
  9564. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  9565. } else {
  9566. addFace( j, j + 1, j + 2, group.materialIndex );
  9567. }
  9568. }
  9569. }
  9570. } else {
  9571. if ( indices !== undefined ) {
  9572. for ( var i = 0; i < indices.length; i += 3 ) {
  9573. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  9574. }
  9575. } else {
  9576. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  9577. addFace( i, i + 1, i + 2 );
  9578. }
  9579. }
  9580. }
  9581. this.computeFaceNormals();
  9582. if ( geometry.boundingBox !== null ) {
  9583. this.boundingBox = geometry.boundingBox.clone();
  9584. }
  9585. if ( geometry.boundingSphere !== null ) {
  9586. this.boundingSphere = geometry.boundingSphere.clone();
  9587. }
  9588. return this;
  9589. },
  9590. center: function () {
  9591. var offset = new Vector3();
  9592. return function center() {
  9593. this.computeBoundingBox();
  9594. this.boundingBox.getCenter( offset ).negate();
  9595. this.translate( offset.x, offset.y, offset.z );
  9596. return this;
  9597. };
  9598. }(),
  9599. normalize: function () {
  9600. this.computeBoundingSphere();
  9601. var center = this.boundingSphere.center;
  9602. var radius = this.boundingSphere.radius;
  9603. var s = radius === 0 ? 1 : 1.0 / radius;
  9604. var matrix = new Matrix4();
  9605. matrix.set(
  9606. s, 0, 0, - s * center.x,
  9607. 0, s, 0, - s * center.y,
  9608. 0, 0, s, - s * center.z,
  9609. 0, 0, 0, 1
  9610. );
  9611. this.applyMatrix( matrix );
  9612. return this;
  9613. },
  9614. computeFaceNormals: function () {
  9615. var cb = new Vector3(), ab = new Vector3();
  9616. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9617. var face = this.faces[ f ];
  9618. var vA = this.vertices[ face.a ];
  9619. var vB = this.vertices[ face.b ];
  9620. var vC = this.vertices[ face.c ];
  9621. cb.subVectors( vC, vB );
  9622. ab.subVectors( vA, vB );
  9623. cb.cross( ab );
  9624. cb.normalize();
  9625. face.normal.copy( cb );
  9626. }
  9627. },
  9628. computeVertexNormals: function ( areaWeighted ) {
  9629. if ( areaWeighted === undefined ) areaWeighted = true;
  9630. var v, vl, f, fl, face, vertices;
  9631. vertices = new Array( this.vertices.length );
  9632. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  9633. vertices[ v ] = new Vector3();
  9634. }
  9635. if ( areaWeighted ) {
  9636. // vertex normals weighted by triangle areas
  9637. // http://www.iquilezles.org/www/articles/normals/normals.htm
  9638. var vA, vB, vC;
  9639. var cb = new Vector3(), ab = new Vector3();
  9640. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9641. face = this.faces[ f ];
  9642. vA = this.vertices[ face.a ];
  9643. vB = this.vertices[ face.b ];
  9644. vC = this.vertices[ face.c ];
  9645. cb.subVectors( vC, vB );
  9646. ab.subVectors( vA, vB );
  9647. cb.cross( ab );
  9648. vertices[ face.a ].add( cb );
  9649. vertices[ face.b ].add( cb );
  9650. vertices[ face.c ].add( cb );
  9651. }
  9652. } else {
  9653. this.computeFaceNormals();
  9654. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9655. face = this.faces[ f ];
  9656. vertices[ face.a ].add( face.normal );
  9657. vertices[ face.b ].add( face.normal );
  9658. vertices[ face.c ].add( face.normal );
  9659. }
  9660. }
  9661. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  9662. vertices[ v ].normalize();
  9663. }
  9664. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9665. face = this.faces[ f ];
  9666. var vertexNormals = face.vertexNormals;
  9667. if ( vertexNormals.length === 3 ) {
  9668. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  9669. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  9670. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  9671. } else {
  9672. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  9673. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  9674. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  9675. }
  9676. }
  9677. if ( this.faces.length > 0 ) {
  9678. this.normalsNeedUpdate = true;
  9679. }
  9680. },
  9681. computeFlatVertexNormals: function () {
  9682. var f, fl, face;
  9683. this.computeFaceNormals();
  9684. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9685. face = this.faces[ f ];
  9686. var vertexNormals = face.vertexNormals;
  9687. if ( vertexNormals.length === 3 ) {
  9688. vertexNormals[ 0 ].copy( face.normal );
  9689. vertexNormals[ 1 ].copy( face.normal );
  9690. vertexNormals[ 2 ].copy( face.normal );
  9691. } else {
  9692. vertexNormals[ 0 ] = face.normal.clone();
  9693. vertexNormals[ 1 ] = face.normal.clone();
  9694. vertexNormals[ 2 ] = face.normal.clone();
  9695. }
  9696. }
  9697. if ( this.faces.length > 0 ) {
  9698. this.normalsNeedUpdate = true;
  9699. }
  9700. },
  9701. computeMorphNormals: function () {
  9702. var i, il, f, fl, face;
  9703. // save original normals
  9704. // - create temp variables on first access
  9705. // otherwise just copy (for faster repeated calls)
  9706. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9707. face = this.faces[ f ];
  9708. if ( ! face.__originalFaceNormal ) {
  9709. face.__originalFaceNormal = face.normal.clone();
  9710. } else {
  9711. face.__originalFaceNormal.copy( face.normal );
  9712. }
  9713. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  9714. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  9715. if ( ! face.__originalVertexNormals[ i ] ) {
  9716. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  9717. } else {
  9718. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  9719. }
  9720. }
  9721. }
  9722. // use temp geometry to compute face and vertex normals for each morph
  9723. var tmpGeo = new Geometry();
  9724. tmpGeo.faces = this.faces;
  9725. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  9726. // create on first access
  9727. if ( ! this.morphNormals[ i ] ) {
  9728. this.morphNormals[ i ] = {};
  9729. this.morphNormals[ i ].faceNormals = [];
  9730. this.morphNormals[ i ].vertexNormals = [];
  9731. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  9732. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  9733. var faceNormal, vertexNormals;
  9734. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9735. faceNormal = new Vector3();
  9736. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  9737. dstNormalsFace.push( faceNormal );
  9738. dstNormalsVertex.push( vertexNormals );
  9739. }
  9740. }
  9741. var morphNormals = this.morphNormals[ i ];
  9742. // set vertices to morph target
  9743. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  9744. // compute morph normals
  9745. tmpGeo.computeFaceNormals();
  9746. tmpGeo.computeVertexNormals();
  9747. // store morph normals
  9748. var faceNormal, vertexNormals;
  9749. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9750. face = this.faces[ f ];
  9751. faceNormal = morphNormals.faceNormals[ f ];
  9752. vertexNormals = morphNormals.vertexNormals[ f ];
  9753. faceNormal.copy( face.normal );
  9754. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  9755. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  9756. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  9757. }
  9758. }
  9759. // restore original normals
  9760. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9761. face = this.faces[ f ];
  9762. face.normal = face.__originalFaceNormal;
  9763. face.vertexNormals = face.__originalVertexNormals;
  9764. }
  9765. },
  9766. computeBoundingBox: function () {
  9767. if ( this.boundingBox === null ) {
  9768. this.boundingBox = new Box3();
  9769. }
  9770. this.boundingBox.setFromPoints( this.vertices );
  9771. },
  9772. computeBoundingSphere: function () {
  9773. if ( this.boundingSphere === null ) {
  9774. this.boundingSphere = new Sphere();
  9775. }
  9776. this.boundingSphere.setFromPoints( this.vertices );
  9777. },
  9778. merge: function ( geometry, matrix, materialIndexOffset ) {
  9779. if ( ! ( geometry && geometry.isGeometry ) ) {
  9780. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  9781. return;
  9782. }
  9783. var normalMatrix,
  9784. vertexOffset = this.vertices.length,
  9785. vertices1 = this.vertices,
  9786. vertices2 = geometry.vertices,
  9787. faces1 = this.faces,
  9788. faces2 = geometry.faces,
  9789. uvs1 = this.faceVertexUvs[ 0 ],
  9790. uvs2 = geometry.faceVertexUvs[ 0 ],
  9791. colors1 = this.colors,
  9792. colors2 = geometry.colors;
  9793. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  9794. if ( matrix !== undefined ) {
  9795. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  9796. }
  9797. // vertices
  9798. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  9799. var vertex = vertices2[ i ];
  9800. var vertexCopy = vertex.clone();
  9801. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  9802. vertices1.push( vertexCopy );
  9803. }
  9804. // colors
  9805. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  9806. colors1.push( colors2[ i ].clone() );
  9807. }
  9808. // faces
  9809. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  9810. var face = faces2[ i ], faceCopy, normal, color,
  9811. faceVertexNormals = face.vertexNormals,
  9812. faceVertexColors = face.vertexColors;
  9813. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  9814. faceCopy.normal.copy( face.normal );
  9815. if ( normalMatrix !== undefined ) {
  9816. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  9817. }
  9818. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  9819. normal = faceVertexNormals[ j ].clone();
  9820. if ( normalMatrix !== undefined ) {
  9821. normal.applyMatrix3( normalMatrix ).normalize();
  9822. }
  9823. faceCopy.vertexNormals.push( normal );
  9824. }
  9825. faceCopy.color.copy( face.color );
  9826. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  9827. color = faceVertexColors[ j ];
  9828. faceCopy.vertexColors.push( color.clone() );
  9829. }
  9830. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  9831. faces1.push( faceCopy );
  9832. }
  9833. // uvs
  9834. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  9835. var uv = uvs2[ i ], uvCopy = [];
  9836. if ( uv === undefined ) {
  9837. continue;
  9838. }
  9839. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  9840. uvCopy.push( uv[ j ].clone() );
  9841. }
  9842. uvs1.push( uvCopy );
  9843. }
  9844. },
  9845. mergeMesh: function ( mesh ) {
  9846. if ( ! ( mesh && mesh.isMesh ) ) {
  9847. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  9848. return;
  9849. }
  9850. if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();
  9851. this.merge( mesh.geometry, mesh.matrix );
  9852. },
  9853. /*
  9854. * Checks for duplicate vertices with hashmap.
  9855. * Duplicated vertices are removed
  9856. * and faces' vertices are updated.
  9857. */
  9858. mergeVertices: function () {
  9859. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  9860. var unique = [], changes = [];
  9861. var v, key;
  9862. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  9863. var precision = Math.pow( 10, precisionPoints );
  9864. var i, il, face;
  9865. var indices, j, jl;
  9866. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  9867. v = this.vertices[ i ];
  9868. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  9869. if ( verticesMap[ key ] === undefined ) {
  9870. verticesMap[ key ] = i;
  9871. unique.push( this.vertices[ i ] );
  9872. changes[ i ] = unique.length - 1;
  9873. } else {
  9874. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  9875. changes[ i ] = changes[ verticesMap[ key ] ];
  9876. }
  9877. }
  9878. // if faces are completely degenerate after merging vertices, we
  9879. // have to remove them from the geometry.
  9880. var faceIndicesToRemove = [];
  9881. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  9882. face = this.faces[ i ];
  9883. face.a = changes[ face.a ];
  9884. face.b = changes[ face.b ];
  9885. face.c = changes[ face.c ];
  9886. indices = [ face.a, face.b, face.c ];
  9887. // if any duplicate vertices are found in a Face3
  9888. // we have to remove the face as nothing can be saved
  9889. for ( var n = 0; n < 3; n ++ ) {
  9890. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  9891. faceIndicesToRemove.push( i );
  9892. break;
  9893. }
  9894. }
  9895. }
  9896. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  9897. var idx = faceIndicesToRemove[ i ];
  9898. this.faces.splice( idx, 1 );
  9899. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  9900. this.faceVertexUvs[ j ].splice( idx, 1 );
  9901. }
  9902. }
  9903. // Use unique set of vertices
  9904. var diff = this.vertices.length - unique.length;
  9905. this.vertices = unique;
  9906. return diff;
  9907. },
  9908. setFromPoints: function ( points ) {
  9909. this.vertices = [];
  9910. for ( var i = 0, l = points.length; i < l; i ++ ) {
  9911. var point = points[ i ];
  9912. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  9913. }
  9914. return this;
  9915. },
  9916. sortFacesByMaterialIndex: function () {
  9917. var faces = this.faces;
  9918. var length = faces.length;
  9919. // tag faces
  9920. for ( var i = 0; i < length; i ++ ) {
  9921. faces[ i ]._id = i;
  9922. }
  9923. // sort faces
  9924. function materialIndexSort( a, b ) {
  9925. return a.materialIndex - b.materialIndex;
  9926. }
  9927. faces.sort( materialIndexSort );
  9928. // sort uvs
  9929. var uvs1 = this.faceVertexUvs[ 0 ];
  9930. var uvs2 = this.faceVertexUvs[ 1 ];
  9931. var newUvs1, newUvs2;
  9932. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  9933. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  9934. for ( var i = 0; i < length; i ++ ) {
  9935. var id = faces[ i ]._id;
  9936. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  9937. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  9938. }
  9939. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  9940. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  9941. },
  9942. toJSON: function () {
  9943. var data = {
  9944. metadata: {
  9945. version: 4.5,
  9946. type: 'Geometry',
  9947. generator: 'Geometry.toJSON'
  9948. }
  9949. };
  9950. // standard Geometry serialization
  9951. data.uuid = this.uuid;
  9952. data.type = this.type;
  9953. if ( this.name !== '' ) data.name = this.name;
  9954. if ( this.parameters !== undefined ) {
  9955. var parameters = this.parameters;
  9956. for ( var key in parameters ) {
  9957. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  9958. }
  9959. return data;
  9960. }
  9961. var vertices = [];
  9962. for ( var i = 0; i < this.vertices.length; i ++ ) {
  9963. var vertex = this.vertices[ i ];
  9964. vertices.push( vertex.x, vertex.y, vertex.z );
  9965. }
  9966. var faces = [];
  9967. var normals = [];
  9968. var normalsHash = {};
  9969. var colors = [];
  9970. var colorsHash = {};
  9971. var uvs = [];
  9972. var uvsHash = {};
  9973. for ( var i = 0; i < this.faces.length; i ++ ) {
  9974. var face = this.faces[ i ];
  9975. var hasMaterial = true;
  9976. var hasFaceUv = false; // deprecated
  9977. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  9978. var hasFaceNormal = face.normal.length() > 0;
  9979. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  9980. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  9981. var hasFaceVertexColor = face.vertexColors.length > 0;
  9982. var faceType = 0;
  9983. faceType = setBit( faceType, 0, 0 ); // isQuad
  9984. faceType = setBit( faceType, 1, hasMaterial );
  9985. faceType = setBit( faceType, 2, hasFaceUv );
  9986. faceType = setBit( faceType, 3, hasFaceVertexUv );
  9987. faceType = setBit( faceType, 4, hasFaceNormal );
  9988. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  9989. faceType = setBit( faceType, 6, hasFaceColor );
  9990. faceType = setBit( faceType, 7, hasFaceVertexColor );
  9991. faces.push( faceType );
  9992. faces.push( face.a, face.b, face.c );
  9993. faces.push( face.materialIndex );
  9994. if ( hasFaceVertexUv ) {
  9995. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  9996. faces.push(
  9997. getUvIndex( faceVertexUvs[ 0 ] ),
  9998. getUvIndex( faceVertexUvs[ 1 ] ),
  9999. getUvIndex( faceVertexUvs[ 2 ] )
  10000. );
  10001. }
  10002. if ( hasFaceNormal ) {
  10003. faces.push( getNormalIndex( face.normal ) );
  10004. }
  10005. if ( hasFaceVertexNormal ) {
  10006. var vertexNormals = face.vertexNormals;
  10007. faces.push(
  10008. getNormalIndex( vertexNormals[ 0 ] ),
  10009. getNormalIndex( vertexNormals[ 1 ] ),
  10010. getNormalIndex( vertexNormals[ 2 ] )
  10011. );
  10012. }
  10013. if ( hasFaceColor ) {
  10014. faces.push( getColorIndex( face.color ) );
  10015. }
  10016. if ( hasFaceVertexColor ) {
  10017. var vertexColors = face.vertexColors;
  10018. faces.push(
  10019. getColorIndex( vertexColors[ 0 ] ),
  10020. getColorIndex( vertexColors[ 1 ] ),
  10021. getColorIndex( vertexColors[ 2 ] )
  10022. );
  10023. }
  10024. }
  10025. function setBit( value, position, enabled ) {
  10026. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  10027. }
  10028. function getNormalIndex( normal ) {
  10029. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  10030. if ( normalsHash[ hash ] !== undefined ) {
  10031. return normalsHash[ hash ];
  10032. }
  10033. normalsHash[ hash ] = normals.length / 3;
  10034. normals.push( normal.x, normal.y, normal.z );
  10035. return normalsHash[ hash ];
  10036. }
  10037. function getColorIndex( color ) {
  10038. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  10039. if ( colorsHash[ hash ] !== undefined ) {
  10040. return colorsHash[ hash ];
  10041. }
  10042. colorsHash[ hash ] = colors.length;
  10043. colors.push( color.getHex() );
  10044. return colorsHash[ hash ];
  10045. }
  10046. function getUvIndex( uv ) {
  10047. var hash = uv.x.toString() + uv.y.toString();
  10048. if ( uvsHash[ hash ] !== undefined ) {
  10049. return uvsHash[ hash ];
  10050. }
  10051. uvsHash[ hash ] = uvs.length / 2;
  10052. uvs.push( uv.x, uv.y );
  10053. return uvsHash[ hash ];
  10054. }
  10055. data.data = {};
  10056. data.data.vertices = vertices;
  10057. data.data.normals = normals;
  10058. if ( colors.length > 0 ) data.data.colors = colors;
  10059. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  10060. data.data.faces = faces;
  10061. return data;
  10062. },
  10063. clone: function () {
  10064. /*
  10065. // Handle primitives
  10066. var parameters = this.parameters;
  10067. if ( parameters !== undefined ) {
  10068. var values = [];
  10069. for ( var key in parameters ) {
  10070. values.push( parameters[ key ] );
  10071. }
  10072. var geometry = Object.create( this.constructor.prototype );
  10073. this.constructor.apply( geometry, values );
  10074. return geometry;
  10075. }
  10076. return new this.constructor().copy( this );
  10077. */
  10078. return new Geometry().copy( this );
  10079. },
  10080. copy: function ( source ) {
  10081. var i, il, j, jl, k, kl;
  10082. // reset
  10083. this.vertices = [];
  10084. this.colors = [];
  10085. this.faces = [];
  10086. this.faceVertexUvs = [[]];
  10087. this.morphTargets = [];
  10088. this.morphNormals = [];
  10089. this.skinWeights = [];
  10090. this.skinIndices = [];
  10091. this.lineDistances = [];
  10092. this.boundingBox = null;
  10093. this.boundingSphere = null;
  10094. // name
  10095. this.name = source.name;
  10096. // vertices
  10097. var vertices = source.vertices;
  10098. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  10099. this.vertices.push( vertices[ i ].clone() );
  10100. }
  10101. // colors
  10102. var colors = source.colors;
  10103. for ( i = 0, il = colors.length; i < il; i ++ ) {
  10104. this.colors.push( colors[ i ].clone() );
  10105. }
  10106. // faces
  10107. var faces = source.faces;
  10108. for ( i = 0, il = faces.length; i < il; i ++ ) {
  10109. this.faces.push( faces[ i ].clone() );
  10110. }
  10111. // face vertex uvs
  10112. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  10113. var faceVertexUvs = source.faceVertexUvs[ i ];
  10114. if ( this.faceVertexUvs[ i ] === undefined ) {
  10115. this.faceVertexUvs[ i ] = [];
  10116. }
  10117. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  10118. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  10119. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  10120. var uv = uvs[ k ];
  10121. uvsCopy.push( uv.clone() );
  10122. }
  10123. this.faceVertexUvs[ i ].push( uvsCopy );
  10124. }
  10125. }
  10126. // morph targets
  10127. var morphTargets = source.morphTargets;
  10128. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  10129. var morphTarget = {};
  10130. morphTarget.name = morphTargets[ i ].name;
  10131. // vertices
  10132. if ( morphTargets[ i ].vertices !== undefined ) {
  10133. morphTarget.vertices = [];
  10134. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  10135. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  10136. }
  10137. }
  10138. // normals
  10139. if ( morphTargets[ i ].normals !== undefined ) {
  10140. morphTarget.normals = [];
  10141. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  10142. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  10143. }
  10144. }
  10145. this.morphTargets.push( morphTarget );
  10146. }
  10147. // morph normals
  10148. var morphNormals = source.morphNormals;
  10149. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  10150. var morphNormal = {};
  10151. // vertex normals
  10152. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  10153. morphNormal.vertexNormals = [];
  10154. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  10155. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  10156. var destVertexNormal = {};
  10157. destVertexNormal.a = srcVertexNormal.a.clone();
  10158. destVertexNormal.b = srcVertexNormal.b.clone();
  10159. destVertexNormal.c = srcVertexNormal.c.clone();
  10160. morphNormal.vertexNormals.push( destVertexNormal );
  10161. }
  10162. }
  10163. // face normals
  10164. if ( morphNormals[ i ].faceNormals !== undefined ) {
  10165. morphNormal.faceNormals = [];
  10166. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  10167. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  10168. }
  10169. }
  10170. this.morphNormals.push( morphNormal );
  10171. }
  10172. // skin weights
  10173. var skinWeights = source.skinWeights;
  10174. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  10175. this.skinWeights.push( skinWeights[ i ].clone() );
  10176. }
  10177. // skin indices
  10178. var skinIndices = source.skinIndices;
  10179. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  10180. this.skinIndices.push( skinIndices[ i ].clone() );
  10181. }
  10182. // line distances
  10183. var lineDistances = source.lineDistances;
  10184. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  10185. this.lineDistances.push( lineDistances[ i ] );
  10186. }
  10187. // bounding box
  10188. var boundingBox = source.boundingBox;
  10189. if ( boundingBox !== null ) {
  10190. this.boundingBox = boundingBox.clone();
  10191. }
  10192. // bounding sphere
  10193. var boundingSphere = source.boundingSphere;
  10194. if ( boundingSphere !== null ) {
  10195. this.boundingSphere = boundingSphere.clone();
  10196. }
  10197. // update flags
  10198. this.elementsNeedUpdate = source.elementsNeedUpdate;
  10199. this.verticesNeedUpdate = source.verticesNeedUpdate;
  10200. this.uvsNeedUpdate = source.uvsNeedUpdate;
  10201. this.normalsNeedUpdate = source.normalsNeedUpdate;
  10202. this.colorsNeedUpdate = source.colorsNeedUpdate;
  10203. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  10204. this.groupsNeedUpdate = source.groupsNeedUpdate;
  10205. return this;
  10206. },
  10207. dispose: function () {
  10208. this.dispatchEvent( { type: 'dispose' } );
  10209. }
  10210. } );
  10211. /**
  10212. * @author mrdoob / http://mrdoob.com/
  10213. */
  10214. function BufferAttribute( array, itemSize, normalized ) {
  10215. if ( Array.isArray( array ) ) {
  10216. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  10217. }
  10218. this.name = '';
  10219. this.array = array;
  10220. this.itemSize = itemSize;
  10221. this.count = array !== undefined ? array.length / itemSize : 0;
  10222. this.normalized = normalized === true;
  10223. this.dynamic = false;
  10224. this.updateRange = { offset: 0, count: - 1 };
  10225. this.version = 0;
  10226. }
  10227. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  10228. set: function ( value ) {
  10229. if ( value === true ) this.version ++;
  10230. }
  10231. } );
  10232. Object.assign( BufferAttribute.prototype, {
  10233. isBufferAttribute: true,
  10234. onUploadCallback: function () {},
  10235. setArray: function ( array ) {
  10236. if ( Array.isArray( array ) ) {
  10237. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  10238. }
  10239. this.count = array !== undefined ? array.length / this.itemSize : 0;
  10240. this.array = array;
  10241. return this;
  10242. },
  10243. setDynamic: function ( value ) {
  10244. this.dynamic = value;
  10245. return this;
  10246. },
  10247. copy: function ( source ) {
  10248. this.name = source.name;
  10249. this.array = new source.array.constructor( source.array );
  10250. this.itemSize = source.itemSize;
  10251. this.count = source.count;
  10252. this.normalized = source.normalized;
  10253. this.dynamic = source.dynamic;
  10254. return this;
  10255. },
  10256. copyAt: function ( index1, attribute, index2 ) {
  10257. index1 *= this.itemSize;
  10258. index2 *= attribute.itemSize;
  10259. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  10260. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  10261. }
  10262. return this;
  10263. },
  10264. copyArray: function ( array ) {
  10265. this.array.set( array );
  10266. return this;
  10267. },
  10268. copyColorsArray: function ( colors ) {
  10269. var array = this.array, offset = 0;
  10270. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  10271. var color = colors[ i ];
  10272. if ( color === undefined ) {
  10273. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  10274. color = new Color();
  10275. }
  10276. array[ offset ++ ] = color.r;
  10277. array[ offset ++ ] = color.g;
  10278. array[ offset ++ ] = color.b;
  10279. }
  10280. return this;
  10281. },
  10282. copyVector2sArray: function ( vectors ) {
  10283. var array = this.array, offset = 0;
  10284. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10285. var vector = vectors[ i ];
  10286. if ( vector === undefined ) {
  10287. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  10288. vector = new Vector2();
  10289. }
  10290. array[ offset ++ ] = vector.x;
  10291. array[ offset ++ ] = vector.y;
  10292. }
  10293. return this;
  10294. },
  10295. copyVector3sArray: function ( vectors ) {
  10296. var array = this.array, offset = 0;
  10297. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10298. var vector = vectors[ i ];
  10299. if ( vector === undefined ) {
  10300. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  10301. vector = new Vector3();
  10302. }
  10303. array[ offset ++ ] = vector.x;
  10304. array[ offset ++ ] = vector.y;
  10305. array[ offset ++ ] = vector.z;
  10306. }
  10307. return this;
  10308. },
  10309. copyVector4sArray: function ( vectors ) {
  10310. var array = this.array, offset = 0;
  10311. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10312. var vector = vectors[ i ];
  10313. if ( vector === undefined ) {
  10314. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  10315. vector = new Vector4();
  10316. }
  10317. array[ offset ++ ] = vector.x;
  10318. array[ offset ++ ] = vector.y;
  10319. array[ offset ++ ] = vector.z;
  10320. array[ offset ++ ] = vector.w;
  10321. }
  10322. return this;
  10323. },
  10324. set: function ( value, offset ) {
  10325. if ( offset === undefined ) offset = 0;
  10326. this.array.set( value, offset );
  10327. return this;
  10328. },
  10329. getX: function ( index ) {
  10330. return this.array[ index * this.itemSize ];
  10331. },
  10332. setX: function ( index, x ) {
  10333. this.array[ index * this.itemSize ] = x;
  10334. return this;
  10335. },
  10336. getY: function ( index ) {
  10337. return this.array[ index * this.itemSize + 1 ];
  10338. },
  10339. setY: function ( index, y ) {
  10340. this.array[ index * this.itemSize + 1 ] = y;
  10341. return this;
  10342. },
  10343. getZ: function ( index ) {
  10344. return this.array[ index * this.itemSize + 2 ];
  10345. },
  10346. setZ: function ( index, z ) {
  10347. this.array[ index * this.itemSize + 2 ] = z;
  10348. return this;
  10349. },
  10350. getW: function ( index ) {
  10351. return this.array[ index * this.itemSize + 3 ];
  10352. },
  10353. setW: function ( index, w ) {
  10354. this.array[ index * this.itemSize + 3 ] = w;
  10355. return this;
  10356. },
  10357. setXY: function ( index, x, y ) {
  10358. index *= this.itemSize;
  10359. this.array[ index + 0 ] = x;
  10360. this.array[ index + 1 ] = y;
  10361. return this;
  10362. },
  10363. setXYZ: function ( index, x, y, z ) {
  10364. index *= this.itemSize;
  10365. this.array[ index + 0 ] = x;
  10366. this.array[ index + 1 ] = y;
  10367. this.array[ index + 2 ] = z;
  10368. return this;
  10369. },
  10370. setXYZW: function ( index, x, y, z, w ) {
  10371. index *= this.itemSize;
  10372. this.array[ index + 0 ] = x;
  10373. this.array[ index + 1 ] = y;
  10374. this.array[ index + 2 ] = z;
  10375. this.array[ index + 3 ] = w;
  10376. return this;
  10377. },
  10378. onUpload: function ( callback ) {
  10379. this.onUploadCallback = callback;
  10380. return this;
  10381. },
  10382. clone: function () {
  10383. return new this.constructor( this.array, this.itemSize ).copy( this );
  10384. }
  10385. } );
  10386. //
  10387. function Int8BufferAttribute( array, itemSize, normalized ) {
  10388. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  10389. }
  10390. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10391. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  10392. function Uint8BufferAttribute( array, itemSize, normalized ) {
  10393. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  10394. }
  10395. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10396. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  10397. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  10398. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  10399. }
  10400. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10401. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  10402. function Int16BufferAttribute( array, itemSize, normalized ) {
  10403. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  10404. }
  10405. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10406. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  10407. function Uint16BufferAttribute( array, itemSize, normalized ) {
  10408. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  10409. }
  10410. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10411. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  10412. function Int32BufferAttribute( array, itemSize, normalized ) {
  10413. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  10414. }
  10415. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10416. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  10417. function Uint32BufferAttribute( array, itemSize, normalized ) {
  10418. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  10419. }
  10420. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10421. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  10422. function Float32BufferAttribute( array, itemSize, normalized ) {
  10423. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  10424. }
  10425. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10426. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  10427. function Float64BufferAttribute( array, itemSize, normalized ) {
  10428. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  10429. }
  10430. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10431. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  10432. /**
  10433. * @author mrdoob / http://mrdoob.com/
  10434. */
  10435. function DirectGeometry() {
  10436. this.vertices = [];
  10437. this.normals = [];
  10438. this.colors = [];
  10439. this.uvs = [];
  10440. this.uvs2 = [];
  10441. this.groups = [];
  10442. this.morphTargets = {};
  10443. this.skinWeights = [];
  10444. this.skinIndices = [];
  10445. // this.lineDistances = [];
  10446. this.boundingBox = null;
  10447. this.boundingSphere = null;
  10448. // update flags
  10449. this.verticesNeedUpdate = false;
  10450. this.normalsNeedUpdate = false;
  10451. this.colorsNeedUpdate = false;
  10452. this.uvsNeedUpdate = false;
  10453. this.groupsNeedUpdate = false;
  10454. }
  10455. Object.assign( DirectGeometry.prototype, {
  10456. computeGroups: function ( geometry ) {
  10457. var group;
  10458. var groups = [];
  10459. var materialIndex = undefined;
  10460. var faces = geometry.faces;
  10461. for ( var i = 0; i < faces.length; i ++ ) {
  10462. var face = faces[ i ];
  10463. // materials
  10464. if ( face.materialIndex !== materialIndex ) {
  10465. materialIndex = face.materialIndex;
  10466. if ( group !== undefined ) {
  10467. group.count = ( i * 3 ) - group.start;
  10468. groups.push( group );
  10469. }
  10470. group = {
  10471. start: i * 3,
  10472. materialIndex: materialIndex
  10473. };
  10474. }
  10475. }
  10476. if ( group !== undefined ) {
  10477. group.count = ( i * 3 ) - group.start;
  10478. groups.push( group );
  10479. }
  10480. this.groups = groups;
  10481. },
  10482. fromGeometry: function ( geometry ) {
  10483. var faces = geometry.faces;
  10484. var vertices = geometry.vertices;
  10485. var faceVertexUvs = geometry.faceVertexUvs;
  10486. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  10487. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  10488. // morphs
  10489. var morphTargets = geometry.morphTargets;
  10490. var morphTargetsLength = morphTargets.length;
  10491. var morphTargetsPosition;
  10492. if ( morphTargetsLength > 0 ) {
  10493. morphTargetsPosition = [];
  10494. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  10495. morphTargetsPosition[ i ] = [];
  10496. }
  10497. this.morphTargets.position = morphTargetsPosition;
  10498. }
  10499. var morphNormals = geometry.morphNormals;
  10500. var morphNormalsLength = morphNormals.length;
  10501. var morphTargetsNormal;
  10502. if ( morphNormalsLength > 0 ) {
  10503. morphTargetsNormal = [];
  10504. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  10505. morphTargetsNormal[ i ] = [];
  10506. }
  10507. this.morphTargets.normal = morphTargetsNormal;
  10508. }
  10509. // skins
  10510. var skinIndices = geometry.skinIndices;
  10511. var skinWeights = geometry.skinWeights;
  10512. var hasSkinIndices = skinIndices.length === vertices.length;
  10513. var hasSkinWeights = skinWeights.length === vertices.length;
  10514. //
  10515. if ( vertices.length > 0 && faces.length === 0 ) {
  10516. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  10517. }
  10518. for ( var i = 0; i < faces.length; i ++ ) {
  10519. var face = faces[ i ];
  10520. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  10521. var vertexNormals = face.vertexNormals;
  10522. if ( vertexNormals.length === 3 ) {
  10523. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  10524. } else {
  10525. var normal = face.normal;
  10526. this.normals.push( normal, normal, normal );
  10527. }
  10528. var vertexColors = face.vertexColors;
  10529. if ( vertexColors.length === 3 ) {
  10530. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  10531. } else {
  10532. var color = face.color;
  10533. this.colors.push( color, color, color );
  10534. }
  10535. if ( hasFaceVertexUv === true ) {
  10536. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  10537. if ( vertexUvs !== undefined ) {
  10538. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  10539. } else {
  10540. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  10541. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  10542. }
  10543. }
  10544. if ( hasFaceVertexUv2 === true ) {
  10545. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  10546. if ( vertexUvs !== undefined ) {
  10547. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  10548. } else {
  10549. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  10550. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  10551. }
  10552. }
  10553. // morphs
  10554. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  10555. var morphTarget = morphTargets[ j ].vertices;
  10556. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  10557. }
  10558. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  10559. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  10560. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  10561. }
  10562. // skins
  10563. if ( hasSkinIndices ) {
  10564. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  10565. }
  10566. if ( hasSkinWeights ) {
  10567. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  10568. }
  10569. }
  10570. this.computeGroups( geometry );
  10571. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  10572. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  10573. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  10574. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  10575. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  10576. return this;
  10577. }
  10578. } );
  10579. /**
  10580. * @author mrdoob / http://mrdoob.com/
  10581. */
  10582. function arrayMax( array ) {
  10583. if ( array.length === 0 ) return - Infinity;
  10584. var max = array[ 0 ];
  10585. for ( var i = 1, l = array.length; i < l; ++ i ) {
  10586. if ( array[ i ] > max ) max = array[ i ];
  10587. }
  10588. return max;
  10589. }
  10590. /**
  10591. * @author alteredq / http://alteredqualia.com/
  10592. * @author mrdoob / http://mrdoob.com/
  10593. */
  10594. var bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  10595. function BufferGeometry() {
  10596. Object.defineProperty( this, 'id', { value: bufferGeometryId += 2 } );
  10597. this.uuid = _Math.generateUUID();
  10598. this.name = '';
  10599. this.type = 'BufferGeometry';
  10600. this.index = null;
  10601. this.attributes = {};
  10602. this.morphAttributes = {};
  10603. this.groups = [];
  10604. this.boundingBox = null;
  10605. this.boundingSphere = null;
  10606. this.drawRange = { start: 0, count: Infinity };
  10607. this.userData = {};
  10608. }
  10609. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  10610. constructor: BufferGeometry,
  10611. isBufferGeometry: true,
  10612. getIndex: function () {
  10613. return this.index;
  10614. },
  10615. setIndex: function ( index ) {
  10616. if ( Array.isArray( index ) ) {
  10617. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  10618. } else {
  10619. this.index = index;
  10620. }
  10621. },
  10622. addAttribute: function ( name, attribute ) {
  10623. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  10624. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  10625. return this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  10626. }
  10627. if ( name === 'index' ) {
  10628. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  10629. this.setIndex( attribute );
  10630. return this;
  10631. }
  10632. this.attributes[ name ] = attribute;
  10633. return this;
  10634. },
  10635. getAttribute: function ( name ) {
  10636. return this.attributes[ name ];
  10637. },
  10638. removeAttribute: function ( name ) {
  10639. delete this.attributes[ name ];
  10640. return this;
  10641. },
  10642. addGroup: function ( start, count, materialIndex ) {
  10643. this.groups.push( {
  10644. start: start,
  10645. count: count,
  10646. materialIndex: materialIndex !== undefined ? materialIndex : 0
  10647. } );
  10648. },
  10649. clearGroups: function () {
  10650. this.groups = [];
  10651. },
  10652. setDrawRange: function ( start, count ) {
  10653. this.drawRange.start = start;
  10654. this.drawRange.count = count;
  10655. },
  10656. applyMatrix: function ( matrix ) {
  10657. var position = this.attributes.position;
  10658. if ( position !== undefined ) {
  10659. matrix.applyToBufferAttribute( position );
  10660. position.needsUpdate = true;
  10661. }
  10662. var normal = this.attributes.normal;
  10663. if ( normal !== undefined ) {
  10664. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  10665. normalMatrix.applyToBufferAttribute( normal );
  10666. normal.needsUpdate = true;
  10667. }
  10668. if ( this.boundingBox !== null ) {
  10669. this.computeBoundingBox();
  10670. }
  10671. if ( this.boundingSphere !== null ) {
  10672. this.computeBoundingSphere();
  10673. }
  10674. return this;
  10675. },
  10676. rotateX: function () {
  10677. // rotate geometry around world x-axis
  10678. var m1 = new Matrix4();
  10679. return function rotateX( angle ) {
  10680. m1.makeRotationX( angle );
  10681. this.applyMatrix( m1 );
  10682. return this;
  10683. };
  10684. }(),
  10685. rotateY: function () {
  10686. // rotate geometry around world y-axis
  10687. var m1 = new Matrix4();
  10688. return function rotateY( angle ) {
  10689. m1.makeRotationY( angle );
  10690. this.applyMatrix( m1 );
  10691. return this;
  10692. };
  10693. }(),
  10694. rotateZ: function () {
  10695. // rotate geometry around world z-axis
  10696. var m1 = new Matrix4();
  10697. return function rotateZ( angle ) {
  10698. m1.makeRotationZ( angle );
  10699. this.applyMatrix( m1 );
  10700. return this;
  10701. };
  10702. }(),
  10703. translate: function () {
  10704. // translate geometry
  10705. var m1 = new Matrix4();
  10706. return function translate( x, y, z ) {
  10707. m1.makeTranslation( x, y, z );
  10708. this.applyMatrix( m1 );
  10709. return this;
  10710. };
  10711. }(),
  10712. scale: function () {
  10713. // scale geometry
  10714. var m1 = new Matrix4();
  10715. return function scale( x, y, z ) {
  10716. m1.makeScale( x, y, z );
  10717. this.applyMatrix( m1 );
  10718. return this;
  10719. };
  10720. }(),
  10721. lookAt: function () {
  10722. var obj = new Object3D();
  10723. return function lookAt( vector ) {
  10724. obj.lookAt( vector );
  10725. obj.updateMatrix();
  10726. this.applyMatrix( obj.matrix );
  10727. };
  10728. }(),
  10729. center: function () {
  10730. var offset = new Vector3();
  10731. return function center() {
  10732. this.computeBoundingBox();
  10733. this.boundingBox.getCenter( offset ).negate();
  10734. this.translate( offset.x, offset.y, offset.z );
  10735. return this;
  10736. };
  10737. }(),
  10738. setFromObject: function ( object ) {
  10739. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  10740. var geometry = object.geometry;
  10741. if ( object.isPoints || object.isLine ) {
  10742. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  10743. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  10744. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  10745. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  10746. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  10747. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  10748. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  10749. }
  10750. if ( geometry.boundingSphere !== null ) {
  10751. this.boundingSphere = geometry.boundingSphere.clone();
  10752. }
  10753. if ( geometry.boundingBox !== null ) {
  10754. this.boundingBox = geometry.boundingBox.clone();
  10755. }
  10756. } else if ( object.isMesh ) {
  10757. if ( geometry && geometry.isGeometry ) {
  10758. this.fromGeometry( geometry );
  10759. }
  10760. }
  10761. return this;
  10762. },
  10763. setFromPoints: function ( points ) {
  10764. var position = [];
  10765. for ( var i = 0, l = points.length; i < l; i ++ ) {
  10766. var point = points[ i ];
  10767. position.push( point.x, point.y, point.z || 0 );
  10768. }
  10769. this.addAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  10770. return this;
  10771. },
  10772. updateFromObject: function ( object ) {
  10773. var geometry = object.geometry;
  10774. if ( object.isMesh ) {
  10775. var direct = geometry.__directGeometry;
  10776. if ( geometry.elementsNeedUpdate === true ) {
  10777. direct = undefined;
  10778. geometry.elementsNeedUpdate = false;
  10779. }
  10780. if ( direct === undefined ) {
  10781. return this.fromGeometry( geometry );
  10782. }
  10783. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  10784. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  10785. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  10786. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  10787. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  10788. geometry.verticesNeedUpdate = false;
  10789. geometry.normalsNeedUpdate = false;
  10790. geometry.colorsNeedUpdate = false;
  10791. geometry.uvsNeedUpdate = false;
  10792. geometry.groupsNeedUpdate = false;
  10793. geometry = direct;
  10794. }
  10795. var attribute;
  10796. if ( geometry.verticesNeedUpdate === true ) {
  10797. attribute = this.attributes.position;
  10798. if ( attribute !== undefined ) {
  10799. attribute.copyVector3sArray( geometry.vertices );
  10800. attribute.needsUpdate = true;
  10801. }
  10802. geometry.verticesNeedUpdate = false;
  10803. }
  10804. if ( geometry.normalsNeedUpdate === true ) {
  10805. attribute = this.attributes.normal;
  10806. if ( attribute !== undefined ) {
  10807. attribute.copyVector3sArray( geometry.normals );
  10808. attribute.needsUpdate = true;
  10809. }
  10810. geometry.normalsNeedUpdate = false;
  10811. }
  10812. if ( geometry.colorsNeedUpdate === true ) {
  10813. attribute = this.attributes.color;
  10814. if ( attribute !== undefined ) {
  10815. attribute.copyColorsArray( geometry.colors );
  10816. attribute.needsUpdate = true;
  10817. }
  10818. geometry.colorsNeedUpdate = false;
  10819. }
  10820. if ( geometry.uvsNeedUpdate ) {
  10821. attribute = this.attributes.uv;
  10822. if ( attribute !== undefined ) {
  10823. attribute.copyVector2sArray( geometry.uvs );
  10824. attribute.needsUpdate = true;
  10825. }
  10826. geometry.uvsNeedUpdate = false;
  10827. }
  10828. if ( geometry.lineDistancesNeedUpdate ) {
  10829. attribute = this.attributes.lineDistance;
  10830. if ( attribute !== undefined ) {
  10831. attribute.copyArray( geometry.lineDistances );
  10832. attribute.needsUpdate = true;
  10833. }
  10834. geometry.lineDistancesNeedUpdate = false;
  10835. }
  10836. if ( geometry.groupsNeedUpdate ) {
  10837. geometry.computeGroups( object.geometry );
  10838. this.groups = geometry.groups;
  10839. geometry.groupsNeedUpdate = false;
  10840. }
  10841. return this;
  10842. },
  10843. fromGeometry: function ( geometry ) {
  10844. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  10845. return this.fromDirectGeometry( geometry.__directGeometry );
  10846. },
  10847. fromDirectGeometry: function ( geometry ) {
  10848. var positions = new Float32Array( geometry.vertices.length * 3 );
  10849. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  10850. if ( geometry.normals.length > 0 ) {
  10851. var normals = new Float32Array( geometry.normals.length * 3 );
  10852. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  10853. }
  10854. if ( geometry.colors.length > 0 ) {
  10855. var colors = new Float32Array( geometry.colors.length * 3 );
  10856. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  10857. }
  10858. if ( geometry.uvs.length > 0 ) {
  10859. var uvs = new Float32Array( geometry.uvs.length * 2 );
  10860. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  10861. }
  10862. if ( geometry.uvs2.length > 0 ) {
  10863. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  10864. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  10865. }
  10866. // groups
  10867. this.groups = geometry.groups;
  10868. // morphs
  10869. for ( var name in geometry.morphTargets ) {
  10870. var array = [];
  10871. var morphTargets = geometry.morphTargets[ name ];
  10872. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  10873. var morphTarget = morphTargets[ i ];
  10874. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  10875. array.push( attribute.copyVector3sArray( morphTarget ) );
  10876. }
  10877. this.morphAttributes[ name ] = array;
  10878. }
  10879. // skinning
  10880. if ( geometry.skinIndices.length > 0 ) {
  10881. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  10882. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  10883. }
  10884. if ( geometry.skinWeights.length > 0 ) {
  10885. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  10886. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  10887. }
  10888. //
  10889. if ( geometry.boundingSphere !== null ) {
  10890. this.boundingSphere = geometry.boundingSphere.clone();
  10891. }
  10892. if ( geometry.boundingBox !== null ) {
  10893. this.boundingBox = geometry.boundingBox.clone();
  10894. }
  10895. return this;
  10896. },
  10897. computeBoundingBox: function () {
  10898. if ( this.boundingBox === null ) {
  10899. this.boundingBox = new Box3();
  10900. }
  10901. var position = this.attributes.position;
  10902. if ( position !== undefined ) {
  10903. this.boundingBox.setFromBufferAttribute( position );
  10904. } else {
  10905. this.boundingBox.makeEmpty();
  10906. }
  10907. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  10908. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  10909. }
  10910. },
  10911. computeBoundingSphere: function () {
  10912. var box = new Box3();
  10913. var vector = new Vector3();
  10914. return function computeBoundingSphere() {
  10915. if ( this.boundingSphere === null ) {
  10916. this.boundingSphere = new Sphere();
  10917. }
  10918. var position = this.attributes.position;
  10919. if ( position ) {
  10920. var center = this.boundingSphere.center;
  10921. box.setFromBufferAttribute( position );
  10922. box.getCenter( center );
  10923. // hoping to find a boundingSphere with a radius smaller than the
  10924. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  10925. var maxRadiusSq = 0;
  10926. for ( var i = 0, il = position.count; i < il; i ++ ) {
  10927. vector.x = position.getX( i );
  10928. vector.y = position.getY( i );
  10929. vector.z = position.getZ( i );
  10930. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  10931. }
  10932. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  10933. if ( isNaN( this.boundingSphere.radius ) ) {
  10934. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  10935. }
  10936. }
  10937. };
  10938. }(),
  10939. computeFaceNormals: function () {
  10940. // backwards compatibility
  10941. },
  10942. computeVertexNormals: function () {
  10943. var index = this.index;
  10944. var attributes = this.attributes;
  10945. var groups = this.groups;
  10946. if ( attributes.position ) {
  10947. var positions = attributes.position.array;
  10948. if ( attributes.normal === undefined ) {
  10949. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  10950. } else {
  10951. // reset existing normals to zero
  10952. var array = attributes.normal.array;
  10953. for ( var i = 0, il = array.length; i < il; i ++ ) {
  10954. array[ i ] = 0;
  10955. }
  10956. }
  10957. var normals = attributes.normal.array;
  10958. var vA, vB, vC;
  10959. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  10960. var cb = new Vector3(), ab = new Vector3();
  10961. // indexed elements
  10962. if ( index ) {
  10963. var indices = index.array;
  10964. if ( groups.length === 0 ) {
  10965. this.addGroup( 0, indices.length );
  10966. }
  10967. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  10968. var group = groups[ j ];
  10969. var start = group.start;
  10970. var count = group.count;
  10971. for ( var i = start, il = start + count; i < il; i += 3 ) {
  10972. vA = indices[ i + 0 ] * 3;
  10973. vB = indices[ i + 1 ] * 3;
  10974. vC = indices[ i + 2 ] * 3;
  10975. pA.fromArray( positions, vA );
  10976. pB.fromArray( positions, vB );
  10977. pC.fromArray( positions, vC );
  10978. cb.subVectors( pC, pB );
  10979. ab.subVectors( pA, pB );
  10980. cb.cross( ab );
  10981. normals[ vA ] += cb.x;
  10982. normals[ vA + 1 ] += cb.y;
  10983. normals[ vA + 2 ] += cb.z;
  10984. normals[ vB ] += cb.x;
  10985. normals[ vB + 1 ] += cb.y;
  10986. normals[ vB + 2 ] += cb.z;
  10987. normals[ vC ] += cb.x;
  10988. normals[ vC + 1 ] += cb.y;
  10989. normals[ vC + 2 ] += cb.z;
  10990. }
  10991. }
  10992. } else {
  10993. // non-indexed elements (unconnected triangle soup)
  10994. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  10995. pA.fromArray( positions, i );
  10996. pB.fromArray( positions, i + 3 );
  10997. pC.fromArray( positions, i + 6 );
  10998. cb.subVectors( pC, pB );
  10999. ab.subVectors( pA, pB );
  11000. cb.cross( ab );
  11001. normals[ i ] = cb.x;
  11002. normals[ i + 1 ] = cb.y;
  11003. normals[ i + 2 ] = cb.z;
  11004. normals[ i + 3 ] = cb.x;
  11005. normals[ i + 4 ] = cb.y;
  11006. normals[ i + 5 ] = cb.z;
  11007. normals[ i + 6 ] = cb.x;
  11008. normals[ i + 7 ] = cb.y;
  11009. normals[ i + 8 ] = cb.z;
  11010. }
  11011. }
  11012. this.normalizeNormals();
  11013. attributes.normal.needsUpdate = true;
  11014. }
  11015. },
  11016. merge: function ( geometry, offset ) {
  11017. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  11018. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  11019. return;
  11020. }
  11021. if ( offset === undefined ) {
  11022. offset = 0;
  11023. console.warn(
  11024. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  11025. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  11026. );
  11027. }
  11028. var attributes = this.attributes;
  11029. for ( var key in attributes ) {
  11030. if ( geometry.attributes[ key ] === undefined ) continue;
  11031. var attribute1 = attributes[ key ];
  11032. var attributeArray1 = attribute1.array;
  11033. var attribute2 = geometry.attributes[ key ];
  11034. var attributeArray2 = attribute2.array;
  11035. var attributeSize = attribute2.itemSize;
  11036. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  11037. attributeArray1[ j ] = attributeArray2[ i ];
  11038. }
  11039. }
  11040. return this;
  11041. },
  11042. normalizeNormals: function () {
  11043. var vector = new Vector3();
  11044. return function normalizeNormals() {
  11045. var normals = this.attributes.normal;
  11046. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  11047. vector.x = normals.getX( i );
  11048. vector.y = normals.getY( i );
  11049. vector.z = normals.getZ( i );
  11050. vector.normalize();
  11051. normals.setXYZ( i, vector.x, vector.y, vector.z );
  11052. }
  11053. };
  11054. }(),
  11055. toNonIndexed: function () {
  11056. if ( this.index === null ) {
  11057. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  11058. return this;
  11059. }
  11060. var geometry2 = new BufferGeometry();
  11061. var indices = this.index.array;
  11062. var attributes = this.attributes;
  11063. for ( var name in attributes ) {
  11064. var attribute = attributes[ name ];
  11065. var array = attribute.array;
  11066. var itemSize = attribute.itemSize;
  11067. var array2 = new array.constructor( indices.length * itemSize );
  11068. var index = 0, index2 = 0;
  11069. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  11070. index = indices[ i ] * itemSize;
  11071. for ( var j = 0; j < itemSize; j ++ ) {
  11072. array2[ index2 ++ ] = array[ index ++ ];
  11073. }
  11074. }
  11075. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  11076. }
  11077. var groups = this.groups;
  11078. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  11079. var group = groups[ i ];
  11080. geometry2.addGroup( group.start, group.count, group.materialIndex );
  11081. }
  11082. return geometry2;
  11083. },
  11084. toJSON: function () {
  11085. var data = {
  11086. metadata: {
  11087. version: 4.5,
  11088. type: 'BufferGeometry',
  11089. generator: 'BufferGeometry.toJSON'
  11090. }
  11091. };
  11092. // standard BufferGeometry serialization
  11093. data.uuid = this.uuid;
  11094. data.type = this.type;
  11095. if ( this.name !== '' ) data.name = this.name;
  11096. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  11097. if ( this.parameters !== undefined ) {
  11098. var parameters = this.parameters;
  11099. for ( var key in parameters ) {
  11100. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  11101. }
  11102. return data;
  11103. }
  11104. data.data = { attributes: {} };
  11105. var index = this.index;
  11106. if ( index !== null ) {
  11107. var array = Array.prototype.slice.call( index.array );
  11108. data.data.index = {
  11109. type: index.array.constructor.name,
  11110. array: array
  11111. };
  11112. }
  11113. var attributes = this.attributes;
  11114. for ( var key in attributes ) {
  11115. var attribute = attributes[ key ];
  11116. var array = Array.prototype.slice.call( attribute.array );
  11117. data.data.attributes[ key ] = {
  11118. itemSize: attribute.itemSize,
  11119. type: attribute.array.constructor.name,
  11120. array: array,
  11121. normalized: attribute.normalized
  11122. };
  11123. }
  11124. var groups = this.groups;
  11125. if ( groups.length > 0 ) {
  11126. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  11127. }
  11128. var boundingSphere = this.boundingSphere;
  11129. if ( boundingSphere !== null ) {
  11130. data.data.boundingSphere = {
  11131. center: boundingSphere.center.toArray(),
  11132. radius: boundingSphere.radius
  11133. };
  11134. }
  11135. return data;
  11136. },
  11137. clone: function () {
  11138. /*
  11139. // Handle primitives
  11140. var parameters = this.parameters;
  11141. if ( parameters !== undefined ) {
  11142. var values = [];
  11143. for ( var key in parameters ) {
  11144. values.push( parameters[ key ] );
  11145. }
  11146. var geometry = Object.create( this.constructor.prototype );
  11147. this.constructor.apply( geometry, values );
  11148. return geometry;
  11149. }
  11150. return new this.constructor().copy( this );
  11151. */
  11152. return new BufferGeometry().copy( this );
  11153. },
  11154. copy: function ( source ) {
  11155. var name, i, l;
  11156. // reset
  11157. this.index = null;
  11158. this.attributes = {};
  11159. this.morphAttributes = {};
  11160. this.groups = [];
  11161. this.boundingBox = null;
  11162. this.boundingSphere = null;
  11163. // name
  11164. this.name = source.name;
  11165. // index
  11166. var index = source.index;
  11167. if ( index !== null ) {
  11168. this.setIndex( index.clone() );
  11169. }
  11170. // attributes
  11171. var attributes = source.attributes;
  11172. for ( name in attributes ) {
  11173. var attribute = attributes[ name ];
  11174. this.addAttribute( name, attribute.clone() );
  11175. }
  11176. // morph attributes
  11177. var morphAttributes = source.morphAttributes;
  11178. for ( name in morphAttributes ) {
  11179. var array = [];
  11180. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11181. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  11182. array.push( morphAttribute[ i ].clone() );
  11183. }
  11184. this.morphAttributes[ name ] = array;
  11185. }
  11186. // groups
  11187. var groups = source.groups;
  11188. for ( i = 0, l = groups.length; i < l; i ++ ) {
  11189. var group = groups[ i ];
  11190. this.addGroup( group.start, group.count, group.materialIndex );
  11191. }
  11192. // bounding box
  11193. var boundingBox = source.boundingBox;
  11194. if ( boundingBox !== null ) {
  11195. this.boundingBox = boundingBox.clone();
  11196. }
  11197. // bounding sphere
  11198. var boundingSphere = source.boundingSphere;
  11199. if ( boundingSphere !== null ) {
  11200. this.boundingSphere = boundingSphere.clone();
  11201. }
  11202. // draw range
  11203. this.drawRange.start = source.drawRange.start;
  11204. this.drawRange.count = source.drawRange.count;
  11205. // user data
  11206. this.userData = source.userData;
  11207. return this;
  11208. },
  11209. dispose: function () {
  11210. this.dispatchEvent( { type: 'dispose' } );
  11211. }
  11212. } );
  11213. /**
  11214. * @author mrdoob / http://mrdoob.com/
  11215. * @author Mugen87 / https://github.com/Mugen87
  11216. */
  11217. // BoxGeometry
  11218. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  11219. Geometry.call( this );
  11220. this.type = 'BoxGeometry';
  11221. this.parameters = {
  11222. width: width,
  11223. height: height,
  11224. depth: depth,
  11225. widthSegments: widthSegments,
  11226. heightSegments: heightSegments,
  11227. depthSegments: depthSegments
  11228. };
  11229. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  11230. this.mergeVertices();
  11231. }
  11232. BoxGeometry.prototype = Object.create( Geometry.prototype );
  11233. BoxGeometry.prototype.constructor = BoxGeometry;
  11234. // BoxBufferGeometry
  11235. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  11236. BufferGeometry.call( this );
  11237. this.type = 'BoxBufferGeometry';
  11238. this.parameters = {
  11239. width: width,
  11240. height: height,
  11241. depth: depth,
  11242. widthSegments: widthSegments,
  11243. heightSegments: heightSegments,
  11244. depthSegments: depthSegments
  11245. };
  11246. var scope = this;
  11247. width = width || 1;
  11248. height = height || 1;
  11249. depth = depth || 1;
  11250. // segments
  11251. widthSegments = Math.floor( widthSegments ) || 1;
  11252. heightSegments = Math.floor( heightSegments ) || 1;
  11253. depthSegments = Math.floor( depthSegments ) || 1;
  11254. // buffers
  11255. var indices = [];
  11256. var vertices = [];
  11257. var normals = [];
  11258. var uvs = [];
  11259. // helper variables
  11260. var numberOfVertices = 0;
  11261. var groupStart = 0;
  11262. // build each side of the box geometry
  11263. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  11264. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  11265. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  11266. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  11267. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  11268. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  11269. // build geometry
  11270. this.setIndex( indices );
  11271. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11272. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11273. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11274. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  11275. var segmentWidth = width / gridX;
  11276. var segmentHeight = height / gridY;
  11277. var widthHalf = width / 2;
  11278. var heightHalf = height / 2;
  11279. var depthHalf = depth / 2;
  11280. var gridX1 = gridX + 1;
  11281. var gridY1 = gridY + 1;
  11282. var vertexCounter = 0;
  11283. var groupCount = 0;
  11284. var ix, iy;
  11285. var vector = new Vector3();
  11286. // generate vertices, normals and uvs
  11287. for ( iy = 0; iy < gridY1; iy ++ ) {
  11288. var y = iy * segmentHeight - heightHalf;
  11289. for ( ix = 0; ix < gridX1; ix ++ ) {
  11290. var x = ix * segmentWidth - widthHalf;
  11291. // set values to correct vector component
  11292. vector[ u ] = x * udir;
  11293. vector[ v ] = y * vdir;
  11294. vector[ w ] = depthHalf;
  11295. // now apply vector to vertex buffer
  11296. vertices.push( vector.x, vector.y, vector.z );
  11297. // set values to correct vector component
  11298. vector[ u ] = 0;
  11299. vector[ v ] = 0;
  11300. vector[ w ] = depth > 0 ? 1 : - 1;
  11301. // now apply vector to normal buffer
  11302. normals.push( vector.x, vector.y, vector.z );
  11303. // uvs
  11304. uvs.push( ix / gridX );
  11305. uvs.push( 1 - ( iy / gridY ) );
  11306. // counters
  11307. vertexCounter += 1;
  11308. }
  11309. }
  11310. // indices
  11311. // 1. you need three indices to draw a single face
  11312. // 2. a single segment consists of two faces
  11313. // 3. so we need to generate six (2*3) indices per segment
  11314. for ( iy = 0; iy < gridY; iy ++ ) {
  11315. for ( ix = 0; ix < gridX; ix ++ ) {
  11316. var a = numberOfVertices + ix + gridX1 * iy;
  11317. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  11318. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  11319. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  11320. // faces
  11321. indices.push( a, b, d );
  11322. indices.push( b, c, d );
  11323. // increase counter
  11324. groupCount += 6;
  11325. }
  11326. }
  11327. // add a group to the geometry. this will ensure multi material support
  11328. scope.addGroup( groupStart, groupCount, materialIndex );
  11329. // calculate new start value for groups
  11330. groupStart += groupCount;
  11331. // update total number of vertices
  11332. numberOfVertices += vertexCounter;
  11333. }
  11334. }
  11335. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  11336. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  11337. /**
  11338. * @author mrdoob / http://mrdoob.com/
  11339. * @author Mugen87 / https://github.com/Mugen87
  11340. */
  11341. // PlaneGeometry
  11342. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  11343. Geometry.call( this );
  11344. this.type = 'PlaneGeometry';
  11345. this.parameters = {
  11346. width: width,
  11347. height: height,
  11348. widthSegments: widthSegments,
  11349. heightSegments: heightSegments
  11350. };
  11351. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  11352. this.mergeVertices();
  11353. }
  11354. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  11355. PlaneGeometry.prototype.constructor = PlaneGeometry;
  11356. // PlaneBufferGeometry
  11357. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  11358. BufferGeometry.call( this );
  11359. this.type = 'PlaneBufferGeometry';
  11360. this.parameters = {
  11361. width: width,
  11362. height: height,
  11363. widthSegments: widthSegments,
  11364. heightSegments: heightSegments
  11365. };
  11366. width = width || 1;
  11367. height = height || 1;
  11368. var width_half = width / 2;
  11369. var height_half = height / 2;
  11370. var gridX = Math.floor( widthSegments ) || 1;
  11371. var gridY = Math.floor( heightSegments ) || 1;
  11372. var gridX1 = gridX + 1;
  11373. var gridY1 = gridY + 1;
  11374. var segment_width = width / gridX;
  11375. var segment_height = height / gridY;
  11376. var ix, iy;
  11377. // buffers
  11378. var indices = [];
  11379. var vertices = [];
  11380. var normals = [];
  11381. var uvs = [];
  11382. // generate vertices, normals and uvs
  11383. for ( iy = 0; iy < gridY1; iy ++ ) {
  11384. var y = iy * segment_height - height_half;
  11385. for ( ix = 0; ix < gridX1; ix ++ ) {
  11386. var x = ix * segment_width - width_half;
  11387. vertices.push( x, - y, 0 );
  11388. normals.push( 0, 0, 1 );
  11389. uvs.push( ix / gridX );
  11390. uvs.push( 1 - ( iy / gridY ) );
  11391. }
  11392. }
  11393. // indices
  11394. for ( iy = 0; iy < gridY; iy ++ ) {
  11395. for ( ix = 0; ix < gridX; ix ++ ) {
  11396. var a = ix + gridX1 * iy;
  11397. var b = ix + gridX1 * ( iy + 1 );
  11398. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  11399. var d = ( ix + 1 ) + gridX1 * iy;
  11400. // faces
  11401. indices.push( a, b, d );
  11402. indices.push( b, c, d );
  11403. }
  11404. }
  11405. // build geometry
  11406. this.setIndex( indices );
  11407. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11408. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11409. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11410. }
  11411. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  11412. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  11413. /**
  11414. * @author mrdoob / http://mrdoob.com/
  11415. * @author alteredq / http://alteredqualia.com/
  11416. */
  11417. var materialId = 0;
  11418. function Material() {
  11419. Object.defineProperty( this, 'id', { value: materialId ++ } );
  11420. this.uuid = _Math.generateUUID();
  11421. this.name = '';
  11422. this.type = 'Material';
  11423. this.fog = true;
  11424. this.lights = true;
  11425. this.blending = NormalBlending;
  11426. this.side = FrontSide;
  11427. this.flatShading = false;
  11428. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  11429. this.opacity = 1;
  11430. this.transparent = false;
  11431. this.blendSrc = SrcAlphaFactor;
  11432. this.blendDst = OneMinusSrcAlphaFactor;
  11433. this.blendEquation = AddEquation;
  11434. this.blendSrcAlpha = null;
  11435. this.blendDstAlpha = null;
  11436. this.blendEquationAlpha = null;
  11437. this.depthFunc = LessEqualDepth;
  11438. this.depthTest = true;
  11439. this.depthWrite = true;
  11440. this.clippingPlanes = null;
  11441. this.clipIntersection = false;
  11442. this.clipShadows = false;
  11443. this.shadowSide = null;
  11444. this.colorWrite = true;
  11445. this.precision = null; // override the renderer's default precision for this material
  11446. this.polygonOffset = false;
  11447. this.polygonOffsetFactor = 0;
  11448. this.polygonOffsetUnits = 0;
  11449. this.dithering = false;
  11450. this.alphaTest = 0;
  11451. this.premultipliedAlpha = false;
  11452. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  11453. this.visible = true;
  11454. this.userData = {};
  11455. this.needsUpdate = true;
  11456. }
  11457. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  11458. constructor: Material,
  11459. isMaterial: true,
  11460. onBeforeCompile: function () {},
  11461. setValues: function ( values ) {
  11462. if ( values === undefined ) return;
  11463. for ( var key in values ) {
  11464. var newValue = values[ key ];
  11465. if ( newValue === undefined ) {
  11466. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  11467. continue;
  11468. }
  11469. // for backward compatability if shading is set in the constructor
  11470. if ( key === 'shading' ) {
  11471. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  11472. this.flatShading = ( newValue === FlatShading ) ? true : false;
  11473. continue;
  11474. }
  11475. var currentValue = this[ key ];
  11476. if ( currentValue === undefined ) {
  11477. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  11478. continue;
  11479. }
  11480. if ( currentValue && currentValue.isColor ) {
  11481. currentValue.set( newValue );
  11482. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  11483. currentValue.copy( newValue );
  11484. } else if ( key === 'overdraw' ) {
  11485. // ensure overdraw is backwards-compatible with legacy boolean type
  11486. this[ key ] = Number( newValue );
  11487. } else {
  11488. this[ key ] = newValue;
  11489. }
  11490. }
  11491. },
  11492. toJSON: function ( meta ) {
  11493. var isRoot = ( meta === undefined || typeof meta === 'string' );
  11494. if ( isRoot ) {
  11495. meta = {
  11496. textures: {},
  11497. images: {}
  11498. };
  11499. }
  11500. var data = {
  11501. metadata: {
  11502. version: 4.5,
  11503. type: 'Material',
  11504. generator: 'Material.toJSON'
  11505. }
  11506. };
  11507. // standard Material serialization
  11508. data.uuid = this.uuid;
  11509. data.type = this.type;
  11510. if ( this.name !== '' ) data.name = this.name;
  11511. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  11512. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  11513. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  11514. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  11515. if ( this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  11516. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  11517. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  11518. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  11519. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  11520. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  11521. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  11522. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  11523. if ( this.aoMap && this.aoMap.isTexture ) {
  11524. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  11525. data.aoMapIntensity = this.aoMapIntensity;
  11526. }
  11527. if ( this.bumpMap && this.bumpMap.isTexture ) {
  11528. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  11529. data.bumpScale = this.bumpScale;
  11530. }
  11531. if ( this.normalMap && this.normalMap.isTexture ) {
  11532. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  11533. data.normalMapType = this.normalMapType;
  11534. data.normalScale = this.normalScale.toArray();
  11535. }
  11536. if ( this.displacementMap && this.displacementMap.isTexture ) {
  11537. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  11538. data.displacementScale = this.displacementScale;
  11539. data.displacementBias = this.displacementBias;
  11540. }
  11541. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  11542. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  11543. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  11544. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  11545. if ( this.envMap && this.envMap.isTexture ) {
  11546. data.envMap = this.envMap.toJSON( meta ).uuid;
  11547. data.reflectivity = this.reflectivity; // Scale behind envMap
  11548. }
  11549. if ( this.gradientMap && this.gradientMap.isTexture ) {
  11550. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  11551. }
  11552. if ( this.size !== undefined ) data.size = this.size;
  11553. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  11554. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  11555. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  11556. if ( this.side !== FrontSide ) data.side = this.side;
  11557. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  11558. if ( this.opacity < 1 ) data.opacity = this.opacity;
  11559. if ( this.transparent === true ) data.transparent = this.transparent;
  11560. data.depthFunc = this.depthFunc;
  11561. data.depthTest = this.depthTest;
  11562. data.depthWrite = this.depthWrite;
  11563. // rotation (SpriteMaterial)
  11564. if ( this.rotation !== 0 ) data.rotation = this.rotation;
  11565. if ( this.linewidth !== 1 ) data.linewidth = this.linewidth;
  11566. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  11567. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  11568. if ( this.scale !== undefined ) data.scale = this.scale;
  11569. if ( this.dithering === true ) data.dithering = true;
  11570. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  11571. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  11572. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  11573. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  11574. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  11575. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  11576. if ( this.morphTargets === true ) data.morphTargets = true;
  11577. if ( this.skinning === true ) data.skinning = true;
  11578. if ( this.visible === false ) data.visible = false;
  11579. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  11580. // TODO: Copied from Object3D.toJSON
  11581. function extractFromCache( cache ) {
  11582. var values = [];
  11583. for ( var key in cache ) {
  11584. var data = cache[ key ];
  11585. delete data.metadata;
  11586. values.push( data );
  11587. }
  11588. return values;
  11589. }
  11590. if ( isRoot ) {
  11591. var textures = extractFromCache( meta.textures );
  11592. var images = extractFromCache( meta.images );
  11593. if ( textures.length > 0 ) data.textures = textures;
  11594. if ( images.length > 0 ) data.images = images;
  11595. }
  11596. return data;
  11597. },
  11598. clone: function () {
  11599. return new this.constructor().copy( this );
  11600. },
  11601. copy: function ( source ) {
  11602. this.name = source.name;
  11603. this.fog = source.fog;
  11604. this.lights = source.lights;
  11605. this.blending = source.blending;
  11606. this.side = source.side;
  11607. this.flatShading = source.flatShading;
  11608. this.vertexColors = source.vertexColors;
  11609. this.opacity = source.opacity;
  11610. this.transparent = source.transparent;
  11611. this.blendSrc = source.blendSrc;
  11612. this.blendDst = source.blendDst;
  11613. this.blendEquation = source.blendEquation;
  11614. this.blendSrcAlpha = source.blendSrcAlpha;
  11615. this.blendDstAlpha = source.blendDstAlpha;
  11616. this.blendEquationAlpha = source.blendEquationAlpha;
  11617. this.depthFunc = source.depthFunc;
  11618. this.depthTest = source.depthTest;
  11619. this.depthWrite = source.depthWrite;
  11620. this.colorWrite = source.colorWrite;
  11621. this.precision = source.precision;
  11622. this.polygonOffset = source.polygonOffset;
  11623. this.polygonOffsetFactor = source.polygonOffsetFactor;
  11624. this.polygonOffsetUnits = source.polygonOffsetUnits;
  11625. this.dithering = source.dithering;
  11626. this.alphaTest = source.alphaTest;
  11627. this.premultipliedAlpha = source.premultipliedAlpha;
  11628. this.overdraw = source.overdraw;
  11629. this.visible = source.visible;
  11630. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11631. this.clipShadows = source.clipShadows;
  11632. this.clipIntersection = source.clipIntersection;
  11633. var srcPlanes = source.clippingPlanes,
  11634. dstPlanes = null;
  11635. if ( srcPlanes !== null ) {
  11636. var n = srcPlanes.length;
  11637. dstPlanes = new Array( n );
  11638. for ( var i = 0; i !== n; ++ i )
  11639. dstPlanes[ i ] = srcPlanes[ i ].clone();
  11640. }
  11641. this.clippingPlanes = dstPlanes;
  11642. this.shadowSide = source.shadowSide;
  11643. return this;
  11644. },
  11645. dispose: function () {
  11646. this.dispatchEvent( { type: 'dispose' } );
  11647. }
  11648. } );
  11649. /**
  11650. * @author mrdoob / http://mrdoob.com/
  11651. * @author alteredq / http://alteredqualia.com/
  11652. *
  11653. * parameters = {
  11654. * color: <hex>,
  11655. * opacity: <float>,
  11656. * map: new THREE.Texture( <Image> ),
  11657. *
  11658. * lightMap: new THREE.Texture( <Image> ),
  11659. * lightMapIntensity: <float>
  11660. *
  11661. * aoMap: new THREE.Texture( <Image> ),
  11662. * aoMapIntensity: <float>
  11663. *
  11664. * specularMap: new THREE.Texture( <Image> ),
  11665. *
  11666. * alphaMap: new THREE.Texture( <Image> ),
  11667. *
  11668. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  11669. * combine: THREE.Multiply,
  11670. * reflectivity: <float>,
  11671. * refractionRatio: <float>,
  11672. *
  11673. * depthTest: <bool>,
  11674. * depthWrite: <bool>,
  11675. *
  11676. * wireframe: <boolean>,
  11677. * wireframeLinewidth: <float>,
  11678. *
  11679. * skinning: <bool>,
  11680. * morphTargets: <bool>
  11681. * }
  11682. */
  11683. function MeshBasicMaterial( parameters ) {
  11684. Material.call( this );
  11685. this.type = 'MeshBasicMaterial';
  11686. this.color = new Color( 0xffffff ); // emissive
  11687. this.map = null;
  11688. this.lightMap = null;
  11689. this.lightMapIntensity = 1.0;
  11690. this.aoMap = null;
  11691. this.aoMapIntensity = 1.0;
  11692. this.specularMap = null;
  11693. this.alphaMap = null;
  11694. this.envMap = null;
  11695. this.combine = MultiplyOperation;
  11696. this.reflectivity = 1;
  11697. this.refractionRatio = 0.98;
  11698. this.wireframe = false;
  11699. this.wireframeLinewidth = 1;
  11700. this.wireframeLinecap = 'round';
  11701. this.wireframeLinejoin = 'round';
  11702. this.skinning = false;
  11703. this.morphTargets = false;
  11704. this.lights = false;
  11705. this.setValues( parameters );
  11706. }
  11707. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  11708. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  11709. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  11710. MeshBasicMaterial.prototype.copy = function ( source ) {
  11711. Material.prototype.copy.call( this, source );
  11712. this.color.copy( source.color );
  11713. this.map = source.map;
  11714. this.lightMap = source.lightMap;
  11715. this.lightMapIntensity = source.lightMapIntensity;
  11716. this.aoMap = source.aoMap;
  11717. this.aoMapIntensity = source.aoMapIntensity;
  11718. this.specularMap = source.specularMap;
  11719. this.alphaMap = source.alphaMap;
  11720. this.envMap = source.envMap;
  11721. this.combine = source.combine;
  11722. this.reflectivity = source.reflectivity;
  11723. this.refractionRatio = source.refractionRatio;
  11724. this.wireframe = source.wireframe;
  11725. this.wireframeLinewidth = source.wireframeLinewidth;
  11726. this.wireframeLinecap = source.wireframeLinecap;
  11727. this.wireframeLinejoin = source.wireframeLinejoin;
  11728. this.skinning = source.skinning;
  11729. this.morphTargets = source.morphTargets;
  11730. return this;
  11731. };
  11732. /**
  11733. * @author alteredq / http://alteredqualia.com/
  11734. *
  11735. * parameters = {
  11736. * defines: { "label" : "value" },
  11737. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  11738. *
  11739. * fragmentShader: <string>,
  11740. * vertexShader: <string>,
  11741. *
  11742. * wireframe: <boolean>,
  11743. * wireframeLinewidth: <float>,
  11744. *
  11745. * lights: <bool>,
  11746. *
  11747. * skinning: <bool>,
  11748. * morphTargets: <bool>,
  11749. * morphNormals: <bool>
  11750. * }
  11751. */
  11752. function ShaderMaterial( parameters ) {
  11753. Material.call( this );
  11754. this.type = 'ShaderMaterial';
  11755. this.defines = {};
  11756. this.uniforms = {};
  11757. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  11758. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  11759. this.linewidth = 1;
  11760. this.wireframe = false;
  11761. this.wireframeLinewidth = 1;
  11762. this.fog = false; // set to use scene fog
  11763. this.lights = false; // set to use scene lights
  11764. this.clipping = false; // set to use user-defined clipping planes
  11765. this.skinning = false; // set to use skinning attribute streams
  11766. this.morphTargets = false; // set to use morph targets
  11767. this.morphNormals = false; // set to use morph normals
  11768. this.extensions = {
  11769. derivatives: false, // set to use derivatives
  11770. fragDepth: false, // set to use fragment depth values
  11771. drawBuffers: false, // set to use draw buffers
  11772. shaderTextureLOD: false // set to use shader texture LOD
  11773. };
  11774. // When rendered geometry doesn't include these attributes but the material does,
  11775. // use these default values in WebGL. This avoids errors when buffer data is missing.
  11776. this.defaultAttributeValues = {
  11777. 'color': [ 1, 1, 1 ],
  11778. 'uv': [ 0, 0 ],
  11779. 'uv2': [ 0, 0 ]
  11780. };
  11781. this.index0AttributeName = undefined;
  11782. this.uniformsNeedUpdate = false;
  11783. if ( parameters !== undefined ) {
  11784. if ( parameters.attributes !== undefined ) {
  11785. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  11786. }
  11787. this.setValues( parameters );
  11788. }
  11789. }
  11790. ShaderMaterial.prototype = Object.create( Material.prototype );
  11791. ShaderMaterial.prototype.constructor = ShaderMaterial;
  11792. ShaderMaterial.prototype.isShaderMaterial = true;
  11793. ShaderMaterial.prototype.copy = function ( source ) {
  11794. Material.prototype.copy.call( this, source );
  11795. this.fragmentShader = source.fragmentShader;
  11796. this.vertexShader = source.vertexShader;
  11797. this.uniforms = UniformsUtils.clone( source.uniforms );
  11798. this.defines = Object.assign( {}, source.defines );
  11799. this.wireframe = source.wireframe;
  11800. this.wireframeLinewidth = source.wireframeLinewidth;
  11801. this.lights = source.lights;
  11802. this.clipping = source.clipping;
  11803. this.skinning = source.skinning;
  11804. this.morphTargets = source.morphTargets;
  11805. this.morphNormals = source.morphNormals;
  11806. this.extensions = source.extensions;
  11807. return this;
  11808. };
  11809. ShaderMaterial.prototype.toJSON = function ( meta ) {
  11810. var data = Material.prototype.toJSON.call( this, meta );
  11811. data.uniforms = this.uniforms;
  11812. data.vertexShader = this.vertexShader;
  11813. data.fragmentShader = this.fragmentShader;
  11814. return data;
  11815. };
  11816. /**
  11817. * @author bhouston / http://clara.io
  11818. */
  11819. function Ray( origin, direction ) {
  11820. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  11821. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  11822. }
  11823. Object.assign( Ray.prototype, {
  11824. set: function ( origin, direction ) {
  11825. this.origin.copy( origin );
  11826. this.direction.copy( direction );
  11827. return this;
  11828. },
  11829. clone: function () {
  11830. return new this.constructor().copy( this );
  11831. },
  11832. copy: function ( ray ) {
  11833. this.origin.copy( ray.origin );
  11834. this.direction.copy( ray.direction );
  11835. return this;
  11836. },
  11837. at: function ( t, target ) {
  11838. if ( target === undefined ) {
  11839. console.warn( 'THREE.Ray: .at() target is now required' );
  11840. target = new Vector3();
  11841. }
  11842. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  11843. },
  11844. lookAt: function ( v ) {
  11845. this.direction.copy( v ).sub( this.origin ).normalize();
  11846. return this;
  11847. },
  11848. recast: function () {
  11849. var v1 = new Vector3();
  11850. return function recast( t ) {
  11851. this.origin.copy( this.at( t, v1 ) );
  11852. return this;
  11853. };
  11854. }(),
  11855. closestPointToPoint: function ( point, target ) {
  11856. if ( target === undefined ) {
  11857. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  11858. target = new Vector3();
  11859. }
  11860. target.subVectors( point, this.origin );
  11861. var directionDistance = target.dot( this.direction );
  11862. if ( directionDistance < 0 ) {
  11863. return target.copy( this.origin );
  11864. }
  11865. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  11866. },
  11867. distanceToPoint: function ( point ) {
  11868. return Math.sqrt( this.distanceSqToPoint( point ) );
  11869. },
  11870. distanceSqToPoint: function () {
  11871. var v1 = new Vector3();
  11872. return function distanceSqToPoint( point ) {
  11873. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  11874. // point behind the ray
  11875. if ( directionDistance < 0 ) {
  11876. return this.origin.distanceToSquared( point );
  11877. }
  11878. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  11879. return v1.distanceToSquared( point );
  11880. };
  11881. }(),
  11882. distanceSqToSegment: function () {
  11883. var segCenter = new Vector3();
  11884. var segDir = new Vector3();
  11885. var diff = new Vector3();
  11886. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  11887. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  11888. // It returns the min distance between the ray and the segment
  11889. // defined by v0 and v1
  11890. // It can also set two optional targets :
  11891. // - The closest point on the ray
  11892. // - The closest point on the segment
  11893. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  11894. segDir.copy( v1 ).sub( v0 ).normalize();
  11895. diff.copy( this.origin ).sub( segCenter );
  11896. var segExtent = v0.distanceTo( v1 ) * 0.5;
  11897. var a01 = - this.direction.dot( segDir );
  11898. var b0 = diff.dot( this.direction );
  11899. var b1 = - diff.dot( segDir );
  11900. var c = diff.lengthSq();
  11901. var det = Math.abs( 1 - a01 * a01 );
  11902. var s0, s1, sqrDist, extDet;
  11903. if ( det > 0 ) {
  11904. // The ray and segment are not parallel.
  11905. s0 = a01 * b1 - b0;
  11906. s1 = a01 * b0 - b1;
  11907. extDet = segExtent * det;
  11908. if ( s0 >= 0 ) {
  11909. if ( s1 >= - extDet ) {
  11910. if ( s1 <= extDet ) {
  11911. // region 0
  11912. // Minimum at interior points of ray and segment.
  11913. var invDet = 1 / det;
  11914. s0 *= invDet;
  11915. s1 *= invDet;
  11916. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  11917. } else {
  11918. // region 1
  11919. s1 = segExtent;
  11920. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  11921. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  11922. }
  11923. } else {
  11924. // region 5
  11925. s1 = - segExtent;
  11926. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  11927. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  11928. }
  11929. } else {
  11930. if ( s1 <= - extDet ) {
  11931. // region 4
  11932. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  11933. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  11934. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  11935. } else if ( s1 <= extDet ) {
  11936. // region 3
  11937. s0 = 0;
  11938. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  11939. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  11940. } else {
  11941. // region 2
  11942. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  11943. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  11944. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  11945. }
  11946. }
  11947. } else {
  11948. // Ray and segment are parallel.
  11949. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  11950. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  11951. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  11952. }
  11953. if ( optionalPointOnRay ) {
  11954. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  11955. }
  11956. if ( optionalPointOnSegment ) {
  11957. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  11958. }
  11959. return sqrDist;
  11960. };
  11961. }(),
  11962. intersectSphere: function () {
  11963. var v1 = new Vector3();
  11964. return function intersectSphere( sphere, target ) {
  11965. v1.subVectors( sphere.center, this.origin );
  11966. var tca = v1.dot( this.direction );
  11967. var d2 = v1.dot( v1 ) - tca * tca;
  11968. var radius2 = sphere.radius * sphere.radius;
  11969. if ( d2 > radius2 ) return null;
  11970. var thc = Math.sqrt( radius2 - d2 );
  11971. // t0 = first intersect point - entrance on front of sphere
  11972. var t0 = tca - thc;
  11973. // t1 = second intersect point - exit point on back of sphere
  11974. var t1 = tca + thc;
  11975. // test to see if both t0 and t1 are behind the ray - if so, return null
  11976. if ( t0 < 0 && t1 < 0 ) return null;
  11977. // test to see if t0 is behind the ray:
  11978. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  11979. // in order to always return an intersect point that is in front of the ray.
  11980. if ( t0 < 0 ) return this.at( t1, target );
  11981. // else t0 is in front of the ray, so return the first collision point scaled by t0
  11982. return this.at( t0, target );
  11983. };
  11984. }(),
  11985. intersectsSphere: function ( sphere ) {
  11986. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  11987. },
  11988. distanceToPlane: function ( plane ) {
  11989. var denominator = plane.normal.dot( this.direction );
  11990. if ( denominator === 0 ) {
  11991. // line is coplanar, return origin
  11992. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  11993. return 0;
  11994. }
  11995. // Null is preferable to undefined since undefined means.... it is undefined
  11996. return null;
  11997. }
  11998. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  11999. // Return if the ray never intersects the plane
  12000. return t >= 0 ? t : null;
  12001. },
  12002. intersectPlane: function ( plane, target ) {
  12003. var t = this.distanceToPlane( plane );
  12004. if ( t === null ) {
  12005. return null;
  12006. }
  12007. return this.at( t, target );
  12008. },
  12009. intersectsPlane: function ( plane ) {
  12010. // check if the ray lies on the plane first
  12011. var distToPoint = plane.distanceToPoint( this.origin );
  12012. if ( distToPoint === 0 ) {
  12013. return true;
  12014. }
  12015. var denominator = plane.normal.dot( this.direction );
  12016. if ( denominator * distToPoint < 0 ) {
  12017. return true;
  12018. }
  12019. // ray origin is behind the plane (and is pointing behind it)
  12020. return false;
  12021. },
  12022. intersectBox: function ( box, target ) {
  12023. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  12024. var invdirx = 1 / this.direction.x,
  12025. invdiry = 1 / this.direction.y,
  12026. invdirz = 1 / this.direction.z;
  12027. var origin = this.origin;
  12028. if ( invdirx >= 0 ) {
  12029. tmin = ( box.min.x - origin.x ) * invdirx;
  12030. tmax = ( box.max.x - origin.x ) * invdirx;
  12031. } else {
  12032. tmin = ( box.max.x - origin.x ) * invdirx;
  12033. tmax = ( box.min.x - origin.x ) * invdirx;
  12034. }
  12035. if ( invdiry >= 0 ) {
  12036. tymin = ( box.min.y - origin.y ) * invdiry;
  12037. tymax = ( box.max.y - origin.y ) * invdiry;
  12038. } else {
  12039. tymin = ( box.max.y - origin.y ) * invdiry;
  12040. tymax = ( box.min.y - origin.y ) * invdiry;
  12041. }
  12042. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  12043. // These lines also handle the case where tmin or tmax is NaN
  12044. // (result of 0 * Infinity). x !== x returns true if x is NaN
  12045. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  12046. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  12047. if ( invdirz >= 0 ) {
  12048. tzmin = ( box.min.z - origin.z ) * invdirz;
  12049. tzmax = ( box.max.z - origin.z ) * invdirz;
  12050. } else {
  12051. tzmin = ( box.max.z - origin.z ) * invdirz;
  12052. tzmax = ( box.min.z - origin.z ) * invdirz;
  12053. }
  12054. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  12055. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  12056. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  12057. //return point closest to the ray (positive side)
  12058. if ( tmax < 0 ) return null;
  12059. return this.at( tmin >= 0 ? tmin : tmax, target );
  12060. },
  12061. intersectsBox: ( function () {
  12062. var v = new Vector3();
  12063. return function intersectsBox( box ) {
  12064. return this.intersectBox( box, v ) !== null;
  12065. };
  12066. } )(),
  12067. intersectTriangle: function () {
  12068. // Compute the offset origin, edges, and normal.
  12069. var diff = new Vector3();
  12070. var edge1 = new Vector3();
  12071. var edge2 = new Vector3();
  12072. var normal = new Vector3();
  12073. return function intersectTriangle( a, b, c, backfaceCulling, target ) {
  12074. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  12075. edge1.subVectors( b, a );
  12076. edge2.subVectors( c, a );
  12077. normal.crossVectors( edge1, edge2 );
  12078. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  12079. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  12080. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  12081. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  12082. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  12083. var DdN = this.direction.dot( normal );
  12084. var sign;
  12085. if ( DdN > 0 ) {
  12086. if ( backfaceCulling ) return null;
  12087. sign = 1;
  12088. } else if ( DdN < 0 ) {
  12089. sign = - 1;
  12090. DdN = - DdN;
  12091. } else {
  12092. return null;
  12093. }
  12094. diff.subVectors( this.origin, a );
  12095. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  12096. // b1 < 0, no intersection
  12097. if ( DdQxE2 < 0 ) {
  12098. return null;
  12099. }
  12100. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  12101. // b2 < 0, no intersection
  12102. if ( DdE1xQ < 0 ) {
  12103. return null;
  12104. }
  12105. // b1+b2 > 1, no intersection
  12106. if ( DdQxE2 + DdE1xQ > DdN ) {
  12107. return null;
  12108. }
  12109. // Line intersects triangle, check if ray does.
  12110. var QdN = - sign * diff.dot( normal );
  12111. // t < 0, no intersection
  12112. if ( QdN < 0 ) {
  12113. return null;
  12114. }
  12115. // Ray intersects triangle.
  12116. return this.at( QdN / DdN, target );
  12117. };
  12118. }(),
  12119. applyMatrix4: function ( matrix4 ) {
  12120. this.origin.applyMatrix4( matrix4 );
  12121. this.direction.transformDirection( matrix4 );
  12122. return this;
  12123. },
  12124. equals: function ( ray ) {
  12125. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  12126. }
  12127. } );
  12128. /**
  12129. * @author bhouston / http://clara.io
  12130. * @author mrdoob / http://mrdoob.com/
  12131. */
  12132. function Triangle( a, b, c ) {
  12133. this.a = ( a !== undefined ) ? a : new Vector3();
  12134. this.b = ( b !== undefined ) ? b : new Vector3();
  12135. this.c = ( c !== undefined ) ? c : new Vector3();
  12136. }
  12137. Object.assign( Triangle, {
  12138. getNormal: function () {
  12139. var v0 = new Vector3();
  12140. return function getNormal( a, b, c, target ) {
  12141. if ( target === undefined ) {
  12142. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  12143. target = new Vector3();
  12144. }
  12145. target.subVectors( c, b );
  12146. v0.subVectors( a, b );
  12147. target.cross( v0 );
  12148. var targetLengthSq = target.lengthSq();
  12149. if ( targetLengthSq > 0 ) {
  12150. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  12151. }
  12152. return target.set( 0, 0, 0 );
  12153. };
  12154. }(),
  12155. // static/instance method to calculate barycentric coordinates
  12156. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  12157. getBarycoord: function () {
  12158. var v0 = new Vector3();
  12159. var v1 = new Vector3();
  12160. var v2 = new Vector3();
  12161. return function getBarycoord( point, a, b, c, target ) {
  12162. v0.subVectors( c, a );
  12163. v1.subVectors( b, a );
  12164. v2.subVectors( point, a );
  12165. var dot00 = v0.dot( v0 );
  12166. var dot01 = v0.dot( v1 );
  12167. var dot02 = v0.dot( v2 );
  12168. var dot11 = v1.dot( v1 );
  12169. var dot12 = v1.dot( v2 );
  12170. var denom = ( dot00 * dot11 - dot01 * dot01 );
  12171. if ( target === undefined ) {
  12172. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  12173. target = new Vector3();
  12174. }
  12175. // collinear or singular triangle
  12176. if ( denom === 0 ) {
  12177. // arbitrary location outside of triangle?
  12178. // not sure if this is the best idea, maybe should be returning undefined
  12179. return target.set( - 2, - 1, - 1 );
  12180. }
  12181. var invDenom = 1 / denom;
  12182. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  12183. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  12184. // barycentric coordinates must always sum to 1
  12185. return target.set( 1 - u - v, v, u );
  12186. };
  12187. }(),
  12188. containsPoint: function () {
  12189. var v1 = new Vector3();
  12190. return function containsPoint( point, a, b, c ) {
  12191. Triangle.getBarycoord( point, a, b, c, v1 );
  12192. return ( v1.x >= 0 ) && ( v1.y >= 0 ) && ( ( v1.x + v1.y ) <= 1 );
  12193. };
  12194. }()
  12195. } );
  12196. Object.assign( Triangle.prototype, {
  12197. set: function ( a, b, c ) {
  12198. this.a.copy( a );
  12199. this.b.copy( b );
  12200. this.c.copy( c );
  12201. return this;
  12202. },
  12203. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  12204. this.a.copy( points[ i0 ] );
  12205. this.b.copy( points[ i1 ] );
  12206. this.c.copy( points[ i2 ] );
  12207. return this;
  12208. },
  12209. clone: function () {
  12210. return new this.constructor().copy( this );
  12211. },
  12212. copy: function ( triangle ) {
  12213. this.a.copy( triangle.a );
  12214. this.b.copy( triangle.b );
  12215. this.c.copy( triangle.c );
  12216. return this;
  12217. },
  12218. getArea: function () {
  12219. var v0 = new Vector3();
  12220. var v1 = new Vector3();
  12221. return function getArea() {
  12222. v0.subVectors( this.c, this.b );
  12223. v1.subVectors( this.a, this.b );
  12224. return v0.cross( v1 ).length() * 0.5;
  12225. };
  12226. }(),
  12227. getMidpoint: function ( target ) {
  12228. if ( target === undefined ) {
  12229. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  12230. target = new Vector3();
  12231. }
  12232. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  12233. },
  12234. getNormal: function ( target ) {
  12235. return Triangle.getNormal( this.a, this.b, this.c, target );
  12236. },
  12237. getPlane: function ( target ) {
  12238. if ( target === undefined ) {
  12239. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  12240. target = new Vector3();
  12241. }
  12242. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  12243. },
  12244. getBarycoord: function ( point, target ) {
  12245. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  12246. },
  12247. containsPoint: function ( point ) {
  12248. return Triangle.containsPoint( point, this.a, this.b, this.c );
  12249. },
  12250. intersectsBox: function ( box ) {
  12251. return box.intersectsTriangle( this );
  12252. },
  12253. closestPointToPoint: function () {
  12254. var vab = new Vector3();
  12255. var vac = new Vector3();
  12256. var vbc = new Vector3();
  12257. var vap = new Vector3();
  12258. var vbp = new Vector3();
  12259. var vcp = new Vector3();
  12260. return function closestPointToPoint( p, target ) {
  12261. if ( target === undefined ) {
  12262. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  12263. target = new Vector3();
  12264. }
  12265. var a = this.a, b = this.b, c = this.c;
  12266. var v, w;
  12267. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  12268. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  12269. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  12270. // basically, we're distinguishing which of the voronoi regions of the triangle
  12271. // the point lies in with the minimum amount of redundant computation.
  12272. vab.subVectors( b, a );
  12273. vac.subVectors( c, a );
  12274. vap.subVectors( p, a );
  12275. var d1 = vab.dot( vap );
  12276. var d2 = vac.dot( vap );
  12277. if ( d1 <= 0 && d2 <= 0 ) {
  12278. // vertex region of A; barycentric coords (1, 0, 0)
  12279. return target.copy( a );
  12280. }
  12281. vbp.subVectors( p, b );
  12282. var d3 = vab.dot( vbp );
  12283. var d4 = vac.dot( vbp );
  12284. if ( d3 >= 0 && d4 <= d3 ) {
  12285. // vertex region of B; barycentric coords (0, 1, 0)
  12286. return target.copy( b );
  12287. }
  12288. var vc = d1 * d4 - d3 * d2;
  12289. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  12290. v = d1 / ( d1 - d3 );
  12291. // edge region of AB; barycentric coords (1-v, v, 0)
  12292. return target.copy( a ).addScaledVector( vab, v );
  12293. }
  12294. vcp.subVectors( p, c );
  12295. var d5 = vab.dot( vcp );
  12296. var d6 = vac.dot( vcp );
  12297. if ( d6 >= 0 && d5 <= d6 ) {
  12298. // vertex region of C; barycentric coords (0, 0, 1)
  12299. return target.copy( c );
  12300. }
  12301. var vb = d5 * d2 - d1 * d6;
  12302. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  12303. w = d2 / ( d2 - d6 );
  12304. // edge region of AC; barycentric coords (1-w, 0, w)
  12305. return target.copy( a ).addScaledVector( vac, w );
  12306. }
  12307. var va = d3 * d6 - d5 * d4;
  12308. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  12309. vbc.subVectors( c, b );
  12310. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  12311. // edge region of BC; barycentric coords (0, 1-w, w)
  12312. return target.copy( b ).addScaledVector( vbc, w ); // edge region of BC
  12313. }
  12314. // face region
  12315. var denom = 1 / ( va + vb + vc );
  12316. // u = va * denom
  12317. v = vb * denom;
  12318. w = vc * denom;
  12319. return target.copy( a ).addScaledVector( vab, v ).addScaledVector( vac, w );
  12320. };
  12321. }(),
  12322. equals: function ( triangle ) {
  12323. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  12324. }
  12325. } );
  12326. /**
  12327. * @author mrdoob / http://mrdoob.com/
  12328. * @author alteredq / http://alteredqualia.com/
  12329. * @author mikael emtinger / http://gomo.se/
  12330. * @author jonobr1 / http://jonobr1.com/
  12331. */
  12332. function Mesh( geometry, material ) {
  12333. Object3D.call( this );
  12334. this.type = 'Mesh';
  12335. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  12336. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  12337. this.drawMode = TrianglesDrawMode;
  12338. this.updateMorphTargets();
  12339. }
  12340. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  12341. constructor: Mesh,
  12342. isMesh: true,
  12343. setDrawMode: function ( value ) {
  12344. this.drawMode = value;
  12345. },
  12346. copy: function ( source ) {
  12347. Object3D.prototype.copy.call( this, source );
  12348. this.drawMode = source.drawMode;
  12349. if ( source.morphTargetInfluences !== undefined ) {
  12350. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  12351. }
  12352. if ( source.morphTargetDictionary !== undefined ) {
  12353. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  12354. }
  12355. return this;
  12356. },
  12357. updateMorphTargets: function () {
  12358. var geometry = this.geometry;
  12359. var m, ml, name;
  12360. if ( geometry.isBufferGeometry ) {
  12361. var morphAttributes = geometry.morphAttributes;
  12362. var keys = Object.keys( morphAttributes );
  12363. if ( keys.length > 0 ) {
  12364. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  12365. if ( morphAttribute !== undefined ) {
  12366. this.morphTargetInfluences = [];
  12367. this.morphTargetDictionary = {};
  12368. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  12369. name = morphAttribute[ m ].name || String( m );
  12370. this.morphTargetInfluences.push( 0 );
  12371. this.morphTargetDictionary[ name ] = m;
  12372. }
  12373. }
  12374. }
  12375. } else {
  12376. var morphTargets = geometry.morphTargets;
  12377. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  12378. this.morphTargetInfluences = [];
  12379. this.morphTargetDictionary = {};
  12380. for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  12381. name = morphTargets[ m ].name || String( m );
  12382. this.morphTargetInfluences.push( 0 );
  12383. this.morphTargetDictionary[ name ] = m;
  12384. }
  12385. }
  12386. }
  12387. },
  12388. raycast: ( function () {
  12389. var inverseMatrix = new Matrix4();
  12390. var ray = new Ray();
  12391. var sphere = new Sphere();
  12392. var vA = new Vector3();
  12393. var vB = new Vector3();
  12394. var vC = new Vector3();
  12395. var tempA = new Vector3();
  12396. var tempB = new Vector3();
  12397. var tempC = new Vector3();
  12398. var uvA = new Vector2();
  12399. var uvB = new Vector2();
  12400. var uvC = new Vector2();
  12401. var barycoord = new Vector3();
  12402. var intersectionPoint = new Vector3();
  12403. var intersectionPointWorld = new Vector3();
  12404. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  12405. Triangle.getBarycoord( point, p1, p2, p3, barycoord );
  12406. uv1.multiplyScalar( barycoord.x );
  12407. uv2.multiplyScalar( barycoord.y );
  12408. uv3.multiplyScalar( barycoord.z );
  12409. uv1.add( uv2 ).add( uv3 );
  12410. return uv1.clone();
  12411. }
  12412. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  12413. var intersect;
  12414. if ( material.side === BackSide ) {
  12415. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12416. } else {
  12417. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  12418. }
  12419. if ( intersect === null ) return null;
  12420. intersectionPointWorld.copy( point );
  12421. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12422. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  12423. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  12424. return {
  12425. distance: distance,
  12426. point: intersectionPointWorld.clone(),
  12427. object: object
  12428. };
  12429. }
  12430. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, uv, a, b, c ) {
  12431. vA.fromBufferAttribute( position, a );
  12432. vB.fromBufferAttribute( position, b );
  12433. vC.fromBufferAttribute( position, c );
  12434. var intersection = checkIntersection( object, material, raycaster, ray, vA, vB, vC, intersectionPoint );
  12435. if ( intersection ) {
  12436. if ( uv ) {
  12437. uvA.fromBufferAttribute( uv, a );
  12438. uvB.fromBufferAttribute( uv, b );
  12439. uvC.fromBufferAttribute( uv, c );
  12440. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  12441. }
  12442. var face = new Face3( a, b, c );
  12443. Triangle.getNormal( vA, vB, vC, face.normal );
  12444. intersection.face = face;
  12445. }
  12446. return intersection;
  12447. }
  12448. return function raycast( raycaster, intersects ) {
  12449. var geometry = this.geometry;
  12450. var material = this.material;
  12451. var matrixWorld = this.matrixWorld;
  12452. if ( material === undefined ) return;
  12453. // Checking boundingSphere distance to ray
  12454. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12455. sphere.copy( geometry.boundingSphere );
  12456. sphere.applyMatrix4( matrixWorld );
  12457. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  12458. //
  12459. inverseMatrix.getInverse( matrixWorld );
  12460. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12461. // Check boundingBox before continuing
  12462. if ( geometry.boundingBox !== null ) {
  12463. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  12464. }
  12465. var intersection;
  12466. if ( geometry.isBufferGeometry ) {
  12467. var a, b, c;
  12468. var index = geometry.index;
  12469. var position = geometry.attributes.position;
  12470. var uv = geometry.attributes.uv;
  12471. var groups = geometry.groups;
  12472. var drawRange = geometry.drawRange;
  12473. var i, j, il, jl;
  12474. var group, groupMaterial;
  12475. var start, end;
  12476. if ( index !== null ) {
  12477. // indexed buffer geometry
  12478. if ( Array.isArray( material ) ) {
  12479. for ( i = 0, il = groups.length; i < il; i ++ ) {
  12480. group = groups[ i ];
  12481. groupMaterial = material[ group.materialIndex ];
  12482. start = Math.max( group.start, drawRange.start );
  12483. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  12484. for ( j = start, jl = end; j < jl; j += 3 ) {
  12485. a = index.getX( j );
  12486. b = index.getX( j + 1 );
  12487. c = index.getX( j + 2 );
  12488. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, uv, a, b, c );
  12489. if ( intersection ) {
  12490. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  12491. intersects.push( intersection );
  12492. }
  12493. }
  12494. }
  12495. } else {
  12496. start = Math.max( 0, drawRange.start );
  12497. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  12498. for ( i = start, il = end; i < il; i += 3 ) {
  12499. a = index.getX( i );
  12500. b = index.getX( i + 1 );
  12501. c = index.getX( i + 2 );
  12502. intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, uv, a, b, c );
  12503. if ( intersection ) {
  12504. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  12505. intersects.push( intersection );
  12506. }
  12507. }
  12508. }
  12509. } else if ( position !== undefined ) {
  12510. // non-indexed buffer geometry
  12511. if ( Array.isArray( material ) ) {
  12512. for ( i = 0, il = groups.length; i < il; i ++ ) {
  12513. group = groups[ i ];
  12514. groupMaterial = material[ group.materialIndex ];
  12515. start = Math.max( group.start, drawRange.start );
  12516. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  12517. for ( j = start, jl = end; j < jl; j += 3 ) {
  12518. a = j;
  12519. b = j + 1;
  12520. c = j + 2;
  12521. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, uv, a, b, c );
  12522. if ( intersection ) {
  12523. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  12524. intersects.push( intersection );
  12525. }
  12526. }
  12527. }
  12528. } else {
  12529. start = Math.max( 0, drawRange.start );
  12530. end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  12531. for ( i = start, il = end; i < il; i += 3 ) {
  12532. a = i;
  12533. b = i + 1;
  12534. c = i + 2;
  12535. intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, uv, a, b, c );
  12536. if ( intersection ) {
  12537. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  12538. intersects.push( intersection );
  12539. }
  12540. }
  12541. }
  12542. }
  12543. } else if ( geometry.isGeometry ) {
  12544. var fvA, fvB, fvC;
  12545. var isMultiMaterial = Array.isArray( material );
  12546. var vertices = geometry.vertices;
  12547. var faces = geometry.faces;
  12548. var uvs;
  12549. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  12550. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  12551. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  12552. var face = faces[ f ];
  12553. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  12554. if ( faceMaterial === undefined ) continue;
  12555. fvA = vertices[ face.a ];
  12556. fvB = vertices[ face.b ];
  12557. fvC = vertices[ face.c ];
  12558. if ( faceMaterial.morphTargets === true ) {
  12559. var morphTargets = geometry.morphTargets;
  12560. var morphInfluences = this.morphTargetInfluences;
  12561. vA.set( 0, 0, 0 );
  12562. vB.set( 0, 0, 0 );
  12563. vC.set( 0, 0, 0 );
  12564. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  12565. var influence = morphInfluences[ t ];
  12566. if ( influence === 0 ) continue;
  12567. var targets = morphTargets[ t ].vertices;
  12568. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  12569. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  12570. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  12571. }
  12572. vA.add( fvA );
  12573. vB.add( fvB );
  12574. vC.add( fvC );
  12575. fvA = vA;
  12576. fvB = vB;
  12577. fvC = vC;
  12578. }
  12579. intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  12580. if ( intersection ) {
  12581. if ( uvs && uvs[ f ] ) {
  12582. var uvs_f = uvs[ f ];
  12583. uvA.copy( uvs_f[ 0 ] );
  12584. uvB.copy( uvs_f[ 1 ] );
  12585. uvC.copy( uvs_f[ 2 ] );
  12586. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  12587. }
  12588. intersection.face = face;
  12589. intersection.faceIndex = f;
  12590. intersects.push( intersection );
  12591. }
  12592. }
  12593. }
  12594. };
  12595. }() ),
  12596. clone: function () {
  12597. return new this.constructor( this.geometry, this.material ).copy( this );
  12598. }
  12599. } );
  12600. /**
  12601. * @author mrdoob / http://mrdoob.com/
  12602. */
  12603. function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {
  12604. var clearColor = new Color( 0x000000 );
  12605. var clearAlpha = 0;
  12606. var planeCamera, planeMesh;
  12607. var boxMesh;
  12608. function render( renderList, scene, camera, forceClear ) {
  12609. var background = scene.background;
  12610. if ( background === null ) {
  12611. setClear( clearColor, clearAlpha );
  12612. } else if ( background && background.isColor ) {
  12613. setClear( background, 1 );
  12614. forceClear = true;
  12615. }
  12616. if ( renderer.autoClear || forceClear ) {
  12617. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  12618. }
  12619. if ( background && background.isCubeTexture ) {
  12620. if ( boxMesh === undefined ) {
  12621. boxMesh = new Mesh(
  12622. new BoxBufferGeometry( 1, 1, 1 ),
  12623. new ShaderMaterial( {
  12624. uniforms: ShaderLib.cube.uniforms,
  12625. vertexShader: ShaderLib.cube.vertexShader,
  12626. fragmentShader: ShaderLib.cube.fragmentShader,
  12627. side: BackSide,
  12628. depthTest: true,
  12629. depthWrite: false,
  12630. fog: false
  12631. } )
  12632. );
  12633. boxMesh.geometry.removeAttribute( 'normal' );
  12634. boxMesh.geometry.removeAttribute( 'uv' );
  12635. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  12636. this.matrixWorld.copyPosition( camera.matrixWorld );
  12637. };
  12638. objects.update( boxMesh );
  12639. }
  12640. boxMesh.material.uniforms.tCube.value = background;
  12641. renderList.push( boxMesh, boxMesh.geometry, boxMesh.material, 0, null );
  12642. } else if ( background && background.isTexture ) {
  12643. if ( planeCamera === undefined ) {
  12644. planeCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  12645. planeMesh = new Mesh(
  12646. new PlaneBufferGeometry( 2, 2 ),
  12647. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  12648. );
  12649. objects.update( planeMesh );
  12650. }
  12651. planeMesh.material.map = background;
  12652. // TODO Push this to renderList
  12653. renderer.renderBufferDirect( planeCamera, null, planeMesh.geometry, planeMesh.material, planeMesh, null );
  12654. }
  12655. }
  12656. function setClear( color, alpha ) {
  12657. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  12658. }
  12659. return {
  12660. getClearColor: function () {
  12661. return clearColor;
  12662. },
  12663. setClearColor: function ( color, alpha ) {
  12664. clearColor.set( color );
  12665. clearAlpha = alpha !== undefined ? alpha : 1;
  12666. setClear( clearColor, clearAlpha );
  12667. },
  12668. getClearAlpha: function () {
  12669. return clearAlpha;
  12670. },
  12671. setClearAlpha: function ( alpha ) {
  12672. clearAlpha = alpha;
  12673. setClear( clearColor, clearAlpha );
  12674. },
  12675. render: render
  12676. };
  12677. }
  12678. /**
  12679. * @author mrdoob / http://mrdoob.com/
  12680. */
  12681. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  12682. var mode;
  12683. function setMode( value ) {
  12684. mode = value;
  12685. }
  12686. function render( start, count ) {
  12687. gl.drawArrays( mode, start, count );
  12688. info.update( count, mode );
  12689. }
  12690. function renderInstances( geometry, start, count ) {
  12691. var extension;
  12692. if ( capabilities.isWebGL2 ) {
  12693. extension = gl;
  12694. } else {
  12695. extension = extensions.get( 'ANGLE_instanced_arrays' );
  12696. if ( extension === null ) {
  12697. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12698. return;
  12699. }
  12700. }
  12701. extension[ capabilities.isWebGL2 ? 'drawArraysInstanced' : 'drawArraysInstancedANGLE' ]( mode, start, count, geometry.maxInstancedCount );
  12702. info.update( count, mode, geometry.maxInstancedCount );
  12703. }
  12704. //
  12705. this.setMode = setMode;
  12706. this.render = render;
  12707. this.renderInstances = renderInstances;
  12708. }
  12709. /**
  12710. * @author mrdoob / http://mrdoob.com/
  12711. */
  12712. function WebGLCapabilities( gl, extensions, parameters ) {
  12713. var maxAnisotropy;
  12714. function getMaxAnisotropy() {
  12715. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  12716. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  12717. if ( extension !== null ) {
  12718. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  12719. } else {
  12720. maxAnisotropy = 0;
  12721. }
  12722. return maxAnisotropy;
  12723. }
  12724. function getMaxPrecision( precision ) {
  12725. if ( precision === 'highp' ) {
  12726. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  12727. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  12728. return 'highp';
  12729. }
  12730. precision = 'mediump';
  12731. }
  12732. if ( precision === 'mediump' ) {
  12733. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  12734. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  12735. return 'mediump';
  12736. }
  12737. }
  12738. return 'lowp';
  12739. }
  12740. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  12741. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  12742. var maxPrecision = getMaxPrecision( precision );
  12743. if ( maxPrecision !== precision ) {
  12744. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  12745. precision = maxPrecision;
  12746. }
  12747. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  12748. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  12749. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12750. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  12751. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12752. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  12753. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  12754. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  12755. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  12756. var vertexTextures = maxVertexTextures > 0;
  12757. var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  12758. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  12759. return {
  12760. isWebGL2: isWebGL2,
  12761. getMaxAnisotropy: getMaxAnisotropy,
  12762. getMaxPrecision: getMaxPrecision,
  12763. precision: precision,
  12764. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12765. maxTextures: maxTextures,
  12766. maxVertexTextures: maxVertexTextures,
  12767. maxTextureSize: maxTextureSize,
  12768. maxCubemapSize: maxCubemapSize,
  12769. maxAttributes: maxAttributes,
  12770. maxVertexUniforms: maxVertexUniforms,
  12771. maxVaryings: maxVaryings,
  12772. maxFragmentUniforms: maxFragmentUniforms,
  12773. vertexTextures: vertexTextures,
  12774. floatFragmentTextures: floatFragmentTextures,
  12775. floatVertexTextures: floatVertexTextures
  12776. };
  12777. }
  12778. /**
  12779. * @author tschw
  12780. */
  12781. function WebGLClipping() {
  12782. var scope = this,
  12783. globalState = null,
  12784. numGlobalPlanes = 0,
  12785. localClippingEnabled = false,
  12786. renderingShadows = false,
  12787. plane = new Plane(),
  12788. viewNormalMatrix = new Matrix3(),
  12789. uniform = { value: null, needsUpdate: false };
  12790. this.uniform = uniform;
  12791. this.numPlanes = 0;
  12792. this.numIntersection = 0;
  12793. this.init = function ( planes, enableLocalClipping, camera ) {
  12794. var enabled =
  12795. planes.length !== 0 ||
  12796. enableLocalClipping ||
  12797. // enable state of previous frame - the clipping code has to
  12798. // run another frame in order to reset the state:
  12799. numGlobalPlanes !== 0 ||
  12800. localClippingEnabled;
  12801. localClippingEnabled = enableLocalClipping;
  12802. globalState = projectPlanes( planes, camera, 0 );
  12803. numGlobalPlanes = planes.length;
  12804. return enabled;
  12805. };
  12806. this.beginShadows = function () {
  12807. renderingShadows = true;
  12808. projectPlanes( null );
  12809. };
  12810. this.endShadows = function () {
  12811. renderingShadows = false;
  12812. resetGlobalState();
  12813. };
  12814. this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  12815. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  12816. // there's no local clipping
  12817. if ( renderingShadows ) {
  12818. // there's no global clipping
  12819. projectPlanes( null );
  12820. } else {
  12821. resetGlobalState();
  12822. }
  12823. } else {
  12824. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  12825. lGlobal = nGlobal * 4,
  12826. dstArray = cache.clippingState || null;
  12827. uniform.value = dstArray; // ensure unique state
  12828. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  12829. for ( var i = 0; i !== lGlobal; ++ i ) {
  12830. dstArray[ i ] = globalState[ i ];
  12831. }
  12832. cache.clippingState = dstArray;
  12833. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  12834. this.numPlanes += nGlobal;
  12835. }
  12836. };
  12837. function resetGlobalState() {
  12838. if ( uniform.value !== globalState ) {
  12839. uniform.value = globalState;
  12840. uniform.needsUpdate = numGlobalPlanes > 0;
  12841. }
  12842. scope.numPlanes = numGlobalPlanes;
  12843. scope.numIntersection = 0;
  12844. }
  12845. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  12846. var nPlanes = planes !== null ? planes.length : 0,
  12847. dstArray = null;
  12848. if ( nPlanes !== 0 ) {
  12849. dstArray = uniform.value;
  12850. if ( skipTransform !== true || dstArray === null ) {
  12851. var flatSize = dstOffset + nPlanes * 4,
  12852. viewMatrix = camera.matrixWorldInverse;
  12853. viewNormalMatrix.getNormalMatrix( viewMatrix );
  12854. if ( dstArray === null || dstArray.length < flatSize ) {
  12855. dstArray = new Float32Array( flatSize );
  12856. }
  12857. for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  12858. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  12859. plane.normal.toArray( dstArray, i4 );
  12860. dstArray[ i4 + 3 ] = plane.constant;
  12861. }
  12862. }
  12863. uniform.value = dstArray;
  12864. uniform.needsUpdate = true;
  12865. }
  12866. scope.numPlanes = nPlanes;
  12867. return dstArray;
  12868. }
  12869. }
  12870. /**
  12871. * @author mrdoob / http://mrdoob.com/
  12872. */
  12873. function WebGLExtensions( gl ) {
  12874. var extensions = {};
  12875. return {
  12876. get: function ( name ) {
  12877. if ( extensions[ name ] !== undefined ) {
  12878. return extensions[ name ];
  12879. }
  12880. var extension;
  12881. switch ( name ) {
  12882. case 'WEBGL_depth_texture':
  12883. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  12884. break;
  12885. case 'EXT_texture_filter_anisotropic':
  12886. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12887. break;
  12888. case 'WEBGL_compressed_texture_s3tc':
  12889. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  12890. break;
  12891. case 'WEBGL_compressed_texture_pvrtc':
  12892. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  12893. break;
  12894. default:
  12895. extension = gl.getExtension( name );
  12896. }
  12897. if ( extension === null ) {
  12898. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  12899. }
  12900. extensions[ name ] = extension;
  12901. return extension;
  12902. }
  12903. };
  12904. }
  12905. /**
  12906. * @author mrdoob / http://mrdoob.com/
  12907. */
  12908. function WebGLGeometries( gl, attributes, info ) {
  12909. var geometries = {};
  12910. var wireframeAttributes = {};
  12911. function onGeometryDispose( event ) {
  12912. var geometry = event.target;
  12913. var buffergeometry = geometries[ geometry.id ];
  12914. if ( buffergeometry.index !== null ) {
  12915. attributes.remove( buffergeometry.index );
  12916. }
  12917. for ( var name in buffergeometry.attributes ) {
  12918. attributes.remove( buffergeometry.attributes[ name ] );
  12919. }
  12920. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12921. delete geometries[ geometry.id ];
  12922. var attribute = wireframeAttributes[ buffergeometry.id ];
  12923. if ( attribute ) {
  12924. attributes.remove( attribute );
  12925. delete wireframeAttributes[ buffergeometry.id ];
  12926. }
  12927. //
  12928. info.memory.geometries --;
  12929. }
  12930. function get( object, geometry ) {
  12931. var buffergeometry = geometries[ geometry.id ];
  12932. if ( buffergeometry ) return buffergeometry;
  12933. geometry.addEventListener( 'dispose', onGeometryDispose );
  12934. if ( geometry.isBufferGeometry ) {
  12935. buffergeometry = geometry;
  12936. } else if ( geometry.isGeometry ) {
  12937. if ( geometry._bufferGeometry === undefined ) {
  12938. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  12939. }
  12940. buffergeometry = geometry._bufferGeometry;
  12941. }
  12942. geometries[ geometry.id ] = buffergeometry;
  12943. info.memory.geometries ++;
  12944. return buffergeometry;
  12945. }
  12946. function update( geometry ) {
  12947. var index = geometry.index;
  12948. var geometryAttributes = geometry.attributes;
  12949. if ( index !== null ) {
  12950. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  12951. }
  12952. for ( var name in geometryAttributes ) {
  12953. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  12954. }
  12955. // morph targets
  12956. var morphAttributes = geometry.morphAttributes;
  12957. for ( var name in morphAttributes ) {
  12958. var array = morphAttributes[ name ];
  12959. for ( var i = 0, l = array.length; i < l; i ++ ) {
  12960. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  12961. }
  12962. }
  12963. }
  12964. function getWireframeAttribute( geometry ) {
  12965. var attribute = wireframeAttributes[ geometry.id ];
  12966. if ( attribute ) return attribute;
  12967. var indices = [];
  12968. var geometryIndex = geometry.index;
  12969. var geometryAttributes = geometry.attributes;
  12970. // console.time( 'wireframe' );
  12971. if ( geometryIndex !== null ) {
  12972. var array = geometryIndex.array;
  12973. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  12974. var a = array[ i + 0 ];
  12975. var b = array[ i + 1 ];
  12976. var c = array[ i + 2 ];
  12977. indices.push( a, b, b, c, c, a );
  12978. }
  12979. } else {
  12980. var array = geometryAttributes.position.array;
  12981. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  12982. var a = i + 0;
  12983. var b = i + 1;
  12984. var c = i + 2;
  12985. indices.push( a, b, b, c, c, a );
  12986. }
  12987. }
  12988. // console.timeEnd( 'wireframe' );
  12989. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  12990. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  12991. wireframeAttributes[ geometry.id ] = attribute;
  12992. return attribute;
  12993. }
  12994. return {
  12995. get: get,
  12996. update: update,
  12997. getWireframeAttribute: getWireframeAttribute
  12998. };
  12999. }
  13000. /**
  13001. * @author mrdoob / http://mrdoob.com/
  13002. */
  13003. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  13004. var mode;
  13005. function setMode( value ) {
  13006. mode = value;
  13007. }
  13008. var type, bytesPerElement;
  13009. function setIndex( value ) {
  13010. type = value.type;
  13011. bytesPerElement = value.bytesPerElement;
  13012. }
  13013. function render( start, count ) {
  13014. gl.drawElements( mode, count, type, start * bytesPerElement );
  13015. info.update( count, mode );
  13016. }
  13017. function renderInstances( geometry, start, count ) {
  13018. var extension;
  13019. if ( capabilities.isWebGL2 ) {
  13020. extension = gl;
  13021. } else {
  13022. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  13023. if ( extension === null ) {
  13024. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  13025. return;
  13026. }
  13027. }
  13028. extension[ capabilities.isWebGL2 ? 'drawElementsInstanced' : 'drawElementsInstancedANGLE' ]( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  13029. info.update( count, mode, geometry.maxInstancedCount );
  13030. }
  13031. //
  13032. this.setMode = setMode;
  13033. this.setIndex = setIndex;
  13034. this.render = render;
  13035. this.renderInstances = renderInstances;
  13036. }
  13037. /**
  13038. * @author Mugen87 / https://github.com/Mugen87
  13039. */
  13040. function WebGLInfo( gl ) {
  13041. var memory = {
  13042. geometries: 0,
  13043. textures: 0
  13044. };
  13045. var render = {
  13046. frame: 0,
  13047. calls: 0,
  13048. triangles: 0,
  13049. points: 0,
  13050. lines: 0
  13051. };
  13052. function update( count, mode, instanceCount ) {
  13053. instanceCount = instanceCount || 1;
  13054. render.calls ++;
  13055. switch ( mode ) {
  13056. case gl.TRIANGLES:
  13057. render.triangles += instanceCount * ( count / 3 );
  13058. break;
  13059. case gl.TRIANGLE_STRIP:
  13060. case gl.TRIANGLE_FAN:
  13061. render.triangles += instanceCount * ( count - 2 );
  13062. break;
  13063. case gl.LINES:
  13064. render.lines += instanceCount * ( count / 2 );
  13065. break;
  13066. case gl.LINE_STRIP:
  13067. render.lines += instanceCount * ( count - 1 );
  13068. break;
  13069. case gl.LINE_LOOP:
  13070. render.lines += instanceCount * count;
  13071. break;
  13072. case gl.POINTS:
  13073. render.points += instanceCount * count;
  13074. break;
  13075. default:
  13076. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  13077. break;
  13078. }
  13079. }
  13080. function reset() {
  13081. render.frame ++;
  13082. render.calls = 0;
  13083. render.triangles = 0;
  13084. render.points = 0;
  13085. render.lines = 0;
  13086. }
  13087. return {
  13088. memory: memory,
  13089. render: render,
  13090. programs: null,
  13091. autoReset: true,
  13092. reset: reset,
  13093. update: update
  13094. };
  13095. }
  13096. /**
  13097. * @author mrdoob / http://mrdoob.com/
  13098. */
  13099. function absNumericalSort( a, b ) {
  13100. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  13101. }
  13102. function WebGLMorphtargets( gl ) {
  13103. var influencesList = {};
  13104. var morphInfluences = new Float32Array( 8 );
  13105. function update( object, geometry, material, program ) {
  13106. var objectInfluences = object.morphTargetInfluences;
  13107. var length = objectInfluences.length;
  13108. var influences = influencesList[ geometry.id ];
  13109. if ( influences === undefined ) {
  13110. // initialise list
  13111. influences = [];
  13112. for ( var i = 0; i < length; i ++ ) {
  13113. influences[ i ] = [ i, 0 ];
  13114. }
  13115. influencesList[ geometry.id ] = influences;
  13116. }
  13117. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  13118. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  13119. // Remove current morphAttributes
  13120. for ( var i = 0; i < length; i ++ ) {
  13121. var influence = influences[ i ];
  13122. if ( influence[ 1 ] !== 0 ) {
  13123. if ( morphTargets ) geometry.removeAttribute( 'morphTarget' + i );
  13124. if ( morphNormals ) geometry.removeAttribute( 'morphNormal' + i );
  13125. }
  13126. }
  13127. // Collect influences
  13128. for ( var i = 0; i < length; i ++ ) {
  13129. var influence = influences[ i ];
  13130. influence[ 0 ] = i;
  13131. influence[ 1 ] = objectInfluences[ i ];
  13132. }
  13133. influences.sort( absNumericalSort );
  13134. // Add morphAttributes
  13135. for ( var i = 0; i < 8; i ++ ) {
  13136. var influence = influences[ i ];
  13137. if ( influence ) {
  13138. var index = influence[ 0 ];
  13139. var value = influence[ 1 ];
  13140. if ( value ) {
  13141. if ( morphTargets ) geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] );
  13142. if ( morphNormals ) geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] );
  13143. morphInfluences[ i ] = value;
  13144. continue;
  13145. }
  13146. }
  13147. morphInfluences[ i ] = 0;
  13148. }
  13149. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  13150. }
  13151. return {
  13152. update: update
  13153. };
  13154. }
  13155. /**
  13156. * @author mrdoob / http://mrdoob.com/
  13157. */
  13158. function WebGLObjects( geometries, info ) {
  13159. var updateList = {};
  13160. function update( object ) {
  13161. var frame = info.render.frame;
  13162. var geometry = object.geometry;
  13163. var buffergeometry = geometries.get( object, geometry );
  13164. // Update once per frame
  13165. if ( updateList[ buffergeometry.id ] !== frame ) {
  13166. if ( geometry.isGeometry ) {
  13167. buffergeometry.updateFromObject( object );
  13168. }
  13169. geometries.update( buffergeometry );
  13170. updateList[ buffergeometry.id ] = frame;
  13171. }
  13172. return buffergeometry;
  13173. }
  13174. function dispose() {
  13175. updateList = {};
  13176. }
  13177. return {
  13178. update: update,
  13179. dispose: dispose
  13180. };
  13181. }
  13182. /**
  13183. * @author mrdoob / http://mrdoob.com/
  13184. */
  13185. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  13186. images = images !== undefined ? images : [];
  13187. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  13188. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13189. this.flipY = false;
  13190. }
  13191. CubeTexture.prototype = Object.create( Texture.prototype );
  13192. CubeTexture.prototype.constructor = CubeTexture;
  13193. CubeTexture.prototype.isCubeTexture = true;
  13194. Object.defineProperty( CubeTexture.prototype, 'images', {
  13195. get: function () {
  13196. return this.image;
  13197. },
  13198. set: function ( value ) {
  13199. this.image = value;
  13200. }
  13201. } );
  13202. /**
  13203. * @author tschw
  13204. * @author Mugen87 / https://github.com/Mugen87
  13205. * @author mrdoob / http://mrdoob.com/
  13206. *
  13207. * Uniforms of a program.
  13208. * Those form a tree structure with a special top-level container for the root,
  13209. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  13210. *
  13211. *
  13212. * Properties of inner nodes including the top-level container:
  13213. *
  13214. * .seq - array of nested uniforms
  13215. * .map - nested uniforms by name
  13216. *
  13217. *
  13218. * Methods of all nodes except the top-level container:
  13219. *
  13220. * .setValue( gl, value, [renderer] )
  13221. *
  13222. * uploads a uniform value(s)
  13223. * the 'renderer' parameter is needed for sampler uniforms
  13224. *
  13225. *
  13226. * Static methods of the top-level container (renderer factorizations):
  13227. *
  13228. * .upload( gl, seq, values, renderer )
  13229. *
  13230. * sets uniforms in 'seq' to 'values[id].value'
  13231. *
  13232. * .seqWithValue( seq, values ) : filteredSeq
  13233. *
  13234. * filters 'seq' entries with corresponding entry in values
  13235. *
  13236. *
  13237. * Methods of the top-level container (renderer factorizations):
  13238. *
  13239. * .setValue( gl, name, value )
  13240. *
  13241. * sets uniform with name 'name' to 'value'
  13242. *
  13243. * .set( gl, obj, prop )
  13244. *
  13245. * sets uniform from object and property with same name than uniform
  13246. *
  13247. * .setOptional( gl, obj, prop )
  13248. *
  13249. * like .set for an optional property of the object
  13250. *
  13251. */
  13252. var emptyTexture = new Texture();
  13253. var emptyCubeTexture = new CubeTexture();
  13254. // --- Base for inner nodes (including the root) ---
  13255. function UniformContainer() {
  13256. this.seq = [];
  13257. this.map = {};
  13258. }
  13259. // --- Utilities ---
  13260. // Array Caches (provide typed arrays for temporary by size)
  13261. var arrayCacheF32 = [];
  13262. var arrayCacheI32 = [];
  13263. // Float32Array caches used for uploading Matrix uniforms
  13264. var mat4array = new Float32Array( 16 );
  13265. var mat3array = new Float32Array( 9 );
  13266. var mat2array = new Float32Array( 4 );
  13267. // Flattening for arrays of vectors and matrices
  13268. function flatten( array, nBlocks, blockSize ) {
  13269. var firstElem = array[ 0 ];
  13270. if ( firstElem <= 0 || firstElem > 0 ) return array;
  13271. // unoptimized: ! isNaN( firstElem )
  13272. // see http://jacksondunstan.com/articles/983
  13273. var n = nBlocks * blockSize,
  13274. r = arrayCacheF32[ n ];
  13275. if ( r === undefined ) {
  13276. r = new Float32Array( n );
  13277. arrayCacheF32[ n ] = r;
  13278. }
  13279. if ( nBlocks !== 0 ) {
  13280. firstElem.toArray( r, 0 );
  13281. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  13282. offset += blockSize;
  13283. array[ i ].toArray( r, offset );
  13284. }
  13285. }
  13286. return r;
  13287. }
  13288. function arraysEqual( a, b ) {
  13289. if ( a.length !== b.length ) return false;
  13290. for ( var i = 0, l = a.length; i < l; i ++ ) {
  13291. if ( a[ i ] !== b[ i ] ) return false;
  13292. }
  13293. return true;
  13294. }
  13295. function copyArray( a, b ) {
  13296. for ( var i = 0, l = b.length; i < l; i ++ ) {
  13297. a[ i ] = b[ i ];
  13298. }
  13299. }
  13300. // Texture unit allocation
  13301. function allocTexUnits( renderer, n ) {
  13302. var r = arrayCacheI32[ n ];
  13303. if ( r === undefined ) {
  13304. r = new Int32Array( n );
  13305. arrayCacheI32[ n ] = r;
  13306. }
  13307. for ( var i = 0; i !== n; ++ i )
  13308. r[ i ] = renderer.allocTextureUnit();
  13309. return r;
  13310. }
  13311. // --- Setters ---
  13312. // Note: Defining these methods externally, because they come in a bunch
  13313. // and this way their names minify.
  13314. // Single scalar
  13315. function setValue1f( gl, v ) {
  13316. var cache = this.cache;
  13317. if ( cache[ 0 ] === v ) return;
  13318. gl.uniform1f( this.addr, v );
  13319. cache[ 0 ] = v;
  13320. }
  13321. function setValue1i( gl, v ) {
  13322. var cache = this.cache;
  13323. if ( cache[ 0 ] === v ) return;
  13324. gl.uniform1i( this.addr, v );
  13325. cache[ 0 ] = v;
  13326. }
  13327. // Single float vector (from flat array or THREE.VectorN)
  13328. function setValue2fv( gl, v ) {
  13329. var cache = this.cache;
  13330. if ( v.x !== undefined ) {
  13331. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  13332. gl.uniform2f( this.addr, v.x, v.y );
  13333. cache[ 0 ] = v.x;
  13334. cache[ 1 ] = v.y;
  13335. }
  13336. } else {
  13337. if ( arraysEqual( cache, v ) ) return;
  13338. gl.uniform2fv( this.addr, v );
  13339. copyArray( cache, v );
  13340. }
  13341. }
  13342. function setValue3fv( gl, v ) {
  13343. var cache = this.cache;
  13344. if ( v.x !== undefined ) {
  13345. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  13346. gl.uniform3f( this.addr, v.x, v.y, v.z );
  13347. cache[ 0 ] = v.x;
  13348. cache[ 1 ] = v.y;
  13349. cache[ 2 ] = v.z;
  13350. }
  13351. } else if ( v.r !== undefined ) {
  13352. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  13353. gl.uniform3f( this.addr, v.r, v.g, v.b );
  13354. cache[ 0 ] = v.r;
  13355. cache[ 1 ] = v.g;
  13356. cache[ 2 ] = v.b;
  13357. }
  13358. } else {
  13359. if ( arraysEqual( cache, v ) ) return;
  13360. gl.uniform3fv( this.addr, v );
  13361. copyArray( cache, v );
  13362. }
  13363. }
  13364. function setValue4fv( gl, v ) {
  13365. var cache = this.cache;
  13366. if ( v.x !== undefined ) {
  13367. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  13368. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  13369. cache[ 0 ] = v.x;
  13370. cache[ 1 ] = v.y;
  13371. cache[ 2 ] = v.z;
  13372. cache[ 3 ] = v.w;
  13373. }
  13374. } else {
  13375. if ( arraysEqual( cache, v ) ) return;
  13376. gl.uniform4fv( this.addr, v );
  13377. copyArray( cache, v );
  13378. }
  13379. }
  13380. // Single matrix (from flat array or MatrixN)
  13381. function setValue2fm( gl, v ) {
  13382. var cache = this.cache;
  13383. var elements = v.elements;
  13384. if ( elements === undefined ) {
  13385. if ( arraysEqual( cache, v ) ) return;
  13386. gl.uniformMatrix2fv( this.addr, false, v );
  13387. copyArray( cache, v );
  13388. } else {
  13389. if ( arraysEqual( cache, elements ) ) return;
  13390. mat2array.set( elements );
  13391. gl.uniformMatrix2fv( this.addr, false, mat2array );
  13392. copyArray( cache, elements );
  13393. }
  13394. }
  13395. function setValue3fm( gl, v ) {
  13396. var cache = this.cache;
  13397. var elements = v.elements;
  13398. if ( elements === undefined ) {
  13399. if ( arraysEqual( cache, v ) ) return;
  13400. gl.uniformMatrix3fv( this.addr, false, v );
  13401. copyArray( cache, v );
  13402. } else {
  13403. if ( arraysEqual( cache, elements ) ) return;
  13404. mat3array.set( elements );
  13405. gl.uniformMatrix3fv( this.addr, false, mat3array );
  13406. copyArray( cache, elements );
  13407. }
  13408. }
  13409. function setValue4fm( gl, v ) {
  13410. var cache = this.cache;
  13411. var elements = v.elements;
  13412. if ( elements === undefined ) {
  13413. if ( arraysEqual( cache, v ) ) return;
  13414. gl.uniformMatrix4fv( this.addr, false, v );
  13415. copyArray( cache, v );
  13416. } else {
  13417. if ( arraysEqual( cache, elements ) ) return;
  13418. mat4array.set( elements );
  13419. gl.uniformMatrix4fv( this.addr, false, mat4array );
  13420. copyArray( cache, elements );
  13421. }
  13422. }
  13423. // Single texture (2D / Cube)
  13424. function setValueT1( gl, v, renderer ) {
  13425. var cache = this.cache;
  13426. var unit = renderer.allocTextureUnit();
  13427. if ( cache[ 0 ] !== unit ) {
  13428. gl.uniform1i( this.addr, unit );
  13429. cache[ 0 ] = unit;
  13430. }
  13431. renderer.setTexture2D( v || emptyTexture, unit );
  13432. }
  13433. function setValueT6( gl, v, renderer ) {
  13434. var cache = this.cache;
  13435. var unit = renderer.allocTextureUnit();
  13436. if ( cache[ 0 ] !== unit ) {
  13437. gl.uniform1i( this.addr, unit );
  13438. cache[ 0 ] = unit;
  13439. }
  13440. renderer.setTextureCube( v || emptyCubeTexture, unit );
  13441. }
  13442. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  13443. function setValue2iv( gl, v ) {
  13444. var cache = this.cache;
  13445. if ( arraysEqual( cache, v ) ) return;
  13446. gl.uniform2iv( this.addr, v );
  13447. copyArray( cache, v );
  13448. }
  13449. function setValue3iv( gl, v ) {
  13450. var cache = this.cache;
  13451. if ( arraysEqual( cache, v ) ) return;
  13452. gl.uniform3iv( this.addr, v );
  13453. copyArray( cache, v );
  13454. }
  13455. function setValue4iv( gl, v ) {
  13456. var cache = this.cache;
  13457. if ( arraysEqual( cache, v ) ) return;
  13458. gl.uniform4iv( this.addr, v );
  13459. copyArray( cache, v );
  13460. }
  13461. // Helper to pick the right setter for the singular case
  13462. function getSingularSetter( type ) {
  13463. switch ( type ) {
  13464. case 0x1406: return setValue1f; // FLOAT
  13465. case 0x8b50: return setValue2fv; // _VEC2
  13466. case 0x8b51: return setValue3fv; // _VEC3
  13467. case 0x8b52: return setValue4fv; // _VEC4
  13468. case 0x8b5a: return setValue2fm; // _MAT2
  13469. case 0x8b5b: return setValue3fm; // _MAT3
  13470. case 0x8b5c: return setValue4fm; // _MAT4
  13471. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  13472. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  13473. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  13474. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  13475. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  13476. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  13477. }
  13478. }
  13479. // Array of scalars
  13480. function setValue1fv( gl, v ) {
  13481. var cache = this.cache;
  13482. if ( arraysEqual( cache, v ) ) return;
  13483. gl.uniform1fv( this.addr, v );
  13484. copyArray( cache, v );
  13485. }
  13486. function setValue1iv( gl, v ) {
  13487. var cache = this.cache;
  13488. if ( arraysEqual( cache, v ) ) return;
  13489. gl.uniform1iv( this.addr, v );
  13490. copyArray( cache, v );
  13491. }
  13492. // Array of vectors (flat or from THREE classes)
  13493. function setValueV2a( gl, v ) {
  13494. var cache = this.cache;
  13495. var data = flatten( v, this.size, 2 );
  13496. if ( arraysEqual( cache, data ) ) return;
  13497. gl.uniform2fv( this.addr, data );
  13498. this.updateCache( data );
  13499. }
  13500. function setValueV3a( gl, v ) {
  13501. var cache = this.cache;
  13502. var data = flatten( v, this.size, 3 );
  13503. if ( arraysEqual( cache, data ) ) return;
  13504. gl.uniform3fv( this.addr, data );
  13505. this.updateCache( data );
  13506. }
  13507. function setValueV4a( gl, v ) {
  13508. var cache = this.cache;
  13509. var data = flatten( v, this.size, 4 );
  13510. if ( arraysEqual( cache, data ) ) return;
  13511. gl.uniform4fv( this.addr, data );
  13512. this.updateCache( data );
  13513. }
  13514. // Array of matrices (flat or from THREE clases)
  13515. function setValueM2a( gl, v ) {
  13516. var cache = this.cache;
  13517. var data = flatten( v, this.size, 4 );
  13518. if ( arraysEqual( cache, data ) ) return;
  13519. gl.uniformMatrix2fv( this.addr, false, data );
  13520. this.updateCache( data );
  13521. }
  13522. function setValueM3a( gl, v ) {
  13523. var cache = this.cache;
  13524. var data = flatten( v, this.size, 9 );
  13525. if ( arraysEqual( cache, data ) ) return;
  13526. gl.uniformMatrix3fv( this.addr, false, data );
  13527. this.updateCache( data );
  13528. }
  13529. function setValueM4a( gl, v ) {
  13530. var cache = this.cache;
  13531. var data = flatten( v, this.size, 16 );
  13532. if ( arraysEqual( cache, data ) ) return;
  13533. gl.uniformMatrix4fv( this.addr, false, data );
  13534. this.updateCache( data );
  13535. }
  13536. // Array of textures (2D / Cube)
  13537. function setValueT1a( gl, v, renderer ) {
  13538. var cache = this.cache;
  13539. var n = v.length;
  13540. var units = allocTexUnits( renderer, n );
  13541. if ( arraysEqual( cache, units ) === false ) {
  13542. gl.uniform1iv( this.addr, units );
  13543. copyArray( cache, units );
  13544. }
  13545. for ( var i = 0; i !== n; ++ i ) {
  13546. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  13547. }
  13548. }
  13549. function setValueT6a( gl, v, renderer ) {
  13550. var cache = this.cache;
  13551. var n = v.length;
  13552. var units = allocTexUnits( renderer, n );
  13553. if ( arraysEqual( cache, units ) === false ) {
  13554. gl.uniform1iv( this.addr, units );
  13555. copyArray( cache, units );
  13556. }
  13557. for ( var i = 0; i !== n; ++ i ) {
  13558. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  13559. }
  13560. }
  13561. // Helper to pick the right setter for a pure (bottom-level) array
  13562. function getPureArraySetter( type ) {
  13563. switch ( type ) {
  13564. case 0x1406: return setValue1fv; // FLOAT
  13565. case 0x8b50: return setValueV2a; // _VEC2
  13566. case 0x8b51: return setValueV3a; // _VEC3
  13567. case 0x8b52: return setValueV4a; // _VEC4
  13568. case 0x8b5a: return setValueM2a; // _MAT2
  13569. case 0x8b5b: return setValueM3a; // _MAT3
  13570. case 0x8b5c: return setValueM4a; // _MAT4
  13571. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  13572. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  13573. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  13574. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  13575. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  13576. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  13577. }
  13578. }
  13579. // --- Uniform Classes ---
  13580. function SingleUniform( id, activeInfo, addr ) {
  13581. this.id = id;
  13582. this.addr = addr;
  13583. this.cache = [];
  13584. this.setValue = getSingularSetter( activeInfo.type );
  13585. // this.path = activeInfo.name; // DEBUG
  13586. }
  13587. function PureArrayUniform( id, activeInfo, addr ) {
  13588. this.id = id;
  13589. this.addr = addr;
  13590. this.cache = [];
  13591. this.size = activeInfo.size;
  13592. this.setValue = getPureArraySetter( activeInfo.type );
  13593. // this.path = activeInfo.name; // DEBUG
  13594. }
  13595. PureArrayUniform.prototype.updateCache = function ( data ) {
  13596. var cache = this.cache;
  13597. if ( data instanceof Float32Array && cache.length !== data.length ) {
  13598. this.cache = new Float32Array( data.length );
  13599. }
  13600. copyArray( cache, data );
  13601. };
  13602. function StructuredUniform( id ) {
  13603. this.id = id;
  13604. UniformContainer.call( this ); // mix-in
  13605. }
  13606. StructuredUniform.prototype.setValue = function ( gl, value, renderer ) {
  13607. var seq = this.seq;
  13608. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  13609. var u = seq[ i ];
  13610. u.setValue( gl, value[ u.id ], renderer );
  13611. }
  13612. };
  13613. // --- Top-level ---
  13614. // Parser - builds up the property tree from the path strings
  13615. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  13616. // extracts
  13617. // - the identifier (member name or array index)
  13618. // - followed by an optional right bracket (found when array index)
  13619. // - followed by an optional left bracket or dot (type of subscript)
  13620. //
  13621. // Note: These portions can be read in a non-overlapping fashion and
  13622. // allow straightforward parsing of the hierarchy that WebGL encodes
  13623. // in the uniform names.
  13624. function addUniform( container, uniformObject ) {
  13625. container.seq.push( uniformObject );
  13626. container.map[ uniformObject.id ] = uniformObject;
  13627. }
  13628. function parseUniform( activeInfo, addr, container ) {
  13629. var path = activeInfo.name,
  13630. pathLength = path.length;
  13631. // reset RegExp object, because of the early exit of a previous run
  13632. RePathPart.lastIndex = 0;
  13633. while ( true ) {
  13634. var match = RePathPart.exec( path ),
  13635. matchEnd = RePathPart.lastIndex,
  13636. id = match[ 1 ],
  13637. idIsIndex = match[ 2 ] === ']',
  13638. subscript = match[ 3 ];
  13639. if ( idIsIndex ) id = id | 0; // convert to integer
  13640. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  13641. // bare name or "pure" bottom-level array "[0]" suffix
  13642. addUniform( container, subscript === undefined ?
  13643. new SingleUniform( id, activeInfo, addr ) :
  13644. new PureArrayUniform( id, activeInfo, addr ) );
  13645. break;
  13646. } else {
  13647. // step into inner node / create it in case it doesn't exist
  13648. var map = container.map, next = map[ id ];
  13649. if ( next === undefined ) {
  13650. next = new StructuredUniform( id );
  13651. addUniform( container, next );
  13652. }
  13653. container = next;
  13654. }
  13655. }
  13656. }
  13657. // Root Container
  13658. function WebGLUniforms( gl, program, renderer ) {
  13659. UniformContainer.call( this );
  13660. this.renderer = renderer;
  13661. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  13662. for ( var i = 0; i < n; ++ i ) {
  13663. var info = gl.getActiveUniform( program, i ),
  13664. addr = gl.getUniformLocation( program, info.name );
  13665. parseUniform( info, addr, this );
  13666. }
  13667. }
  13668. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  13669. var u = this.map[ name ];
  13670. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  13671. };
  13672. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  13673. var v = object[ name ];
  13674. if ( v !== undefined ) this.setValue( gl, name, v );
  13675. };
  13676. // Static interface
  13677. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  13678. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  13679. var u = seq[ i ],
  13680. v = values[ u.id ];
  13681. if ( v.needsUpdate !== false ) {
  13682. // note: always updating when .needsUpdate is undefined
  13683. u.setValue( gl, v.value, renderer );
  13684. }
  13685. }
  13686. };
  13687. WebGLUniforms.seqWithValue = function ( seq, values ) {
  13688. var r = [];
  13689. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  13690. var u = seq[ i ];
  13691. if ( u.id in values ) r.push( u );
  13692. }
  13693. return r;
  13694. };
  13695. /**
  13696. * @author mrdoob / http://mrdoob.com/
  13697. */
  13698. function addLineNumbers( string ) {
  13699. var lines = string.split( '\n' );
  13700. for ( var i = 0; i < lines.length; i ++ ) {
  13701. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  13702. }
  13703. return lines.join( '\n' );
  13704. }
  13705. function WebGLShader( gl, type, string ) {
  13706. var shader = gl.createShader( type );
  13707. gl.shaderSource( shader, string );
  13708. gl.compileShader( shader );
  13709. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  13710. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  13711. }
  13712. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  13713. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  13714. }
  13715. // --enable-privileged-webgl-extension
  13716. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  13717. return shader;
  13718. }
  13719. /**
  13720. * @author mrdoob / http://mrdoob.com/
  13721. */
  13722. var programIdCount = 0;
  13723. function getEncodingComponents( encoding ) {
  13724. switch ( encoding ) {
  13725. case LinearEncoding:
  13726. return [ 'Linear', '( value )' ];
  13727. case sRGBEncoding:
  13728. return [ 'sRGB', '( value )' ];
  13729. case RGBEEncoding:
  13730. return [ 'RGBE', '( value )' ];
  13731. case RGBM7Encoding:
  13732. return [ 'RGBM', '( value, 7.0 )' ];
  13733. case RGBM16Encoding:
  13734. return [ 'RGBM', '( value, 16.0 )' ];
  13735. case RGBDEncoding:
  13736. return [ 'RGBD', '( value, 256.0 )' ];
  13737. case GammaEncoding:
  13738. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  13739. default:
  13740. throw new Error( 'unsupported encoding: ' + encoding );
  13741. }
  13742. }
  13743. function getTexelDecodingFunction( functionName, encoding ) {
  13744. var components = getEncodingComponents( encoding );
  13745. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  13746. }
  13747. function getTexelEncodingFunction( functionName, encoding ) {
  13748. var components = getEncodingComponents( encoding );
  13749. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  13750. }
  13751. function getToneMappingFunction( functionName, toneMapping ) {
  13752. var toneMappingName;
  13753. switch ( toneMapping ) {
  13754. case LinearToneMapping:
  13755. toneMappingName = 'Linear';
  13756. break;
  13757. case ReinhardToneMapping:
  13758. toneMappingName = 'Reinhard';
  13759. break;
  13760. case Uncharted2ToneMapping:
  13761. toneMappingName = 'Uncharted2';
  13762. break;
  13763. case CineonToneMapping:
  13764. toneMappingName = 'OptimizedCineon';
  13765. break;
  13766. default:
  13767. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  13768. }
  13769. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  13770. }
  13771. function generateExtensions( extensions, parameters, rendererExtensions ) {
  13772. extensions = extensions || {};
  13773. var chunks = [
  13774. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || ( parameters.normalMap && ! parameters.objectSpaceNormalMap ) || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  13775. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  13776. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  13777. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  13778. ];
  13779. return chunks.filter( filterEmptyLine ).join( '\n' );
  13780. }
  13781. function generateDefines( defines ) {
  13782. var chunks = [];
  13783. for ( var name in defines ) {
  13784. var value = defines[ name ];
  13785. if ( value === false ) continue;
  13786. chunks.push( '#define ' + name + ' ' + value );
  13787. }
  13788. return chunks.join( '\n' );
  13789. }
  13790. function fetchAttributeLocations( gl, program ) {
  13791. var attributes = {};
  13792. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  13793. for ( var i = 0; i < n; i ++ ) {
  13794. var info = gl.getActiveAttrib( program, i );
  13795. var name = info.name;
  13796. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  13797. attributes[ name ] = gl.getAttribLocation( program, name );
  13798. }
  13799. return attributes;
  13800. }
  13801. function filterEmptyLine( string ) {
  13802. return string !== '';
  13803. }
  13804. function replaceLightNums( string, parameters ) {
  13805. return string
  13806. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  13807. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  13808. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  13809. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  13810. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  13811. }
  13812. function replaceClippingPlaneNums( string, parameters ) {
  13813. return string
  13814. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  13815. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  13816. }
  13817. function parseIncludes( string ) {
  13818. var pattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  13819. function replace( match, include ) {
  13820. var replace = ShaderChunk[ include ];
  13821. if ( replace === undefined ) {
  13822. throw new Error( 'Can not resolve #include <' + include + '>' );
  13823. }
  13824. return parseIncludes( replace );
  13825. }
  13826. return string.replace( pattern, replace );
  13827. }
  13828. function unrollLoops( string ) {
  13829. var pattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  13830. function replace( match, start, end, snippet ) {
  13831. var unroll = '';
  13832. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  13833. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  13834. }
  13835. return unroll;
  13836. }
  13837. return string.replace( pattern, replace );
  13838. }
  13839. function WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities ) {
  13840. var gl = renderer.context;
  13841. var defines = material.defines;
  13842. var vertexShader = shader.vertexShader;
  13843. var fragmentShader = shader.fragmentShader;
  13844. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  13845. if ( parameters.shadowMapType === PCFShadowMap ) {
  13846. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  13847. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  13848. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  13849. }
  13850. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  13851. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  13852. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  13853. if ( parameters.envMap ) {
  13854. switch ( material.envMap.mapping ) {
  13855. case CubeReflectionMapping:
  13856. case CubeRefractionMapping:
  13857. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  13858. break;
  13859. case CubeUVReflectionMapping:
  13860. case CubeUVRefractionMapping:
  13861. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  13862. break;
  13863. case EquirectangularReflectionMapping:
  13864. case EquirectangularRefractionMapping:
  13865. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  13866. break;
  13867. case SphericalReflectionMapping:
  13868. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  13869. break;
  13870. }
  13871. switch ( material.envMap.mapping ) {
  13872. case CubeRefractionMapping:
  13873. case EquirectangularRefractionMapping:
  13874. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  13875. break;
  13876. }
  13877. switch ( material.combine ) {
  13878. case MultiplyOperation:
  13879. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  13880. break;
  13881. case MixOperation:
  13882. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  13883. break;
  13884. case AddOperation:
  13885. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  13886. break;
  13887. }
  13888. }
  13889. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  13890. // console.log( 'building new program ' );
  13891. //
  13892. var customExtensions = capabilities.isWebGL2 ? '' : generateExtensions( material.extensions, parameters, extensions );
  13893. var customDefines = generateDefines( defines );
  13894. //
  13895. var program = gl.createProgram();
  13896. var prefixVertex, prefixFragment;
  13897. if ( material.isRawShaderMaterial ) {
  13898. prefixVertex = [
  13899. customDefines
  13900. ].filter( filterEmptyLine ).join( '\n' );
  13901. if ( prefixVertex.length > 0 ) {
  13902. prefixVertex += '\n';
  13903. }
  13904. prefixFragment = [
  13905. customExtensions,
  13906. customDefines
  13907. ].filter( filterEmptyLine ).join( '\n' );
  13908. if ( prefixFragment.length > 0 ) {
  13909. prefixFragment += '\n';
  13910. }
  13911. } else {
  13912. prefixVertex = [
  13913. 'precision ' + parameters.precision + ' float;',
  13914. 'precision ' + parameters.precision + ' int;',
  13915. '#define SHADER_NAME ' + shader.name,
  13916. customDefines,
  13917. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  13918. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  13919. '#define MAX_BONES ' + parameters.maxBones,
  13920. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  13921. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  13922. parameters.map ? '#define USE_MAP' : '',
  13923. parameters.envMap ? '#define USE_ENVMAP' : '',
  13924. parameters.envMap ? '#define ' + envMapModeDefine : '',
  13925. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  13926. parameters.aoMap ? '#define USE_AOMAP' : '',
  13927. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  13928. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  13929. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  13930. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  13931. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  13932. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  13933. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  13934. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  13935. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  13936. parameters.vertexColors ? '#define USE_COLOR' : '',
  13937. parameters.flatShading ? '#define FLAT_SHADED' : '',
  13938. parameters.skinning ? '#define USE_SKINNING' : '',
  13939. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  13940. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  13941. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  13942. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  13943. parameters.flipSided ? '#define FLIP_SIDED' : '',
  13944. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  13945. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  13946. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  13947. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  13948. parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  13949. 'uniform mat4 modelMatrix;',
  13950. 'uniform mat4 modelViewMatrix;',
  13951. 'uniform mat4 projectionMatrix;',
  13952. 'uniform mat4 viewMatrix;',
  13953. 'uniform mat3 normalMatrix;',
  13954. 'uniform vec3 cameraPosition;',
  13955. 'attribute vec3 position;',
  13956. 'attribute vec3 normal;',
  13957. 'attribute vec2 uv;',
  13958. '#ifdef USE_COLOR',
  13959. ' attribute vec3 color;',
  13960. '#endif',
  13961. '#ifdef USE_MORPHTARGETS',
  13962. ' attribute vec3 morphTarget0;',
  13963. ' attribute vec3 morphTarget1;',
  13964. ' attribute vec3 morphTarget2;',
  13965. ' attribute vec3 morphTarget3;',
  13966. ' #ifdef USE_MORPHNORMALS',
  13967. ' attribute vec3 morphNormal0;',
  13968. ' attribute vec3 morphNormal1;',
  13969. ' attribute vec3 morphNormal2;',
  13970. ' attribute vec3 morphNormal3;',
  13971. ' #else',
  13972. ' attribute vec3 morphTarget4;',
  13973. ' attribute vec3 morphTarget5;',
  13974. ' attribute vec3 morphTarget6;',
  13975. ' attribute vec3 morphTarget7;',
  13976. ' #endif',
  13977. '#endif',
  13978. '#ifdef USE_SKINNING',
  13979. ' attribute vec4 skinIndex;',
  13980. ' attribute vec4 skinWeight;',
  13981. '#endif',
  13982. '\n'
  13983. ].filter( filterEmptyLine ).join( '\n' );
  13984. prefixFragment = [
  13985. customExtensions,
  13986. 'precision ' + parameters.precision + ' float;',
  13987. 'precision ' + parameters.precision + ' int;',
  13988. '#define SHADER_NAME ' + shader.name,
  13989. customDefines,
  13990. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  13991. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  13992. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  13993. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  13994. parameters.map ? '#define USE_MAP' : '',
  13995. parameters.envMap ? '#define USE_ENVMAP' : '',
  13996. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  13997. parameters.envMap ? '#define ' + envMapModeDefine : '',
  13998. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  13999. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14000. parameters.aoMap ? '#define USE_AOMAP' : '',
  14001. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14002. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14003. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14004. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  14005. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14006. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  14007. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  14008. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14009. parameters.vertexColors ? '#define USE_COLOR' : '',
  14010. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  14011. parameters.flatShading ? '#define FLAT_SHADED' : '',
  14012. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14013. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14014. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14015. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14016. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  14017. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  14018. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14019. parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14020. parameters.envMap && ( capabilities.isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) ) ? '#define TEXTURE_LOD_EXT' : '',
  14021. 'uniform mat4 viewMatrix;',
  14022. 'uniform vec3 cameraPosition;',
  14023. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  14024. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  14025. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  14026. parameters.dithering ? '#define DITHERING' : '',
  14027. ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  14028. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  14029. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  14030. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  14031. parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '',
  14032. parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '',
  14033. '\n'
  14034. ].filter( filterEmptyLine ).join( '\n' );
  14035. }
  14036. vertexShader = parseIncludes( vertexShader );
  14037. vertexShader = replaceLightNums( vertexShader, parameters );
  14038. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  14039. fragmentShader = parseIncludes( fragmentShader );
  14040. fragmentShader = replaceLightNums( fragmentShader, parameters );
  14041. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  14042. vertexShader = unrollLoops( vertexShader );
  14043. fragmentShader = unrollLoops( fragmentShader );
  14044. if ( capabilities.isWebGL2 && ! material.isRawShaderMaterial ) {
  14045. var isGLSL3ShaderMaterial = false;
  14046. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  14047. if ( material.isShaderMaterial &&
  14048. vertexShader.match( versionRegex ) !== null &&
  14049. fragmentShader.match( versionRegex ) !== null ) {
  14050. isGLSL3ShaderMaterial = true;
  14051. vertexShader = vertexShader.replace( versionRegex, '' );
  14052. fragmentShader = fragmentShader.replace( versionRegex, '' );
  14053. }
  14054. // GLSL 3.0 conversion
  14055. prefixVertex = [
  14056. '#version 300 es\n',
  14057. '#define attribute in',
  14058. '#define varying out',
  14059. '#define texture2D texture'
  14060. ].join( '\n' ) + '\n' + prefixVertex;
  14061. prefixFragment = [
  14062. '#version 300 es\n',
  14063. '#define varying in',
  14064. isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;',
  14065. isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor',
  14066. '#define gl_FragDepthEXT gl_FragDepth',
  14067. '#define texture2D texture',
  14068. '#define textureCube texture',
  14069. '#define texture2DProj textureProj',
  14070. '#define texture2DLodEXT textureLod',
  14071. '#define texture2DProjLodEXT textureProjLod',
  14072. '#define textureCubeLodEXT textureLod',
  14073. '#define texture2DGradEXT textureGrad',
  14074. '#define texture2DProjGradEXT textureProjGrad',
  14075. '#define textureCubeGradEXT textureGrad'
  14076. ].join( '\n' ) + '\n' + prefixFragment;
  14077. }
  14078. var vertexGlsl = prefixVertex + vertexShader;
  14079. var fragmentGlsl = prefixFragment + fragmentShader;
  14080. // console.log( '*VERTEX*', vertexGlsl );
  14081. // console.log( '*FRAGMENT*', fragmentGlsl );
  14082. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  14083. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  14084. gl.attachShader( program, glVertexShader );
  14085. gl.attachShader( program, glFragmentShader );
  14086. // Force a particular attribute to index 0.
  14087. if ( material.index0AttributeName !== undefined ) {
  14088. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  14089. } else if ( parameters.morphTargets === true ) {
  14090. // programs with morphTargets displace position out of attribute 0
  14091. gl.bindAttribLocation( program, 0, 'position' );
  14092. }
  14093. gl.linkProgram( program );
  14094. var programLog = gl.getProgramInfoLog( program ).trim();
  14095. var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  14096. var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  14097. var runnable = true;
  14098. var haveDiagnostics = true;
  14099. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  14100. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  14101. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  14102. runnable = false;
  14103. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  14104. } else if ( programLog !== '' ) {
  14105. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  14106. } else if ( vertexLog === '' || fragmentLog === '' ) {
  14107. haveDiagnostics = false;
  14108. }
  14109. if ( haveDiagnostics ) {
  14110. this.diagnostics = {
  14111. runnable: runnable,
  14112. material: material,
  14113. programLog: programLog,
  14114. vertexShader: {
  14115. log: vertexLog,
  14116. prefix: prefixVertex
  14117. },
  14118. fragmentShader: {
  14119. log: fragmentLog,
  14120. prefix: prefixFragment
  14121. }
  14122. };
  14123. }
  14124. // clean up
  14125. gl.deleteShader( glVertexShader );
  14126. gl.deleteShader( glFragmentShader );
  14127. // set up caching for uniform locations
  14128. var cachedUniforms;
  14129. this.getUniforms = function () {
  14130. if ( cachedUniforms === undefined ) {
  14131. cachedUniforms = new WebGLUniforms( gl, program, renderer );
  14132. }
  14133. return cachedUniforms;
  14134. };
  14135. // set up caching for attribute locations
  14136. var cachedAttributes;
  14137. this.getAttributes = function () {
  14138. if ( cachedAttributes === undefined ) {
  14139. cachedAttributes = fetchAttributeLocations( gl, program );
  14140. }
  14141. return cachedAttributes;
  14142. };
  14143. // free resource
  14144. this.destroy = function () {
  14145. gl.deleteProgram( program );
  14146. this.program = undefined;
  14147. };
  14148. // DEPRECATED
  14149. Object.defineProperties( this, {
  14150. uniforms: {
  14151. get: function () {
  14152. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  14153. return this.getUniforms();
  14154. }
  14155. },
  14156. attributes: {
  14157. get: function () {
  14158. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  14159. return this.getAttributes();
  14160. }
  14161. }
  14162. } );
  14163. //
  14164. this.name = shader.name;
  14165. this.id = programIdCount ++;
  14166. this.code = code;
  14167. this.usedTimes = 1;
  14168. this.program = program;
  14169. this.vertexShader = glVertexShader;
  14170. this.fragmentShader = glFragmentShader;
  14171. return this;
  14172. }
  14173. /**
  14174. * @author mrdoob / http://mrdoob.com/
  14175. */
  14176. function WebGLPrograms( renderer, extensions, capabilities ) {
  14177. var programs = [];
  14178. var shaderIDs = {
  14179. MeshDepthMaterial: 'depth',
  14180. MeshDistanceMaterial: 'distanceRGBA',
  14181. MeshNormalMaterial: 'normal',
  14182. MeshBasicMaterial: 'basic',
  14183. MeshLambertMaterial: 'lambert',
  14184. MeshPhongMaterial: 'phong',
  14185. MeshToonMaterial: 'phong',
  14186. MeshStandardMaterial: 'physical',
  14187. MeshPhysicalMaterial: 'physical',
  14188. LineBasicMaterial: 'basic',
  14189. LineDashedMaterial: 'dashed',
  14190. PointsMaterial: 'points',
  14191. ShadowMaterial: 'shadow',
  14192. SpriteMaterial: 'sprite'
  14193. };
  14194. var parameterNames = [
  14195. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  14196. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "displacementMap", "specularMap",
  14197. "roughnessMap", "metalnessMap", "gradientMap",
  14198. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  14199. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  14200. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  14201. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  14202. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  14203. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  14204. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  14205. ];
  14206. function allocateBones( object ) {
  14207. var skeleton = object.skeleton;
  14208. var bones = skeleton.bones;
  14209. if ( capabilities.floatVertexTextures ) {
  14210. return 1024;
  14211. } else {
  14212. // default for when object is not specified
  14213. // ( for example when prebuilding shader to be used with multiple objects )
  14214. //
  14215. // - leave some extra space for other uniforms
  14216. // - limit here is ANGLE's 254 max uniform vectors
  14217. // (up to 54 should be safe)
  14218. var nVertexUniforms = capabilities.maxVertexUniforms;
  14219. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14220. var maxBones = Math.min( nVertexMatrices, bones.length );
  14221. if ( maxBones < bones.length ) {
  14222. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  14223. return 0;
  14224. }
  14225. return maxBones;
  14226. }
  14227. }
  14228. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  14229. var encoding;
  14230. if ( ! map ) {
  14231. encoding = LinearEncoding;
  14232. } else if ( map.isTexture ) {
  14233. encoding = map.encoding;
  14234. } else if ( map.isWebGLRenderTarget ) {
  14235. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  14236. encoding = map.texture.encoding;
  14237. }
  14238. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  14239. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  14240. encoding = GammaEncoding;
  14241. }
  14242. return encoding;
  14243. }
  14244. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  14245. var shaderID = shaderIDs[ material.type ];
  14246. // heuristics to create shader parameters according to lights in the scene
  14247. // (not to blow over maxLights budget)
  14248. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  14249. var precision = capabilities.precision;
  14250. if ( material.precision !== null ) {
  14251. precision = capabilities.getMaxPrecision( material.precision );
  14252. if ( precision !== material.precision ) {
  14253. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  14254. }
  14255. }
  14256. var currentRenderTarget = renderer.getRenderTarget();
  14257. var parameters = {
  14258. shaderID: shaderID,
  14259. precision: precision,
  14260. supportsVertexTextures: capabilities.vertexTextures,
  14261. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  14262. map: !! material.map,
  14263. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  14264. envMap: !! material.envMap,
  14265. envMapMode: material.envMap && material.envMap.mapping,
  14266. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  14267. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  14268. lightMap: !! material.lightMap,
  14269. aoMap: !! material.aoMap,
  14270. emissiveMap: !! material.emissiveMap,
  14271. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  14272. bumpMap: !! material.bumpMap,
  14273. normalMap: !! material.normalMap,
  14274. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  14275. displacementMap: !! material.displacementMap,
  14276. roughnessMap: !! material.roughnessMap,
  14277. metalnessMap: !! material.metalnessMap,
  14278. specularMap: !! material.specularMap,
  14279. alphaMap: !! material.alphaMap,
  14280. gradientMap: !! material.gradientMap,
  14281. combine: material.combine,
  14282. vertexColors: material.vertexColors,
  14283. fog: !! fog,
  14284. useFog: material.fog,
  14285. fogExp: ( fog && fog.isFogExp2 ),
  14286. flatShading: material.flatShading,
  14287. sizeAttenuation: material.sizeAttenuation,
  14288. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  14289. skinning: material.skinning && maxBones > 0,
  14290. maxBones: maxBones,
  14291. useVertexTexture: capabilities.floatVertexTextures,
  14292. morphTargets: material.morphTargets,
  14293. morphNormals: material.morphNormals,
  14294. maxMorphTargets: renderer.maxMorphTargets,
  14295. maxMorphNormals: renderer.maxMorphNormals,
  14296. numDirLights: lights.directional.length,
  14297. numPointLights: lights.point.length,
  14298. numSpotLights: lights.spot.length,
  14299. numRectAreaLights: lights.rectArea.length,
  14300. numHemiLights: lights.hemi.length,
  14301. numClippingPlanes: nClipPlanes,
  14302. numClipIntersection: nClipIntersection,
  14303. dithering: material.dithering,
  14304. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,
  14305. shadowMapType: renderer.shadowMap.type,
  14306. toneMapping: renderer.toneMapping,
  14307. physicallyCorrectLights: renderer.physicallyCorrectLights,
  14308. premultipliedAlpha: material.premultipliedAlpha,
  14309. alphaTest: material.alphaTest,
  14310. doubleSided: material.side === DoubleSide,
  14311. flipSided: material.side === BackSide,
  14312. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  14313. };
  14314. return parameters;
  14315. };
  14316. this.getProgramCode = function ( material, parameters ) {
  14317. var array = [];
  14318. if ( parameters.shaderID ) {
  14319. array.push( parameters.shaderID );
  14320. } else {
  14321. array.push( material.fragmentShader );
  14322. array.push( material.vertexShader );
  14323. }
  14324. if ( material.defines !== undefined ) {
  14325. for ( var name in material.defines ) {
  14326. array.push( name );
  14327. array.push( material.defines[ name ] );
  14328. }
  14329. }
  14330. for ( var i = 0; i < parameterNames.length; i ++ ) {
  14331. array.push( parameters[ parameterNames[ i ] ] );
  14332. }
  14333. array.push( material.onBeforeCompile.toString() );
  14334. array.push( renderer.gammaOutput );
  14335. return array.join();
  14336. };
  14337. this.acquireProgram = function ( material, shader, parameters, code ) {
  14338. var program;
  14339. // Check if code has been already compiled
  14340. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  14341. var programInfo = programs[ p ];
  14342. if ( programInfo.code === code ) {
  14343. program = programInfo;
  14344. ++ program.usedTimes;
  14345. break;
  14346. }
  14347. }
  14348. if ( program === undefined ) {
  14349. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities );
  14350. programs.push( program );
  14351. }
  14352. return program;
  14353. };
  14354. this.releaseProgram = function ( program ) {
  14355. if ( -- program.usedTimes === 0 ) {
  14356. // Remove from unordered set
  14357. var i = programs.indexOf( program );
  14358. programs[ i ] = programs[ programs.length - 1 ];
  14359. programs.pop();
  14360. // Free WebGL resources
  14361. program.destroy();
  14362. }
  14363. };
  14364. // Exposed for resource monitoring & error feedback via renderer.info:
  14365. this.programs = programs;
  14366. }
  14367. /**
  14368. * @author fordacious / fordacious.github.io
  14369. */
  14370. function WebGLProperties() {
  14371. var properties = new WeakMap();
  14372. function get( object ) {
  14373. var map = properties.get( object );
  14374. if ( map === undefined ) {
  14375. map = {};
  14376. properties.set( object, map );
  14377. }
  14378. return map;
  14379. }
  14380. function remove( object ) {
  14381. properties.delete( object );
  14382. }
  14383. function update( object, key, value ) {
  14384. properties.get( object )[ key ] = value;
  14385. }
  14386. function dispose() {
  14387. properties = new WeakMap();
  14388. }
  14389. return {
  14390. get: get,
  14391. remove: remove,
  14392. update: update,
  14393. dispose: dispose
  14394. };
  14395. }
  14396. /**
  14397. * @author mrdoob / http://mrdoob.com/
  14398. */
  14399. function painterSortStable( a, b ) {
  14400. if ( a.renderOrder !== b.renderOrder ) {
  14401. return a.renderOrder - b.renderOrder;
  14402. } else if ( a.program && b.program && a.program !== b.program ) {
  14403. return a.program.id - b.program.id;
  14404. } else if ( a.material.id !== b.material.id ) {
  14405. return a.material.id - b.material.id;
  14406. } else if ( a.z !== b.z ) {
  14407. return a.z - b.z;
  14408. } else {
  14409. return a.id - b.id;
  14410. }
  14411. }
  14412. function reversePainterSortStable( a, b ) {
  14413. if ( a.renderOrder !== b.renderOrder ) {
  14414. return a.renderOrder - b.renderOrder;
  14415. } if ( a.z !== b.z ) {
  14416. return b.z - a.z;
  14417. } else {
  14418. return a.id - b.id;
  14419. }
  14420. }
  14421. function WebGLRenderList() {
  14422. var renderItems = [];
  14423. var renderItemsIndex = 0;
  14424. var opaque = [];
  14425. var transparent = [];
  14426. function init() {
  14427. renderItemsIndex = 0;
  14428. opaque.length = 0;
  14429. transparent.length = 0;
  14430. }
  14431. function push( object, geometry, material, z, group ) {
  14432. var renderItem = renderItems[ renderItemsIndex ];
  14433. if ( renderItem === undefined ) {
  14434. renderItem = {
  14435. id: object.id,
  14436. object: object,
  14437. geometry: geometry,
  14438. material: material,
  14439. program: material.program,
  14440. renderOrder: object.renderOrder,
  14441. z: z,
  14442. group: group
  14443. };
  14444. renderItems[ renderItemsIndex ] = renderItem;
  14445. } else {
  14446. renderItem.id = object.id;
  14447. renderItem.object = object;
  14448. renderItem.geometry = geometry;
  14449. renderItem.material = material;
  14450. renderItem.program = material.program;
  14451. renderItem.renderOrder = object.renderOrder;
  14452. renderItem.z = z;
  14453. renderItem.group = group;
  14454. }
  14455. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  14456. renderItemsIndex ++;
  14457. }
  14458. function sort() {
  14459. if ( opaque.length > 1 ) opaque.sort( painterSortStable );
  14460. if ( transparent.length > 1 ) transparent.sort( reversePainterSortStable );
  14461. }
  14462. return {
  14463. opaque: opaque,
  14464. transparent: transparent,
  14465. init: init,
  14466. push: push,
  14467. sort: sort
  14468. };
  14469. }
  14470. function WebGLRenderLists() {
  14471. var lists = {};
  14472. function get( scene, camera ) {
  14473. var hash = scene.id + ',' + camera.id;
  14474. var list = lists[ hash ];
  14475. if ( list === undefined ) {
  14476. // console.log( 'THREE.WebGLRenderLists:', hash );
  14477. list = new WebGLRenderList();
  14478. lists[ hash ] = list;
  14479. }
  14480. return list;
  14481. }
  14482. function dispose() {
  14483. lists = {};
  14484. }
  14485. return {
  14486. get: get,
  14487. dispose: dispose
  14488. };
  14489. }
  14490. /**
  14491. * @author mrdoob / http://mrdoob.com/
  14492. */
  14493. function UniformsCache() {
  14494. var lights = {};
  14495. return {
  14496. get: function ( light ) {
  14497. if ( lights[ light.id ] !== undefined ) {
  14498. return lights[ light.id ];
  14499. }
  14500. var uniforms;
  14501. switch ( light.type ) {
  14502. case 'DirectionalLight':
  14503. uniforms = {
  14504. direction: new Vector3(),
  14505. color: new Color(),
  14506. shadow: false,
  14507. shadowBias: 0,
  14508. shadowRadius: 1,
  14509. shadowMapSize: new Vector2()
  14510. };
  14511. break;
  14512. case 'SpotLight':
  14513. uniforms = {
  14514. position: new Vector3(),
  14515. direction: new Vector3(),
  14516. color: new Color(),
  14517. distance: 0,
  14518. coneCos: 0,
  14519. penumbraCos: 0,
  14520. decay: 0,
  14521. shadow: false,
  14522. shadowBias: 0,
  14523. shadowRadius: 1,
  14524. shadowMapSize: new Vector2()
  14525. };
  14526. break;
  14527. case 'PointLight':
  14528. uniforms = {
  14529. position: new Vector3(),
  14530. color: new Color(),
  14531. distance: 0,
  14532. decay: 0,
  14533. shadow: false,
  14534. shadowBias: 0,
  14535. shadowRadius: 1,
  14536. shadowMapSize: new Vector2(),
  14537. shadowCameraNear: 1,
  14538. shadowCameraFar: 1000
  14539. };
  14540. break;
  14541. case 'HemisphereLight':
  14542. uniforms = {
  14543. direction: new Vector3(),
  14544. skyColor: new Color(),
  14545. groundColor: new Color()
  14546. };
  14547. break;
  14548. case 'RectAreaLight':
  14549. uniforms = {
  14550. color: new Color(),
  14551. position: new Vector3(),
  14552. halfWidth: new Vector3(),
  14553. halfHeight: new Vector3()
  14554. // TODO (abelnation): set RectAreaLight shadow uniforms
  14555. };
  14556. break;
  14557. }
  14558. lights[ light.id ] = uniforms;
  14559. return uniforms;
  14560. }
  14561. };
  14562. }
  14563. var count = 0;
  14564. function WebGLLights() {
  14565. var cache = new UniformsCache();
  14566. var state = {
  14567. id: count ++,
  14568. hash: {
  14569. stateID: - 1,
  14570. directionalLength: - 1,
  14571. pointLength: - 1,
  14572. spotLength: - 1,
  14573. rectAreaLength: - 1,
  14574. hemiLength: - 1,
  14575. shadowsLength: - 1
  14576. },
  14577. ambient: [ 0, 0, 0 ],
  14578. directional: [],
  14579. directionalShadowMap: [],
  14580. directionalShadowMatrix: [],
  14581. spot: [],
  14582. spotShadowMap: [],
  14583. spotShadowMatrix: [],
  14584. rectArea: [],
  14585. point: [],
  14586. pointShadowMap: [],
  14587. pointShadowMatrix: [],
  14588. hemi: []
  14589. };
  14590. var vector3 = new Vector3();
  14591. var matrix4 = new Matrix4();
  14592. var matrix42 = new Matrix4();
  14593. function setup( lights, shadows, camera ) {
  14594. var r = 0, g = 0, b = 0;
  14595. var directionalLength = 0;
  14596. var pointLength = 0;
  14597. var spotLength = 0;
  14598. var rectAreaLength = 0;
  14599. var hemiLength = 0;
  14600. var viewMatrix = camera.matrixWorldInverse;
  14601. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  14602. var light = lights[ i ];
  14603. var color = light.color;
  14604. var intensity = light.intensity;
  14605. var distance = light.distance;
  14606. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  14607. if ( light.isAmbientLight ) {
  14608. r += color.r * intensity;
  14609. g += color.g * intensity;
  14610. b += color.b * intensity;
  14611. } else if ( light.isDirectionalLight ) {
  14612. var uniforms = cache.get( light );
  14613. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  14614. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14615. vector3.setFromMatrixPosition( light.target.matrixWorld );
  14616. uniforms.direction.sub( vector3 );
  14617. uniforms.direction.transformDirection( viewMatrix );
  14618. uniforms.shadow = light.castShadow;
  14619. if ( light.castShadow ) {
  14620. var shadow = light.shadow;
  14621. uniforms.shadowBias = shadow.bias;
  14622. uniforms.shadowRadius = shadow.radius;
  14623. uniforms.shadowMapSize = shadow.mapSize;
  14624. }
  14625. state.directionalShadowMap[ directionalLength ] = shadowMap;
  14626. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  14627. state.directional[ directionalLength ] = uniforms;
  14628. directionalLength ++;
  14629. } else if ( light.isSpotLight ) {
  14630. var uniforms = cache.get( light );
  14631. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14632. uniforms.position.applyMatrix4( viewMatrix );
  14633. uniforms.color.copy( color ).multiplyScalar( intensity );
  14634. uniforms.distance = distance;
  14635. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14636. vector3.setFromMatrixPosition( light.target.matrixWorld );
  14637. uniforms.direction.sub( vector3 );
  14638. uniforms.direction.transformDirection( viewMatrix );
  14639. uniforms.coneCos = Math.cos( light.angle );
  14640. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  14641. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  14642. uniforms.shadow = light.castShadow;
  14643. if ( light.castShadow ) {
  14644. var shadow = light.shadow;
  14645. uniforms.shadowBias = shadow.bias;
  14646. uniforms.shadowRadius = shadow.radius;
  14647. uniforms.shadowMapSize = shadow.mapSize;
  14648. }
  14649. state.spotShadowMap[ spotLength ] = shadowMap;
  14650. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  14651. state.spot[ spotLength ] = uniforms;
  14652. spotLength ++;
  14653. } else if ( light.isRectAreaLight ) {
  14654. var uniforms = cache.get( light );
  14655. // (a) intensity is the total visible light emitted
  14656. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  14657. // (b) intensity is the brightness of the light
  14658. uniforms.color.copy( color ).multiplyScalar( intensity );
  14659. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14660. uniforms.position.applyMatrix4( viewMatrix );
  14661. // extract local rotation of light to derive width/height half vectors
  14662. matrix42.identity();
  14663. matrix4.copy( light.matrixWorld );
  14664. matrix4.premultiply( viewMatrix );
  14665. matrix42.extractRotation( matrix4 );
  14666. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  14667. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  14668. uniforms.halfWidth.applyMatrix4( matrix42 );
  14669. uniforms.halfHeight.applyMatrix4( matrix42 );
  14670. // TODO (abelnation): RectAreaLight distance?
  14671. // uniforms.distance = distance;
  14672. state.rectArea[ rectAreaLength ] = uniforms;
  14673. rectAreaLength ++;
  14674. } else if ( light.isPointLight ) {
  14675. var uniforms = cache.get( light );
  14676. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14677. uniforms.position.applyMatrix4( viewMatrix );
  14678. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  14679. uniforms.distance = light.distance;
  14680. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  14681. uniforms.shadow = light.castShadow;
  14682. if ( light.castShadow ) {
  14683. var shadow = light.shadow;
  14684. uniforms.shadowBias = shadow.bias;
  14685. uniforms.shadowRadius = shadow.radius;
  14686. uniforms.shadowMapSize = shadow.mapSize;
  14687. uniforms.shadowCameraNear = shadow.camera.near;
  14688. uniforms.shadowCameraFar = shadow.camera.far;
  14689. }
  14690. state.pointShadowMap[ pointLength ] = shadowMap;
  14691. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  14692. state.point[ pointLength ] = uniforms;
  14693. pointLength ++;
  14694. } else if ( light.isHemisphereLight ) {
  14695. var uniforms = cache.get( light );
  14696. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14697. uniforms.direction.transformDirection( viewMatrix );
  14698. uniforms.direction.normalize();
  14699. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  14700. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  14701. state.hemi[ hemiLength ] = uniforms;
  14702. hemiLength ++;
  14703. }
  14704. }
  14705. state.ambient[ 0 ] = r;
  14706. state.ambient[ 1 ] = g;
  14707. state.ambient[ 2 ] = b;
  14708. state.directional.length = directionalLength;
  14709. state.spot.length = spotLength;
  14710. state.rectArea.length = rectAreaLength;
  14711. state.point.length = pointLength;
  14712. state.hemi.length = hemiLength;
  14713. state.hash.stateID = state.id;
  14714. state.hash.directionalLength = directionalLength;
  14715. state.hash.pointLength = pointLength;
  14716. state.hash.spotLength = spotLength;
  14717. state.hash.rectAreaLength = rectAreaLength;
  14718. state.hash.hemiLength = hemiLength;
  14719. state.hash.shadowsLength = shadows.length;
  14720. }
  14721. return {
  14722. setup: setup,
  14723. state: state
  14724. };
  14725. }
  14726. /**
  14727. * @author Mugen87 / https://github.com/Mugen87
  14728. */
  14729. function WebGLRenderState() {
  14730. var lights = new WebGLLights();
  14731. var lightsArray = [];
  14732. var shadowsArray = [];
  14733. function init() {
  14734. lightsArray.length = 0;
  14735. shadowsArray.length = 0;
  14736. }
  14737. function pushLight( light ) {
  14738. lightsArray.push( light );
  14739. }
  14740. function pushShadow( shadowLight ) {
  14741. shadowsArray.push( shadowLight );
  14742. }
  14743. function setupLights( camera ) {
  14744. lights.setup( lightsArray, shadowsArray, camera );
  14745. }
  14746. var state = {
  14747. lightsArray: lightsArray,
  14748. shadowsArray: shadowsArray,
  14749. lights: lights
  14750. };
  14751. return {
  14752. init: init,
  14753. state: state,
  14754. setupLights: setupLights,
  14755. pushLight: pushLight,
  14756. pushShadow: pushShadow
  14757. };
  14758. }
  14759. function WebGLRenderStates() {
  14760. var renderStates = {};
  14761. function get( scene, camera ) {
  14762. var renderState;
  14763. if ( renderStates[ scene.id ] === undefined ) {
  14764. renderState = new WebGLRenderState();
  14765. renderStates[ scene.id ] = {};
  14766. renderStates[ scene.id ][ camera.id ] = renderState;
  14767. } else {
  14768. if ( renderStates[ scene.id ][ camera.id ] === undefined ) {
  14769. renderState = new WebGLRenderState();
  14770. renderStates[ scene.id ][ camera.id ] = renderState;
  14771. } else {
  14772. renderState = renderStates[ scene.id ][ camera.id ];
  14773. }
  14774. }
  14775. return renderState;
  14776. }
  14777. function dispose() {
  14778. renderStates = {};
  14779. }
  14780. return {
  14781. get: get,
  14782. dispose: dispose
  14783. };
  14784. }
  14785. /**
  14786. * @author mrdoob / http://mrdoob.com/
  14787. * @author alteredq / http://alteredqualia.com/
  14788. * @author bhouston / https://clara.io
  14789. * @author WestLangley / http://github.com/WestLangley
  14790. *
  14791. * parameters = {
  14792. *
  14793. * opacity: <float>,
  14794. *
  14795. * map: new THREE.Texture( <Image> ),
  14796. *
  14797. * alphaMap: new THREE.Texture( <Image> ),
  14798. *
  14799. * displacementMap: new THREE.Texture( <Image> ),
  14800. * displacementScale: <float>,
  14801. * displacementBias: <float>,
  14802. *
  14803. * wireframe: <boolean>,
  14804. * wireframeLinewidth: <float>
  14805. * }
  14806. */
  14807. function MeshDepthMaterial( parameters ) {
  14808. Material.call( this );
  14809. this.type = 'MeshDepthMaterial';
  14810. this.depthPacking = BasicDepthPacking;
  14811. this.skinning = false;
  14812. this.morphTargets = false;
  14813. this.map = null;
  14814. this.alphaMap = null;
  14815. this.displacementMap = null;
  14816. this.displacementScale = 1;
  14817. this.displacementBias = 0;
  14818. this.wireframe = false;
  14819. this.wireframeLinewidth = 1;
  14820. this.fog = false;
  14821. this.lights = false;
  14822. this.setValues( parameters );
  14823. }
  14824. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  14825. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  14826. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  14827. MeshDepthMaterial.prototype.copy = function ( source ) {
  14828. Material.prototype.copy.call( this, source );
  14829. this.depthPacking = source.depthPacking;
  14830. this.skinning = source.skinning;
  14831. this.morphTargets = source.morphTargets;
  14832. this.map = source.map;
  14833. this.alphaMap = source.alphaMap;
  14834. this.displacementMap = source.displacementMap;
  14835. this.displacementScale = source.displacementScale;
  14836. this.displacementBias = source.displacementBias;
  14837. this.wireframe = source.wireframe;
  14838. this.wireframeLinewidth = source.wireframeLinewidth;
  14839. return this;
  14840. };
  14841. /**
  14842. * @author WestLangley / http://github.com/WestLangley
  14843. *
  14844. * parameters = {
  14845. *
  14846. * referencePosition: <float>,
  14847. * nearDistance: <float>,
  14848. * farDistance: <float>,
  14849. *
  14850. * skinning: <bool>,
  14851. * morphTargets: <bool>,
  14852. *
  14853. * map: new THREE.Texture( <Image> ),
  14854. *
  14855. * alphaMap: new THREE.Texture( <Image> ),
  14856. *
  14857. * displacementMap: new THREE.Texture( <Image> ),
  14858. * displacementScale: <float>,
  14859. * displacementBias: <float>
  14860. *
  14861. * }
  14862. */
  14863. function MeshDistanceMaterial( parameters ) {
  14864. Material.call( this );
  14865. this.type = 'MeshDistanceMaterial';
  14866. this.referencePosition = new Vector3();
  14867. this.nearDistance = 1;
  14868. this.farDistance = 1000;
  14869. this.skinning = false;
  14870. this.morphTargets = false;
  14871. this.map = null;
  14872. this.alphaMap = null;
  14873. this.displacementMap = null;
  14874. this.displacementScale = 1;
  14875. this.displacementBias = 0;
  14876. this.fog = false;
  14877. this.lights = false;
  14878. this.setValues( parameters );
  14879. }
  14880. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  14881. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  14882. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  14883. MeshDistanceMaterial.prototype.copy = function ( source ) {
  14884. Material.prototype.copy.call( this, source );
  14885. this.referencePosition.copy( source.referencePosition );
  14886. this.nearDistance = source.nearDistance;
  14887. this.farDistance = source.farDistance;
  14888. this.skinning = source.skinning;
  14889. this.morphTargets = source.morphTargets;
  14890. this.map = source.map;
  14891. this.alphaMap = source.alphaMap;
  14892. this.displacementMap = source.displacementMap;
  14893. this.displacementScale = source.displacementScale;
  14894. this.displacementBias = source.displacementBias;
  14895. return this;
  14896. };
  14897. /**
  14898. * @author alteredq / http://alteredqualia.com/
  14899. * @author mrdoob / http://mrdoob.com/
  14900. */
  14901. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  14902. var _frustum = new Frustum(),
  14903. _projScreenMatrix = new Matrix4(),
  14904. _shadowMapSize = new Vector2(),
  14905. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  14906. _lookTarget = new Vector3(),
  14907. _lightPositionWorld = new Vector3(),
  14908. _MorphingFlag = 1,
  14909. _SkinningFlag = 2,
  14910. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  14911. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  14912. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  14913. _materialCache = {};
  14914. var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  14915. var cubeDirections = [
  14916. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  14917. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  14918. ];
  14919. var cubeUps = [
  14920. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  14921. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  14922. ];
  14923. var cube2DViewPorts = [
  14924. new Vector4(), new Vector4(), new Vector4(),
  14925. new Vector4(), new Vector4(), new Vector4()
  14926. ];
  14927. // init
  14928. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  14929. var useMorphing = ( i & _MorphingFlag ) !== 0;
  14930. var useSkinning = ( i & _SkinningFlag ) !== 0;
  14931. var depthMaterial = new MeshDepthMaterial( {
  14932. depthPacking: RGBADepthPacking,
  14933. morphTargets: useMorphing,
  14934. skinning: useSkinning
  14935. } );
  14936. _depthMaterials[ i ] = depthMaterial;
  14937. //
  14938. var distanceMaterial = new MeshDistanceMaterial( {
  14939. morphTargets: useMorphing,
  14940. skinning: useSkinning
  14941. } );
  14942. _distanceMaterials[ i ] = distanceMaterial;
  14943. }
  14944. //
  14945. var scope = this;
  14946. this.enabled = false;
  14947. this.autoUpdate = true;
  14948. this.needsUpdate = false;
  14949. this.type = PCFShadowMap;
  14950. this.render = function ( lights, scene, camera ) {
  14951. if ( scope.enabled === false ) return;
  14952. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  14953. if ( lights.length === 0 ) return;
  14954. // TODO Clean up (needed in case of contextlost)
  14955. var _gl = _renderer.context;
  14956. var _state = _renderer.state;
  14957. // Set GL state for depth map.
  14958. _state.disable( _gl.BLEND );
  14959. _state.buffers.color.setClear( 1, 1, 1, 1 );
  14960. _state.buffers.depth.setTest( true );
  14961. _state.setScissorTest( false );
  14962. // render depth map
  14963. var faceCount;
  14964. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14965. var light = lights[ i ];
  14966. var shadow = light.shadow;
  14967. var isPointLight = light && light.isPointLight;
  14968. if ( shadow === undefined ) {
  14969. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  14970. continue;
  14971. }
  14972. var shadowCamera = shadow.camera;
  14973. _shadowMapSize.copy( shadow.mapSize );
  14974. _shadowMapSize.min( _maxShadowMapSize );
  14975. if ( isPointLight ) {
  14976. var vpWidth = _shadowMapSize.x;
  14977. var vpHeight = _shadowMapSize.y;
  14978. // These viewports map a cube-map onto a 2D texture with the
  14979. // following orientation:
  14980. //
  14981. // xzXZ
  14982. // y Y
  14983. //
  14984. // X - Positive x direction
  14985. // x - Negative x direction
  14986. // Y - Positive y direction
  14987. // y - Negative y direction
  14988. // Z - Positive z direction
  14989. // z - Negative z direction
  14990. // positive X
  14991. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  14992. // negative X
  14993. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  14994. // positive Z
  14995. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  14996. // negative Z
  14997. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  14998. // positive Y
  14999. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  15000. // negative Y
  15001. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  15002. _shadowMapSize.x *= 4.0;
  15003. _shadowMapSize.y *= 2.0;
  15004. }
  15005. if ( shadow.map === null ) {
  15006. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  15007. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  15008. shadow.map.texture.name = light.name + ".shadowMap";
  15009. shadowCamera.updateProjectionMatrix();
  15010. }
  15011. if ( shadow.isSpotLightShadow ) {
  15012. shadow.update( light );
  15013. }
  15014. var shadowMap = shadow.map;
  15015. var shadowMatrix = shadow.matrix;
  15016. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  15017. shadowCamera.position.copy( _lightPositionWorld );
  15018. if ( isPointLight ) {
  15019. faceCount = 6;
  15020. // for point lights we set the shadow matrix to be a translation-only matrix
  15021. // equal to inverse of the light's position
  15022. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  15023. } else {
  15024. faceCount = 1;
  15025. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  15026. shadowCamera.lookAt( _lookTarget );
  15027. shadowCamera.updateMatrixWorld();
  15028. // compute shadow matrix
  15029. shadowMatrix.set(
  15030. 0.5, 0.0, 0.0, 0.5,
  15031. 0.0, 0.5, 0.0, 0.5,
  15032. 0.0, 0.0, 0.5, 0.5,
  15033. 0.0, 0.0, 0.0, 1.0
  15034. );
  15035. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  15036. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  15037. }
  15038. _renderer.setRenderTarget( shadowMap );
  15039. _renderer.clear();
  15040. // render shadow map for each cube face (if omni-directional) or
  15041. // run a single pass if not
  15042. for ( var face = 0; face < faceCount; face ++ ) {
  15043. if ( isPointLight ) {
  15044. _lookTarget.copy( shadowCamera.position );
  15045. _lookTarget.add( cubeDirections[ face ] );
  15046. shadowCamera.up.copy( cubeUps[ face ] );
  15047. shadowCamera.lookAt( _lookTarget );
  15048. shadowCamera.updateMatrixWorld();
  15049. var vpDimensions = cube2DViewPorts[ face ];
  15050. _state.viewport( vpDimensions );
  15051. }
  15052. // update camera matrices and frustum
  15053. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  15054. _frustum.setFromMatrix( _projScreenMatrix );
  15055. // set object matrices & frustum culling
  15056. renderObject( scene, camera, shadowCamera, isPointLight );
  15057. }
  15058. }
  15059. scope.needsUpdate = false;
  15060. };
  15061. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  15062. var geometry = object.geometry;
  15063. var result = null;
  15064. var materialVariants = _depthMaterials;
  15065. var customMaterial = object.customDepthMaterial;
  15066. if ( isPointLight ) {
  15067. materialVariants = _distanceMaterials;
  15068. customMaterial = object.customDistanceMaterial;
  15069. }
  15070. if ( ! customMaterial ) {
  15071. var useMorphing = false;
  15072. if ( material.morphTargets ) {
  15073. if ( geometry && geometry.isBufferGeometry ) {
  15074. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  15075. } else if ( geometry && geometry.isGeometry ) {
  15076. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  15077. }
  15078. }
  15079. if ( object.isSkinnedMesh && material.skinning === false ) {
  15080. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  15081. }
  15082. var useSkinning = object.isSkinnedMesh && material.skinning;
  15083. var variantIndex = 0;
  15084. if ( useMorphing ) variantIndex |= _MorphingFlag;
  15085. if ( useSkinning ) variantIndex |= _SkinningFlag;
  15086. result = materialVariants[ variantIndex ];
  15087. } else {
  15088. result = customMaterial;
  15089. }
  15090. if ( _renderer.localClippingEnabled &&
  15091. material.clipShadows === true &&
  15092. material.clippingPlanes.length !== 0 ) {
  15093. // in this case we need a unique material instance reflecting the
  15094. // appropriate state
  15095. var keyA = result.uuid, keyB = material.uuid;
  15096. var materialsForVariant = _materialCache[ keyA ];
  15097. if ( materialsForVariant === undefined ) {
  15098. materialsForVariant = {};
  15099. _materialCache[ keyA ] = materialsForVariant;
  15100. }
  15101. var cachedMaterial = materialsForVariant[ keyB ];
  15102. if ( cachedMaterial === undefined ) {
  15103. cachedMaterial = result.clone();
  15104. materialsForVariant[ keyB ] = cachedMaterial;
  15105. }
  15106. result = cachedMaterial;
  15107. }
  15108. result.visible = material.visible;
  15109. result.wireframe = material.wireframe;
  15110. result.side = ( material.shadowSide != null ) ? material.shadowSide : shadowSide[ material.side ];
  15111. result.clipShadows = material.clipShadows;
  15112. result.clippingPlanes = material.clippingPlanes;
  15113. result.clipIntersection = material.clipIntersection;
  15114. result.wireframeLinewidth = material.wireframeLinewidth;
  15115. result.linewidth = material.linewidth;
  15116. if ( isPointLight && result.isMeshDistanceMaterial ) {
  15117. result.referencePosition.copy( lightPositionWorld );
  15118. result.nearDistance = shadowCameraNear;
  15119. result.farDistance = shadowCameraFar;
  15120. }
  15121. return result;
  15122. }
  15123. function renderObject( object, camera, shadowCamera, isPointLight ) {
  15124. if ( object.visible === false ) return;
  15125. var visible = object.layers.test( camera.layers );
  15126. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  15127. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  15128. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  15129. var geometry = _objects.update( object );
  15130. var material = object.material;
  15131. if ( Array.isArray( material ) ) {
  15132. var groups = geometry.groups;
  15133. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  15134. var group = groups[ k ];
  15135. var groupMaterial = material[ group.materialIndex ];
  15136. if ( groupMaterial && groupMaterial.visible ) {
  15137. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  15138. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  15139. }
  15140. }
  15141. } else if ( material.visible ) {
  15142. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  15143. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  15144. }
  15145. }
  15146. }
  15147. var children = object.children;
  15148. for ( var i = 0, l = children.length; i < l; i ++ ) {
  15149. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  15150. }
  15151. }
  15152. }
  15153. /**
  15154. * @author mrdoob / http://mrdoob.com/
  15155. */
  15156. function WebGLState( gl, extensions, utils, capabilities ) {
  15157. function ColorBuffer() {
  15158. var locked = false;
  15159. var color = new Vector4();
  15160. var currentColorMask = null;
  15161. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  15162. return {
  15163. setMask: function ( colorMask ) {
  15164. if ( currentColorMask !== colorMask && ! locked ) {
  15165. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  15166. currentColorMask = colorMask;
  15167. }
  15168. },
  15169. setLocked: function ( lock ) {
  15170. locked = lock;
  15171. },
  15172. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  15173. if ( premultipliedAlpha === true ) {
  15174. r *= a; g *= a; b *= a;
  15175. }
  15176. color.set( r, g, b, a );
  15177. if ( currentColorClear.equals( color ) === false ) {
  15178. gl.clearColor( r, g, b, a );
  15179. currentColorClear.copy( color );
  15180. }
  15181. },
  15182. reset: function () {
  15183. locked = false;
  15184. currentColorMask = null;
  15185. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  15186. }
  15187. };
  15188. }
  15189. function DepthBuffer() {
  15190. var locked = false;
  15191. var currentDepthMask = null;
  15192. var currentDepthFunc = null;
  15193. var currentDepthClear = null;
  15194. return {
  15195. setTest: function ( depthTest ) {
  15196. if ( depthTest ) {
  15197. enable( gl.DEPTH_TEST );
  15198. } else {
  15199. disable( gl.DEPTH_TEST );
  15200. }
  15201. },
  15202. setMask: function ( depthMask ) {
  15203. if ( currentDepthMask !== depthMask && ! locked ) {
  15204. gl.depthMask( depthMask );
  15205. currentDepthMask = depthMask;
  15206. }
  15207. },
  15208. setFunc: function ( depthFunc ) {
  15209. if ( currentDepthFunc !== depthFunc ) {
  15210. if ( depthFunc ) {
  15211. switch ( depthFunc ) {
  15212. case NeverDepth:
  15213. gl.depthFunc( gl.NEVER );
  15214. break;
  15215. case AlwaysDepth:
  15216. gl.depthFunc( gl.ALWAYS );
  15217. break;
  15218. case LessDepth:
  15219. gl.depthFunc( gl.LESS );
  15220. break;
  15221. case LessEqualDepth:
  15222. gl.depthFunc( gl.LEQUAL );
  15223. break;
  15224. case EqualDepth:
  15225. gl.depthFunc( gl.EQUAL );
  15226. break;
  15227. case GreaterEqualDepth:
  15228. gl.depthFunc( gl.GEQUAL );
  15229. break;
  15230. case GreaterDepth:
  15231. gl.depthFunc( gl.GREATER );
  15232. break;
  15233. case NotEqualDepth:
  15234. gl.depthFunc( gl.NOTEQUAL );
  15235. break;
  15236. default:
  15237. gl.depthFunc( gl.LEQUAL );
  15238. }
  15239. } else {
  15240. gl.depthFunc( gl.LEQUAL );
  15241. }
  15242. currentDepthFunc = depthFunc;
  15243. }
  15244. },
  15245. setLocked: function ( lock ) {
  15246. locked = lock;
  15247. },
  15248. setClear: function ( depth ) {
  15249. if ( currentDepthClear !== depth ) {
  15250. gl.clearDepth( depth );
  15251. currentDepthClear = depth;
  15252. }
  15253. },
  15254. reset: function () {
  15255. locked = false;
  15256. currentDepthMask = null;
  15257. currentDepthFunc = null;
  15258. currentDepthClear = null;
  15259. }
  15260. };
  15261. }
  15262. function StencilBuffer() {
  15263. var locked = false;
  15264. var currentStencilMask = null;
  15265. var currentStencilFunc = null;
  15266. var currentStencilRef = null;
  15267. var currentStencilFuncMask = null;
  15268. var currentStencilFail = null;
  15269. var currentStencilZFail = null;
  15270. var currentStencilZPass = null;
  15271. var currentStencilClear = null;
  15272. return {
  15273. setTest: function ( stencilTest ) {
  15274. if ( stencilTest ) {
  15275. enable( gl.STENCIL_TEST );
  15276. } else {
  15277. disable( gl.STENCIL_TEST );
  15278. }
  15279. },
  15280. setMask: function ( stencilMask ) {
  15281. if ( currentStencilMask !== stencilMask && ! locked ) {
  15282. gl.stencilMask( stencilMask );
  15283. currentStencilMask = stencilMask;
  15284. }
  15285. },
  15286. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  15287. if ( currentStencilFunc !== stencilFunc ||
  15288. currentStencilRef !== stencilRef ||
  15289. currentStencilFuncMask !== stencilMask ) {
  15290. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  15291. currentStencilFunc = stencilFunc;
  15292. currentStencilRef = stencilRef;
  15293. currentStencilFuncMask = stencilMask;
  15294. }
  15295. },
  15296. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  15297. if ( currentStencilFail !== stencilFail ||
  15298. currentStencilZFail !== stencilZFail ||
  15299. currentStencilZPass !== stencilZPass ) {
  15300. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  15301. currentStencilFail = stencilFail;
  15302. currentStencilZFail = stencilZFail;
  15303. currentStencilZPass = stencilZPass;
  15304. }
  15305. },
  15306. setLocked: function ( lock ) {
  15307. locked = lock;
  15308. },
  15309. setClear: function ( stencil ) {
  15310. if ( currentStencilClear !== stencil ) {
  15311. gl.clearStencil( stencil );
  15312. currentStencilClear = stencil;
  15313. }
  15314. },
  15315. reset: function () {
  15316. locked = false;
  15317. currentStencilMask = null;
  15318. currentStencilFunc = null;
  15319. currentStencilRef = null;
  15320. currentStencilFuncMask = null;
  15321. currentStencilFail = null;
  15322. currentStencilZFail = null;
  15323. currentStencilZPass = null;
  15324. currentStencilClear = null;
  15325. }
  15326. };
  15327. }
  15328. //
  15329. var colorBuffer = new ColorBuffer();
  15330. var depthBuffer = new DepthBuffer();
  15331. var stencilBuffer = new StencilBuffer();
  15332. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  15333. var newAttributes = new Uint8Array( maxVertexAttributes );
  15334. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  15335. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  15336. var enabledCapabilities = {};
  15337. var compressedTextureFormats = null;
  15338. var currentProgram = null;
  15339. var currentBlending = null;
  15340. var currentBlendEquation = null;
  15341. var currentBlendSrc = null;
  15342. var currentBlendDst = null;
  15343. var currentBlendEquationAlpha = null;
  15344. var currentBlendSrcAlpha = null;
  15345. var currentBlendDstAlpha = null;
  15346. var currentPremultipledAlpha = false;
  15347. var currentFlipSided = null;
  15348. var currentCullFace = null;
  15349. var currentLineWidth = null;
  15350. var currentPolygonOffsetFactor = null;
  15351. var currentPolygonOffsetUnits = null;
  15352. var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  15353. var lineWidthAvailable = false;
  15354. var version = 0;
  15355. var glVersion = gl.getParameter( gl.VERSION );
  15356. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  15357. version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
  15358. lineWidthAvailable = ( version >= 1.0 );
  15359. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  15360. version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
  15361. lineWidthAvailable = ( version >= 2.0 );
  15362. }
  15363. var currentTextureSlot = null;
  15364. var currentBoundTextures = {};
  15365. var currentScissor = new Vector4();
  15366. var currentViewport = new Vector4();
  15367. function createTexture( type, target, count ) {
  15368. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  15369. var texture = gl.createTexture();
  15370. gl.bindTexture( type, texture );
  15371. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  15372. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  15373. for ( var i = 0; i < count; i ++ ) {
  15374. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  15375. }
  15376. return texture;
  15377. }
  15378. var emptyTextures = {};
  15379. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  15380. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  15381. // init
  15382. colorBuffer.setClear( 0, 0, 0, 1 );
  15383. depthBuffer.setClear( 1 );
  15384. stencilBuffer.setClear( 0 );
  15385. enable( gl.DEPTH_TEST );
  15386. depthBuffer.setFunc( LessEqualDepth );
  15387. setFlipSided( false );
  15388. setCullFace( CullFaceBack );
  15389. enable( gl.CULL_FACE );
  15390. enable( gl.BLEND );
  15391. setBlending( NormalBlending );
  15392. //
  15393. function initAttributes() {
  15394. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  15395. newAttributes[ i ] = 0;
  15396. }
  15397. }
  15398. function enableAttribute( attribute ) {
  15399. enableAttributeAndDivisor( attribute, 0 );
  15400. }
  15401. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  15402. newAttributes[ attribute ] = 1;
  15403. if ( enabledAttributes[ attribute ] === 0 ) {
  15404. gl.enableVertexAttribArray( attribute );
  15405. enabledAttributes[ attribute ] = 1;
  15406. }
  15407. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  15408. var extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  15409. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  15410. attributeDivisors[ attribute ] = meshPerAttribute;
  15411. }
  15412. }
  15413. function disableUnusedAttributes() {
  15414. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  15415. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  15416. gl.disableVertexAttribArray( i );
  15417. enabledAttributes[ i ] = 0;
  15418. }
  15419. }
  15420. }
  15421. function enable( id ) {
  15422. if ( enabledCapabilities[ id ] !== true ) {
  15423. gl.enable( id );
  15424. enabledCapabilities[ id ] = true;
  15425. }
  15426. }
  15427. function disable( id ) {
  15428. if ( enabledCapabilities[ id ] !== false ) {
  15429. gl.disable( id );
  15430. enabledCapabilities[ id ] = false;
  15431. }
  15432. }
  15433. function getCompressedTextureFormats() {
  15434. if ( compressedTextureFormats === null ) {
  15435. compressedTextureFormats = [];
  15436. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  15437. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  15438. extensions.get( 'WEBGL_compressed_texture_etc1' ) ||
  15439. extensions.get( 'WEBGL_compressed_texture_astc' ) ) {
  15440. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  15441. for ( var i = 0; i < formats.length; i ++ ) {
  15442. compressedTextureFormats.push( formats[ i ] );
  15443. }
  15444. }
  15445. }
  15446. return compressedTextureFormats;
  15447. }
  15448. function useProgram( program ) {
  15449. if ( currentProgram !== program ) {
  15450. gl.useProgram( program );
  15451. currentProgram = program;
  15452. return true;
  15453. }
  15454. return false;
  15455. }
  15456. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  15457. if ( blending !== NoBlending ) {
  15458. enable( gl.BLEND );
  15459. } else {
  15460. disable( gl.BLEND );
  15461. }
  15462. if ( blending !== CustomBlending ) {
  15463. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  15464. switch ( blending ) {
  15465. case AdditiveBlending:
  15466. if ( premultipliedAlpha ) {
  15467. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15468. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  15469. } else {
  15470. gl.blendEquation( gl.FUNC_ADD );
  15471. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  15472. }
  15473. break;
  15474. case SubtractiveBlending:
  15475. if ( premultipliedAlpha ) {
  15476. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15477. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  15478. } else {
  15479. gl.blendEquation( gl.FUNC_ADD );
  15480. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  15481. }
  15482. break;
  15483. case MultiplyBlending:
  15484. if ( premultipliedAlpha ) {
  15485. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15486. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  15487. } else {
  15488. gl.blendEquation( gl.FUNC_ADD );
  15489. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  15490. }
  15491. break;
  15492. default:
  15493. if ( premultipliedAlpha ) {
  15494. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15495. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  15496. } else {
  15497. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15498. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  15499. }
  15500. }
  15501. }
  15502. currentBlendEquation = null;
  15503. currentBlendSrc = null;
  15504. currentBlendDst = null;
  15505. currentBlendEquationAlpha = null;
  15506. currentBlendSrcAlpha = null;
  15507. currentBlendDstAlpha = null;
  15508. } else {
  15509. blendEquationAlpha = blendEquationAlpha || blendEquation;
  15510. blendSrcAlpha = blendSrcAlpha || blendSrc;
  15511. blendDstAlpha = blendDstAlpha || blendDst;
  15512. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  15513. gl.blendEquationSeparate( utils.convert( blendEquation ), utils.convert( blendEquationAlpha ) );
  15514. currentBlendEquation = blendEquation;
  15515. currentBlendEquationAlpha = blendEquationAlpha;
  15516. }
  15517. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  15518. gl.blendFuncSeparate( utils.convert( blendSrc ), utils.convert( blendDst ), utils.convert( blendSrcAlpha ), utils.convert( blendDstAlpha ) );
  15519. currentBlendSrc = blendSrc;
  15520. currentBlendDst = blendDst;
  15521. currentBlendSrcAlpha = blendSrcAlpha;
  15522. currentBlendDstAlpha = blendDstAlpha;
  15523. }
  15524. }
  15525. currentBlending = blending;
  15526. currentPremultipledAlpha = premultipliedAlpha;
  15527. }
  15528. function setMaterial( material, frontFaceCW ) {
  15529. material.side === DoubleSide
  15530. ? disable( gl.CULL_FACE )
  15531. : enable( gl.CULL_FACE );
  15532. var flipSided = ( material.side === BackSide );
  15533. if ( frontFaceCW ) flipSided = ! flipSided;
  15534. setFlipSided( flipSided );
  15535. ( material.blending === NormalBlending && material.transparent === false )
  15536. ? setBlending( NoBlending )
  15537. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  15538. depthBuffer.setFunc( material.depthFunc );
  15539. depthBuffer.setTest( material.depthTest );
  15540. depthBuffer.setMask( material.depthWrite );
  15541. colorBuffer.setMask( material.colorWrite );
  15542. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  15543. }
  15544. //
  15545. function setFlipSided( flipSided ) {
  15546. if ( currentFlipSided !== flipSided ) {
  15547. if ( flipSided ) {
  15548. gl.frontFace( gl.CW );
  15549. } else {
  15550. gl.frontFace( gl.CCW );
  15551. }
  15552. currentFlipSided = flipSided;
  15553. }
  15554. }
  15555. function setCullFace( cullFace ) {
  15556. if ( cullFace !== CullFaceNone ) {
  15557. enable( gl.CULL_FACE );
  15558. if ( cullFace !== currentCullFace ) {
  15559. if ( cullFace === CullFaceBack ) {
  15560. gl.cullFace( gl.BACK );
  15561. } else if ( cullFace === CullFaceFront ) {
  15562. gl.cullFace( gl.FRONT );
  15563. } else {
  15564. gl.cullFace( gl.FRONT_AND_BACK );
  15565. }
  15566. }
  15567. } else {
  15568. disable( gl.CULL_FACE );
  15569. }
  15570. currentCullFace = cullFace;
  15571. }
  15572. function setLineWidth( width ) {
  15573. if ( width !== currentLineWidth ) {
  15574. if ( lineWidthAvailable ) gl.lineWidth( width );
  15575. currentLineWidth = width;
  15576. }
  15577. }
  15578. function setPolygonOffset( polygonOffset, factor, units ) {
  15579. if ( polygonOffset ) {
  15580. enable( gl.POLYGON_OFFSET_FILL );
  15581. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  15582. gl.polygonOffset( factor, units );
  15583. currentPolygonOffsetFactor = factor;
  15584. currentPolygonOffsetUnits = units;
  15585. }
  15586. } else {
  15587. disable( gl.POLYGON_OFFSET_FILL );
  15588. }
  15589. }
  15590. function setScissorTest( scissorTest ) {
  15591. if ( scissorTest ) {
  15592. enable( gl.SCISSOR_TEST );
  15593. } else {
  15594. disable( gl.SCISSOR_TEST );
  15595. }
  15596. }
  15597. // texture
  15598. function activeTexture( webglSlot ) {
  15599. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  15600. if ( currentTextureSlot !== webglSlot ) {
  15601. gl.activeTexture( webglSlot );
  15602. currentTextureSlot = webglSlot;
  15603. }
  15604. }
  15605. function bindTexture( webglType, webglTexture ) {
  15606. if ( currentTextureSlot === null ) {
  15607. activeTexture();
  15608. }
  15609. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  15610. if ( boundTexture === undefined ) {
  15611. boundTexture = { type: undefined, texture: undefined };
  15612. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  15613. }
  15614. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  15615. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  15616. boundTexture.type = webglType;
  15617. boundTexture.texture = webglTexture;
  15618. }
  15619. }
  15620. function compressedTexImage2D() {
  15621. try {
  15622. gl.compressedTexImage2D.apply( gl, arguments );
  15623. } catch ( error ) {
  15624. console.error( 'THREE.WebGLState:', error );
  15625. }
  15626. }
  15627. function texImage2D() {
  15628. try {
  15629. gl.texImage2D.apply( gl, arguments );
  15630. } catch ( error ) {
  15631. console.error( 'THREE.WebGLState:', error );
  15632. }
  15633. }
  15634. //
  15635. function scissor( scissor ) {
  15636. if ( currentScissor.equals( scissor ) === false ) {
  15637. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  15638. currentScissor.copy( scissor );
  15639. }
  15640. }
  15641. function viewport( viewport ) {
  15642. if ( currentViewport.equals( viewport ) === false ) {
  15643. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  15644. currentViewport.copy( viewport );
  15645. }
  15646. }
  15647. //
  15648. function reset() {
  15649. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  15650. if ( enabledAttributes[ i ] === 1 ) {
  15651. gl.disableVertexAttribArray( i );
  15652. enabledAttributes[ i ] = 0;
  15653. }
  15654. }
  15655. enabledCapabilities = {};
  15656. compressedTextureFormats = null;
  15657. currentTextureSlot = null;
  15658. currentBoundTextures = {};
  15659. currentProgram = null;
  15660. currentBlending = null;
  15661. currentFlipSided = null;
  15662. currentCullFace = null;
  15663. colorBuffer.reset();
  15664. depthBuffer.reset();
  15665. stencilBuffer.reset();
  15666. }
  15667. return {
  15668. buffers: {
  15669. color: colorBuffer,
  15670. depth: depthBuffer,
  15671. stencil: stencilBuffer
  15672. },
  15673. initAttributes: initAttributes,
  15674. enableAttribute: enableAttribute,
  15675. enableAttributeAndDivisor: enableAttributeAndDivisor,
  15676. disableUnusedAttributes: disableUnusedAttributes,
  15677. enable: enable,
  15678. disable: disable,
  15679. getCompressedTextureFormats: getCompressedTextureFormats,
  15680. useProgram: useProgram,
  15681. setBlending: setBlending,
  15682. setMaterial: setMaterial,
  15683. setFlipSided: setFlipSided,
  15684. setCullFace: setCullFace,
  15685. setLineWidth: setLineWidth,
  15686. setPolygonOffset: setPolygonOffset,
  15687. setScissorTest: setScissorTest,
  15688. activeTexture: activeTexture,
  15689. bindTexture: bindTexture,
  15690. compressedTexImage2D: compressedTexImage2D,
  15691. texImage2D: texImage2D,
  15692. scissor: scissor,
  15693. viewport: viewport,
  15694. reset: reset
  15695. };
  15696. }
  15697. /**
  15698. * @author mrdoob / http://mrdoob.com/
  15699. */
  15700. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  15701. var _videoTextures = {};
  15702. var _canvas;
  15703. //
  15704. function clampToMaxSize( image, maxSize ) {
  15705. if ( image.width > maxSize || image.height > maxSize ) {
  15706. if ( 'data' in image ) {
  15707. console.warn( 'THREE.WebGLRenderer: image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  15708. return;
  15709. }
  15710. // Warning: Scaling through the canvas will only work with images that use
  15711. // premultiplied alpha.
  15712. var scale = maxSize / Math.max( image.width, image.height );
  15713. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  15714. canvas.width = Math.floor( image.width * scale );
  15715. canvas.height = Math.floor( image.height * scale );
  15716. var context = canvas.getContext( '2d' );
  15717. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  15718. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height );
  15719. return canvas;
  15720. }
  15721. return image;
  15722. }
  15723. function isPowerOfTwo( image ) {
  15724. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  15725. }
  15726. function makePowerOfTwo( image ) {
  15727. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof ImageBitmap ) {
  15728. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  15729. _canvas.width = _Math.floorPowerOfTwo( image.width );
  15730. _canvas.height = _Math.floorPowerOfTwo( image.height );
  15731. var context = _canvas.getContext( '2d' );
  15732. context.drawImage( image, 0, 0, _canvas.width, _canvas.height );
  15733. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + _canvas.width + 'x' + _canvas.height );
  15734. return _canvas;
  15735. }
  15736. return image;
  15737. }
  15738. function textureNeedsPowerOfTwo( texture ) {
  15739. if ( capabilities.isWebGL2 ) return false;
  15740. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  15741. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  15742. }
  15743. function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) {
  15744. return texture.generateMipmaps && isPowerOfTwo &&
  15745. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  15746. }
  15747. function generateMipmap( target, texture, width, height ) {
  15748. _gl.generateMipmap( target );
  15749. var textureProperties = properties.get( texture );
  15750. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  15751. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  15752. }
  15753. function getInternalFormat( glFormat, glType ) {
  15754. if ( ! capabilities.isWebGL2 ) return glFormat;
  15755. if ( glFormat === _gl.RGB ) {
  15756. if ( glType === _gl.FLOAT ) return _gl.RGB32F;
  15757. if ( glType === _gl.HALF_FLOAT ) return _gl.RGB16F;
  15758. if ( glType === _gl.UNSIGNED_BYTE ) return _gl.RGB8;
  15759. }
  15760. if ( glFormat === _gl.RGBA ) {
  15761. if ( glType === _gl.FLOAT ) return _gl.RGBA32F;
  15762. if ( glType === _gl.HALF_FLOAT ) return _gl.RGBA16F;
  15763. if ( glType === _gl.UNSIGNED_BYTE ) return _gl.RGBA8;
  15764. }
  15765. return glFormat;
  15766. }
  15767. // Fallback filters for non-power-of-2 textures
  15768. function filterFallback( f ) {
  15769. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  15770. return _gl.NEAREST;
  15771. }
  15772. return _gl.LINEAR;
  15773. }
  15774. //
  15775. function onTextureDispose( event ) {
  15776. var texture = event.target;
  15777. texture.removeEventListener( 'dispose', onTextureDispose );
  15778. deallocateTexture( texture );
  15779. if ( texture.isVideoTexture ) {
  15780. delete _videoTextures[ texture.id ];
  15781. }
  15782. info.memory.textures --;
  15783. }
  15784. function onRenderTargetDispose( event ) {
  15785. var renderTarget = event.target;
  15786. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  15787. deallocateRenderTarget( renderTarget );
  15788. info.memory.textures --;
  15789. }
  15790. //
  15791. function deallocateTexture( texture ) {
  15792. var textureProperties = properties.get( texture );
  15793. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  15794. // cube texture
  15795. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  15796. } else {
  15797. // 2D texture
  15798. if ( textureProperties.__webglInit === undefined ) return;
  15799. _gl.deleteTexture( textureProperties.__webglTexture );
  15800. }
  15801. // remove all webgl properties
  15802. properties.remove( texture );
  15803. }
  15804. function deallocateRenderTarget( renderTarget ) {
  15805. var renderTargetProperties = properties.get( renderTarget );
  15806. var textureProperties = properties.get( renderTarget.texture );
  15807. if ( ! renderTarget ) return;
  15808. if ( textureProperties.__webglTexture !== undefined ) {
  15809. _gl.deleteTexture( textureProperties.__webglTexture );
  15810. }
  15811. if ( renderTarget.depthTexture ) {
  15812. renderTarget.depthTexture.dispose();
  15813. }
  15814. if ( renderTarget.isWebGLRenderTargetCube ) {
  15815. for ( var i = 0; i < 6; i ++ ) {
  15816. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  15817. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  15818. }
  15819. } else {
  15820. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  15821. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  15822. }
  15823. properties.remove( renderTarget.texture );
  15824. properties.remove( renderTarget );
  15825. }
  15826. //
  15827. function setTexture2D( texture, slot ) {
  15828. var textureProperties = properties.get( texture );
  15829. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  15830. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  15831. var image = texture.image;
  15832. if ( image === undefined ) {
  15833. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  15834. } else if ( image.complete === false ) {
  15835. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  15836. } else {
  15837. uploadTexture( textureProperties, texture, slot );
  15838. return;
  15839. }
  15840. }
  15841. state.activeTexture( _gl.TEXTURE0 + slot );
  15842. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15843. }
  15844. function setTextureCube( texture, slot ) {
  15845. var textureProperties = properties.get( texture );
  15846. if ( texture.image.length === 6 ) {
  15847. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  15848. if ( ! textureProperties.__image__webglTextureCube ) {
  15849. texture.addEventListener( 'dispose', onTextureDispose );
  15850. textureProperties.__image__webglTextureCube = _gl.createTexture();
  15851. info.memory.textures ++;
  15852. }
  15853. state.activeTexture( _gl.TEXTURE0 + slot );
  15854. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  15855. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15856. var isCompressed = ( texture && texture.isCompressedTexture );
  15857. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  15858. var cubeImage = [];
  15859. for ( var i = 0; i < 6; i ++ ) {
  15860. if ( ! isCompressed && ! isDataTexture ) {
  15861. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  15862. } else {
  15863. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  15864. }
  15865. }
  15866. var image = cubeImage[ 0 ],
  15867. isPowerOfTwoImage = isPowerOfTwo( image ),
  15868. glFormat = utils.convert( texture.format ),
  15869. glType = utils.convert( texture.type ),
  15870. glInternalFormat = getInternalFormat( glFormat, glType );
  15871. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  15872. for ( var i = 0; i < 6; i ++ ) {
  15873. if ( ! isCompressed ) {
  15874. if ( isDataTexture ) {
  15875. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  15876. } else {
  15877. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  15878. }
  15879. } else {
  15880. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15881. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15882. mipmap = mipmaps[ j ];
  15883. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  15884. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  15885. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15886. } else {
  15887. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  15888. }
  15889. } else {
  15890. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15891. }
  15892. }
  15893. }
  15894. }
  15895. if ( ! isCompressed ) {
  15896. textureProperties.__maxMipLevel = 0;
  15897. } else {
  15898. textureProperties.__maxMipLevel = mipmaps.length - 1;
  15899. }
  15900. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  15901. // We assume images for cube map have the same size.
  15902. generateMipmap( _gl.TEXTURE_CUBE_MAP, texture, image.width, image.height );
  15903. }
  15904. textureProperties.__version = texture.version;
  15905. if ( texture.onUpdate ) texture.onUpdate( texture );
  15906. } else {
  15907. state.activeTexture( _gl.TEXTURE0 + slot );
  15908. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  15909. }
  15910. }
  15911. }
  15912. function setTextureCubeDynamic( texture, slot ) {
  15913. state.activeTexture( _gl.TEXTURE0 + slot );
  15914. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  15915. }
  15916. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  15917. var extension;
  15918. if ( isPowerOfTwoImage ) {
  15919. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, utils.convert( texture.wrapS ) );
  15920. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, utils.convert( texture.wrapT ) );
  15921. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, utils.convert( texture.magFilter ) );
  15922. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, utils.convert( texture.minFilter ) );
  15923. } else {
  15924. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15925. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15926. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  15927. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  15928. }
  15929. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15930. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15931. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  15932. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  15933. }
  15934. }
  15935. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  15936. if ( extension ) {
  15937. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  15938. if ( texture.type === HalfFloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;
  15939. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  15940. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  15941. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  15942. }
  15943. }
  15944. }
  15945. function uploadTexture( textureProperties, texture, slot ) {
  15946. if ( textureProperties.__webglInit === undefined ) {
  15947. textureProperties.__webglInit = true;
  15948. texture.addEventListener( 'dispose', onTextureDispose );
  15949. textureProperties.__webglTexture = _gl.createTexture();
  15950. info.memory.textures ++;
  15951. }
  15952. state.activeTexture( _gl.TEXTURE0 + slot );
  15953. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15954. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15955. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15956. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15957. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  15958. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  15959. image = makePowerOfTwo( image );
  15960. }
  15961. var isPowerOfTwoImage = isPowerOfTwo( image ),
  15962. glFormat = utils.convert( texture.format ),
  15963. glType = utils.convert( texture.type ),
  15964. glInternalFormat = getInternalFormat( glFormat, glType );
  15965. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  15966. var mipmap, mipmaps = texture.mipmaps;
  15967. if ( texture.isDepthTexture ) {
  15968. // populate depth texture with dummy data
  15969. glInternalFormat = _gl.DEPTH_COMPONENT;
  15970. if ( texture.type === FloatType ) {
  15971. if ( ! capabilities.isWebGL2 ) throw new Error( 'Float Depth Texture only supported in WebGL2.0' );
  15972. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  15973. } else if ( capabilities.isWebGL2 ) {
  15974. // WebGL 2.0 requires signed internalformat for glTexImage2D
  15975. glInternalFormat = _gl.DEPTH_COMPONENT16;
  15976. }
  15977. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  15978. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  15979. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  15980. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15981. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  15982. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  15983. texture.type = UnsignedShortType;
  15984. glType = utils.convert( texture.type );
  15985. }
  15986. }
  15987. // Depth stencil textures need the DEPTH_STENCIL internal format
  15988. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15989. if ( texture.format === DepthStencilFormat ) {
  15990. glInternalFormat = _gl.DEPTH_STENCIL;
  15991. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  15992. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  15993. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15994. if ( texture.type !== UnsignedInt248Type ) {
  15995. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  15996. texture.type = UnsignedInt248Type;
  15997. glType = utils.convert( texture.type );
  15998. }
  15999. }
  16000. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  16001. } else if ( texture.isDataTexture ) {
  16002. // use manually created mipmaps if available
  16003. // if there are no manual mipmaps
  16004. // set 0 level mipmap and then use GL to generate other mipmap levels
  16005. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  16006. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16007. mipmap = mipmaps[ i ];
  16008. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16009. }
  16010. texture.generateMipmaps = false;
  16011. textureProperties.__maxMipLevel = mipmaps.length - 1;
  16012. } else {
  16013. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  16014. textureProperties.__maxMipLevel = 0;
  16015. }
  16016. } else if ( texture.isCompressedTexture ) {
  16017. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16018. mipmap = mipmaps[ i ];
  16019. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  16020. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16021. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16022. } else {
  16023. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  16024. }
  16025. } else {
  16026. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16027. }
  16028. }
  16029. textureProperties.__maxMipLevel = mipmaps.length - 1;
  16030. } else {
  16031. // regular Texture (image, video, canvas)
  16032. // use manually created mipmaps if available
  16033. // if there are no manual mipmaps
  16034. // set 0 level mipmap and then use GL to generate other mipmap levels
  16035. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  16036. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16037. mipmap = mipmaps[ i ];
  16038. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  16039. }
  16040. texture.generateMipmaps = false;
  16041. textureProperties.__maxMipLevel = mipmaps.length - 1;
  16042. } else {
  16043. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  16044. textureProperties.__maxMipLevel = 0;
  16045. }
  16046. }
  16047. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  16048. generateMipmap( _gl.TEXTURE_2D, texture, image.width, image.height );
  16049. }
  16050. textureProperties.__version = texture.version;
  16051. if ( texture.onUpdate ) texture.onUpdate( texture );
  16052. }
  16053. // Render targets
  16054. // Setup storage for target texture and bind it to correct framebuffer
  16055. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  16056. var glFormat = utils.convert( renderTarget.texture.format );
  16057. var glType = utils.convert( renderTarget.texture.type );
  16058. var glInternalFormat = getInternalFormat( glFormat, glType );
  16059. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16060. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16061. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  16062. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16063. }
  16064. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  16065. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  16066. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  16067. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16068. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  16069. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16070. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16071. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  16072. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16073. } else {
  16074. // FIXME: We don't support !depth !stencil
  16075. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  16076. }
  16077. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  16078. }
  16079. // Setup resources for a Depth Texture for a FBO (needs an extension)
  16080. function setupDepthTexture( framebuffer, renderTarget ) {
  16081. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  16082. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  16083. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16084. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  16085. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  16086. }
  16087. // upload an empty depth texture with framebuffer size
  16088. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  16089. renderTarget.depthTexture.image.width !== renderTarget.width ||
  16090. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  16091. renderTarget.depthTexture.image.width = renderTarget.width;
  16092. renderTarget.depthTexture.image.height = renderTarget.height;
  16093. renderTarget.depthTexture.needsUpdate = true;
  16094. }
  16095. setTexture2D( renderTarget.depthTexture, 0 );
  16096. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  16097. if ( renderTarget.depthTexture.format === DepthFormat ) {
  16098. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  16099. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  16100. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  16101. } else {
  16102. throw new Error( 'Unknown depthTexture format' );
  16103. }
  16104. }
  16105. // Setup GL resources for a non-texture depth buffer
  16106. function setupDepthRenderbuffer( renderTarget ) {
  16107. var renderTargetProperties = properties.get( renderTarget );
  16108. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  16109. if ( renderTarget.depthTexture ) {
  16110. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  16111. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  16112. } else {
  16113. if ( isCube ) {
  16114. renderTargetProperties.__webglDepthbuffer = [];
  16115. for ( var i = 0; i < 6; i ++ ) {
  16116. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  16117. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  16118. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  16119. }
  16120. } else {
  16121. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  16122. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  16123. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  16124. }
  16125. }
  16126. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16127. }
  16128. // Set up GL resources for the render target
  16129. function setupRenderTarget( renderTarget ) {
  16130. var renderTargetProperties = properties.get( renderTarget );
  16131. var textureProperties = properties.get( renderTarget.texture );
  16132. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  16133. textureProperties.__webglTexture = _gl.createTexture();
  16134. info.memory.textures ++;
  16135. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  16136. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  16137. // Setup framebuffer
  16138. if ( isCube ) {
  16139. renderTargetProperties.__webglFramebuffer = [];
  16140. for ( var i = 0; i < 6; i ++ ) {
  16141. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  16142. }
  16143. } else {
  16144. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  16145. }
  16146. // Setup color buffer
  16147. if ( isCube ) {
  16148. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  16149. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  16150. for ( var i = 0; i < 6; i ++ ) {
  16151. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  16152. }
  16153. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) {
  16154. generateMipmap( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, renderTarget.width, renderTarget.height );
  16155. }
  16156. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  16157. } else {
  16158. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16159. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  16160. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  16161. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) {
  16162. generateMipmap( _gl.TEXTURE_2D, renderTarget.texture, renderTarget.width, renderTarget.height );
  16163. }
  16164. state.bindTexture( _gl.TEXTURE_2D, null );
  16165. }
  16166. // Setup depth and stencil buffers
  16167. if ( renderTarget.depthBuffer ) {
  16168. setupDepthRenderbuffer( renderTarget );
  16169. }
  16170. }
  16171. function updateRenderTargetMipmap( renderTarget ) {
  16172. var texture = renderTarget.texture;
  16173. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  16174. if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) {
  16175. var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  16176. var webglTexture = properties.get( texture ).__webglTexture;
  16177. state.bindTexture( target, webglTexture );
  16178. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  16179. state.bindTexture( target, null );
  16180. }
  16181. }
  16182. function updateVideoTexture( texture ) {
  16183. var id = texture.id;
  16184. var frame = info.render.frame;
  16185. // Check the last frame we updated the VideoTexture
  16186. if ( _videoTextures[ id ] !== frame ) {
  16187. _videoTextures[ id ] = frame;
  16188. texture.update();
  16189. }
  16190. }
  16191. this.setTexture2D = setTexture2D;
  16192. this.setTextureCube = setTextureCube;
  16193. this.setTextureCubeDynamic = setTextureCubeDynamic;
  16194. this.setupRenderTarget = setupRenderTarget;
  16195. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  16196. }
  16197. /**
  16198. * @author thespite / http://www.twitter.com/thespite
  16199. */
  16200. function WebGLUtils( gl, extensions, capabilities ) {
  16201. function convert( p ) {
  16202. var extension;
  16203. if ( p === RepeatWrapping ) return gl.REPEAT;
  16204. if ( p === ClampToEdgeWrapping ) return gl.CLAMP_TO_EDGE;
  16205. if ( p === MirroredRepeatWrapping ) return gl.MIRRORED_REPEAT;
  16206. if ( p === NearestFilter ) return gl.NEAREST;
  16207. if ( p === NearestMipMapNearestFilter ) return gl.NEAREST_MIPMAP_NEAREST;
  16208. if ( p === NearestMipMapLinearFilter ) return gl.NEAREST_MIPMAP_LINEAR;
  16209. if ( p === LinearFilter ) return gl.LINEAR;
  16210. if ( p === LinearMipMapNearestFilter ) return gl.LINEAR_MIPMAP_NEAREST;
  16211. if ( p === LinearMipMapLinearFilter ) return gl.LINEAR_MIPMAP_LINEAR;
  16212. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  16213. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  16214. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  16215. if ( p === UnsignedShort565Type ) return gl.UNSIGNED_SHORT_5_6_5;
  16216. if ( p === ByteType ) return gl.BYTE;
  16217. if ( p === ShortType ) return gl.SHORT;
  16218. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  16219. if ( p === IntType ) return gl.INT;
  16220. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  16221. if ( p === FloatType ) return gl.FLOAT;
  16222. if ( p === HalfFloatType ) {
  16223. if ( capabilities.isWebGL2 ) return gl.HALF_FLOAT;
  16224. extension = extensions.get( 'OES_texture_half_float' );
  16225. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  16226. }
  16227. if ( p === AlphaFormat ) return gl.ALPHA;
  16228. if ( p === RGBFormat ) return gl.RGB;
  16229. if ( p === RGBAFormat ) return gl.RGBA;
  16230. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  16231. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  16232. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  16233. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  16234. if ( p === AddEquation ) return gl.FUNC_ADD;
  16235. if ( p === SubtractEquation ) return gl.FUNC_SUBTRACT;
  16236. if ( p === ReverseSubtractEquation ) return gl.FUNC_REVERSE_SUBTRACT;
  16237. if ( p === ZeroFactor ) return gl.ZERO;
  16238. if ( p === OneFactor ) return gl.ONE;
  16239. if ( p === SrcColorFactor ) return gl.SRC_COLOR;
  16240. if ( p === OneMinusSrcColorFactor ) return gl.ONE_MINUS_SRC_COLOR;
  16241. if ( p === SrcAlphaFactor ) return gl.SRC_ALPHA;
  16242. if ( p === OneMinusSrcAlphaFactor ) return gl.ONE_MINUS_SRC_ALPHA;
  16243. if ( p === DstAlphaFactor ) return gl.DST_ALPHA;
  16244. if ( p === OneMinusDstAlphaFactor ) return gl.ONE_MINUS_DST_ALPHA;
  16245. if ( p === DstColorFactor ) return gl.DST_COLOR;
  16246. if ( p === OneMinusDstColorFactor ) return gl.ONE_MINUS_DST_COLOR;
  16247. if ( p === SrcAlphaSaturateFactor ) return gl.SRC_ALPHA_SATURATE;
  16248. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  16249. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  16250. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  16251. if ( extension !== null ) {
  16252. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16253. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16254. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16255. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16256. }
  16257. }
  16258. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  16259. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  16260. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  16261. if ( extension !== null ) {
  16262. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  16263. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  16264. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  16265. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  16266. }
  16267. }
  16268. if ( p === RGB_ETC1_Format ) {
  16269. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  16270. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  16271. }
  16272. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  16273. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  16274. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  16275. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  16276. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  16277. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  16278. if ( extension !== null ) {
  16279. return p;
  16280. }
  16281. }
  16282. if ( p === MinEquation || p === MaxEquation ) {
  16283. if ( capabilities.isWebGL2 ) {
  16284. if ( p === MinEquation ) return gl.MIN;
  16285. if ( p === MaxEquation ) return gl.MAX;
  16286. }
  16287. extension = extensions.get( 'EXT_blend_minmax' );
  16288. if ( extension !== null ) {
  16289. if ( p === MinEquation ) return extension.MIN_EXT;
  16290. if ( p === MaxEquation ) return extension.MAX_EXT;
  16291. }
  16292. }
  16293. if ( p === UnsignedInt248Type ) {
  16294. if ( capabilities.isWebGL2 ) return gl.UNSIGNED_INT_24_8;
  16295. extension = extensions.get( 'WEBGL_depth_texture' );
  16296. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  16297. }
  16298. return 0;
  16299. }
  16300. return { convert: convert };
  16301. }
  16302. /**
  16303. * @author mrdoob / http://mrdoob.com/
  16304. */
  16305. function Group() {
  16306. Object3D.call( this );
  16307. this.type = 'Group';
  16308. }
  16309. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16310. constructor: Group,
  16311. isGroup: true
  16312. } );
  16313. /**
  16314. * @author mrdoob / http://mrdoob.com/
  16315. * @author greggman / http://games.greggman.com/
  16316. * @author zz85 / http://www.lab4games.net/zz85/blog
  16317. * @author tschw
  16318. */
  16319. function PerspectiveCamera( fov, aspect, near, far ) {
  16320. Camera.call( this );
  16321. this.type = 'PerspectiveCamera';
  16322. this.fov = fov !== undefined ? fov : 50;
  16323. this.zoom = 1;
  16324. this.near = near !== undefined ? near : 0.1;
  16325. this.far = far !== undefined ? far : 2000;
  16326. this.focus = 10;
  16327. this.aspect = aspect !== undefined ? aspect : 1;
  16328. this.view = null;
  16329. this.filmGauge = 35; // width of the film (default in millimeters)
  16330. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  16331. this.updateProjectionMatrix();
  16332. }
  16333. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  16334. constructor: PerspectiveCamera,
  16335. isPerspectiveCamera: true,
  16336. copy: function ( source, recursive ) {
  16337. Camera.prototype.copy.call( this, source, recursive );
  16338. this.fov = source.fov;
  16339. this.zoom = source.zoom;
  16340. this.near = source.near;
  16341. this.far = source.far;
  16342. this.focus = source.focus;
  16343. this.aspect = source.aspect;
  16344. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16345. this.filmGauge = source.filmGauge;
  16346. this.filmOffset = source.filmOffset;
  16347. return this;
  16348. },
  16349. /**
  16350. * Sets the FOV by focal length in respect to the current .filmGauge.
  16351. *
  16352. * The default film gauge is 35, so that the focal length can be specified for
  16353. * a 35mm (full frame) camera.
  16354. *
  16355. * Values for focal length and film gauge must have the same unit.
  16356. */
  16357. setFocalLength: function ( focalLength ) {
  16358. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  16359. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16360. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  16361. this.updateProjectionMatrix();
  16362. },
  16363. /**
  16364. * Calculates the focal length from the current .fov and .filmGauge.
  16365. */
  16366. getFocalLength: function () {
  16367. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  16368. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16369. },
  16370. getEffectiveFOV: function () {
  16371. return _Math.RAD2DEG * 2 * Math.atan(
  16372. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16373. },
  16374. getFilmWidth: function () {
  16375. // film not completely covered in portrait format (aspect < 1)
  16376. return this.filmGauge * Math.min( this.aspect, 1 );
  16377. },
  16378. getFilmHeight: function () {
  16379. // film not completely covered in landscape format (aspect > 1)
  16380. return this.filmGauge / Math.max( this.aspect, 1 );
  16381. },
  16382. /**
  16383. * Sets an offset in a larger frustum. This is useful for multi-window or
  16384. * multi-monitor/multi-machine setups.
  16385. *
  16386. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16387. * the monitors are in grid like this
  16388. *
  16389. * +---+---+---+
  16390. * | A | B | C |
  16391. * +---+---+---+
  16392. * | D | E | F |
  16393. * +---+---+---+
  16394. *
  16395. * then for each monitor you would call it like this
  16396. *
  16397. * var w = 1920;
  16398. * var h = 1080;
  16399. * var fullWidth = w * 3;
  16400. * var fullHeight = h * 2;
  16401. *
  16402. * --A--
  16403. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16404. * --B--
  16405. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16406. * --C--
  16407. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16408. * --D--
  16409. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16410. * --E--
  16411. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16412. * --F--
  16413. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16414. *
  16415. * Note there is no reason monitors have to be the same size or in a grid.
  16416. */
  16417. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  16418. this.aspect = fullWidth / fullHeight;
  16419. if ( this.view === null ) {
  16420. this.view = {
  16421. enabled: true,
  16422. fullWidth: 1,
  16423. fullHeight: 1,
  16424. offsetX: 0,
  16425. offsetY: 0,
  16426. width: 1,
  16427. height: 1
  16428. };
  16429. }
  16430. this.view.enabled = true;
  16431. this.view.fullWidth = fullWidth;
  16432. this.view.fullHeight = fullHeight;
  16433. this.view.offsetX = x;
  16434. this.view.offsetY = y;
  16435. this.view.width = width;
  16436. this.view.height = height;
  16437. this.updateProjectionMatrix();
  16438. },
  16439. clearViewOffset: function () {
  16440. if ( this.view !== null ) {
  16441. this.view.enabled = false;
  16442. }
  16443. this.updateProjectionMatrix();
  16444. },
  16445. updateProjectionMatrix: function () {
  16446. var near = this.near,
  16447. top = near * Math.tan(
  16448. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  16449. height = 2 * top,
  16450. width = this.aspect * height,
  16451. left = - 0.5 * width,
  16452. view = this.view;
  16453. if ( this.view !== null && this.view.enabled ) {
  16454. var fullWidth = view.fullWidth,
  16455. fullHeight = view.fullHeight;
  16456. left += view.offsetX * width / fullWidth;
  16457. top -= view.offsetY * height / fullHeight;
  16458. width *= view.width / fullWidth;
  16459. height *= view.height / fullHeight;
  16460. }
  16461. var skew = this.filmOffset;
  16462. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16463. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  16464. },
  16465. toJSON: function ( meta ) {
  16466. var data = Object3D.prototype.toJSON.call( this, meta );
  16467. data.object.fov = this.fov;
  16468. data.object.zoom = this.zoom;
  16469. data.object.near = this.near;
  16470. data.object.far = this.far;
  16471. data.object.focus = this.focus;
  16472. data.object.aspect = this.aspect;
  16473. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16474. data.object.filmGauge = this.filmGauge;
  16475. data.object.filmOffset = this.filmOffset;
  16476. return data;
  16477. }
  16478. } );
  16479. /**
  16480. * @author mrdoob / http://mrdoob.com/
  16481. */
  16482. function ArrayCamera( array ) {
  16483. PerspectiveCamera.call( this );
  16484. this.cameras = array || [];
  16485. }
  16486. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  16487. constructor: ArrayCamera,
  16488. isArrayCamera: true
  16489. } );
  16490. /**
  16491. * @author mrdoob / http://mrdoob.com/
  16492. */
  16493. function WebVRManager( renderer ) {
  16494. var scope = this;
  16495. var device = null;
  16496. var frameData = null;
  16497. var poseTarget = null;
  16498. var controllers = [];
  16499. var standingMatrix = new Matrix4();
  16500. var standingMatrixInverse = new Matrix4();
  16501. if ( typeof window !== 'undefined' && 'VRFrameData' in window ) {
  16502. frameData = new window.VRFrameData();
  16503. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  16504. }
  16505. var matrixWorldInverse = new Matrix4();
  16506. var tempQuaternion = new Quaternion();
  16507. var tempPosition = new Vector3();
  16508. var cameraL = new PerspectiveCamera();
  16509. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  16510. cameraL.layers.enable( 1 );
  16511. var cameraR = new PerspectiveCamera();
  16512. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  16513. cameraR.layers.enable( 2 );
  16514. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  16515. cameraVR.layers.enable( 1 );
  16516. cameraVR.layers.enable( 2 );
  16517. //
  16518. function isPresenting() {
  16519. return device !== null && device.isPresenting === true;
  16520. }
  16521. var currentSize, currentPixelRatio;
  16522. function onVRDisplayPresentChange() {
  16523. if ( isPresenting() ) {
  16524. var eyeParameters = device.getEyeParameters( 'left' );
  16525. var renderWidth = eyeParameters.renderWidth;
  16526. var renderHeight = eyeParameters.renderHeight;
  16527. currentPixelRatio = renderer.getPixelRatio();
  16528. currentSize = renderer.getSize();
  16529. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  16530. animation.start();
  16531. } else if ( scope.enabled ) {
  16532. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  16533. animation.stop();
  16534. }
  16535. }
  16536. //
  16537. var triggers = [];
  16538. function findGamepad( id ) {
  16539. var gamepads = navigator.getGamepads && navigator.getGamepads();
  16540. for ( var i = 0, j = 0, l = gamepads.length; i < l; i ++ ) {
  16541. var gamepad = gamepads[ i ];
  16542. if ( gamepad && ( gamepad.id === 'Daydream Controller' ||
  16543. gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' ||
  16544. gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith( 'Oculus Touch' ) ||
  16545. gamepad.id.startsWith( 'Spatial Controller' ) ) ) {
  16546. if ( j === id ) return gamepad;
  16547. j ++;
  16548. }
  16549. }
  16550. }
  16551. function updateControllers() {
  16552. for ( var i = 0; i < controllers.length; i ++ ) {
  16553. var controller = controllers[ i ];
  16554. var gamepad = findGamepad( i );
  16555. if ( gamepad !== undefined && gamepad.pose !== undefined ) {
  16556. if ( gamepad.pose === null ) return;
  16557. // Pose
  16558. var pose = gamepad.pose;
  16559. if ( pose.hasPosition === false ) controller.position.set( 0.2, - 0.6, - 0.05 );
  16560. if ( pose.position !== null ) controller.position.fromArray( pose.position );
  16561. if ( pose.orientation !== null ) controller.quaternion.fromArray( pose.orientation );
  16562. controller.matrix.compose( controller.position, controller.quaternion, controller.scale );
  16563. controller.matrix.premultiply( standingMatrix );
  16564. controller.matrix.decompose( controller.position, controller.quaternion, controller.scale );
  16565. controller.matrixWorldNeedsUpdate = true;
  16566. controller.visible = true;
  16567. // Trigger
  16568. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  16569. if ( triggers[ i ] !== gamepad.buttons[ buttonId ].pressed ) {
  16570. triggers[ i ] = gamepad.buttons[ buttonId ].pressed;
  16571. if ( triggers[ i ] === true ) {
  16572. controller.dispatchEvent( { type: 'selectstart' } );
  16573. } else {
  16574. controller.dispatchEvent( { type: 'selectend' } );
  16575. controller.dispatchEvent( { type: 'select' } );
  16576. }
  16577. }
  16578. } else {
  16579. controller.visible = false;
  16580. }
  16581. }
  16582. }
  16583. //
  16584. this.enabled = false;
  16585. this.userHeight = 1.6;
  16586. this.getController = function ( id ) {
  16587. var controller = controllers[ id ];
  16588. if ( controller === undefined ) {
  16589. controller = new Group();
  16590. controller.matrixAutoUpdate = false;
  16591. controller.visible = false;
  16592. controllers[ id ] = controller;
  16593. }
  16594. return controller;
  16595. };
  16596. this.getDevice = function () {
  16597. return device;
  16598. };
  16599. this.setDevice = function ( value ) {
  16600. if ( value !== undefined ) device = value;
  16601. animation.setContext( value );
  16602. };
  16603. this.setPoseTarget = function ( object ) {
  16604. if ( object !== undefined ) poseTarget = object;
  16605. };
  16606. this.getCamera = function ( camera ) {
  16607. if ( device === null ) {
  16608. camera.position.set( 0, scope.userHeight, 0 );
  16609. return camera;
  16610. }
  16611. device.depthNear = camera.near;
  16612. device.depthFar = camera.far;
  16613. device.getFrameData( frameData );
  16614. //
  16615. var stageParameters = device.stageParameters;
  16616. if ( stageParameters ) {
  16617. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  16618. } else {
  16619. standingMatrix.makeTranslation( 0, scope.userHeight, 0 );
  16620. }
  16621. var pose = frameData.pose;
  16622. var poseObject = poseTarget !== null ? poseTarget : camera;
  16623. // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  16624. poseObject.matrix.copy( standingMatrix );
  16625. poseObject.matrix.decompose( poseObject.position, poseObject.quaternion, poseObject.scale );
  16626. if ( pose.orientation !== null ) {
  16627. tempQuaternion.fromArray( pose.orientation );
  16628. poseObject.quaternion.multiply( tempQuaternion );
  16629. }
  16630. if ( pose.position !== null ) {
  16631. tempQuaternion.setFromRotationMatrix( standingMatrix );
  16632. tempPosition.fromArray( pose.position );
  16633. tempPosition.applyQuaternion( tempQuaternion );
  16634. poseObject.position.add( tempPosition );
  16635. }
  16636. poseObject.updateMatrixWorld();
  16637. if ( device.isPresenting === false ) return camera;
  16638. //
  16639. cameraL.near = camera.near;
  16640. cameraR.near = camera.near;
  16641. cameraL.far = camera.far;
  16642. cameraR.far = camera.far;
  16643. cameraVR.matrixWorld.copy( camera.matrixWorld );
  16644. cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse );
  16645. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  16646. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  16647. // TODO (mrdoob) Double check this code
  16648. standingMatrixInverse.getInverse( standingMatrix );
  16649. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  16650. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  16651. var parent = poseObject.parent;
  16652. if ( parent !== null ) {
  16653. matrixWorldInverse.getInverse( parent.matrixWorld );
  16654. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  16655. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  16656. }
  16657. // envMap and Mirror needs camera.matrixWorld
  16658. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  16659. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  16660. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  16661. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  16662. // HACK (mrdoob)
  16663. // https://github.com/w3c/webvr/issues/203
  16664. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  16665. //
  16666. var layers = device.getLayers();
  16667. if ( layers.length ) {
  16668. var layer = layers[ 0 ];
  16669. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  16670. cameraL.bounds.fromArray( layer.leftBounds );
  16671. }
  16672. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  16673. cameraR.bounds.fromArray( layer.rightBounds );
  16674. }
  16675. }
  16676. updateControllers();
  16677. return cameraVR;
  16678. };
  16679. this.getStandingMatrix = function () {
  16680. return standingMatrix;
  16681. };
  16682. this.isPresenting = isPresenting;
  16683. // Animation Loop
  16684. var animation = new WebGLAnimation();
  16685. this.setAnimationLoop = function ( callback ) {
  16686. animation.setAnimationLoop( callback );
  16687. };
  16688. this.submitFrame = function () {
  16689. if ( isPresenting() ) device.submitFrame();
  16690. };
  16691. this.dispose = function () {
  16692. if ( typeof window !== 'undefined' ) {
  16693. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  16694. }
  16695. };
  16696. }
  16697. /**
  16698. * @author mrdoob / http://mrdoob.com/
  16699. */
  16700. function WebXRManager( renderer ) {
  16701. var gl = renderer.context;
  16702. var device = null;
  16703. var session = null;
  16704. var frameOfRef = null;
  16705. var pose = null;
  16706. var controllers = [];
  16707. var inputSources = [];
  16708. function isPresenting() {
  16709. return session !== null && frameOfRef !== null;
  16710. }
  16711. //
  16712. var cameraL = new PerspectiveCamera();
  16713. cameraL.layers.enable( 1 );
  16714. cameraL.viewport = new Vector4();
  16715. var cameraR = new PerspectiveCamera();
  16716. cameraR.layers.enable( 2 );
  16717. cameraR.viewport = new Vector4();
  16718. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  16719. cameraVR.layers.enable( 1 );
  16720. cameraVR.layers.enable( 2 );
  16721. //
  16722. this.enabled = false;
  16723. this.getController = function ( id ) {
  16724. var controller = controllers[ id ];
  16725. if ( controller === undefined ) {
  16726. controller = new Group();
  16727. controller.matrixAutoUpdate = false;
  16728. controller.visible = false;
  16729. controllers[ id ] = controller;
  16730. }
  16731. return controller;
  16732. };
  16733. this.getDevice = function () {
  16734. return device;
  16735. };
  16736. this.setDevice = function ( value ) {
  16737. if ( value !== undefined ) device = value;
  16738. if ( value instanceof XRDevice ) gl.setCompatibleXRDevice( value );
  16739. };
  16740. //
  16741. function onSessionEvent( event ) {
  16742. var controller = controllers[ inputSources.indexOf( event.inputSource ) ];
  16743. if ( controller ) controller.dispatchEvent( { type: event.type } );
  16744. }
  16745. function onSessionEnd() {
  16746. renderer.setFramebuffer( null );
  16747. animation.stop();
  16748. }
  16749. this.setSession = function ( value, options ) {
  16750. session = value;
  16751. if ( session !== null ) {
  16752. session.addEventListener( 'select', onSessionEvent );
  16753. session.addEventListener( 'selectstart', onSessionEvent );
  16754. session.addEventListener( 'selectend', onSessionEvent );
  16755. session.addEventListener( 'end', onSessionEnd );
  16756. session.baseLayer = new XRWebGLLayer( session, gl );
  16757. session.requestFrameOfReference( options.frameOfReferenceType ).then( function ( value ) {
  16758. frameOfRef = value;
  16759. renderer.setFramebuffer( session.baseLayer.framebuffer );
  16760. animation.setContext( session );
  16761. animation.start();
  16762. } );
  16763. //
  16764. inputSources = session.getInputSources();
  16765. session.addEventListener( 'inputsourceschange', function () {
  16766. inputSources = session.getInputSources();
  16767. console.log( inputSources );
  16768. } );
  16769. }
  16770. };
  16771. function updateCamera( camera, parent ) {
  16772. if ( parent === null ) {
  16773. camera.matrixWorld.copy( camera.matrix );
  16774. } else {
  16775. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  16776. }
  16777. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  16778. }
  16779. this.getCamera = function ( camera ) {
  16780. if ( isPresenting() ) {
  16781. var parent = camera.parent;
  16782. var cameras = cameraVR.cameras;
  16783. // apply camera.parent to cameraVR
  16784. updateCamera( cameraVR, parent );
  16785. for ( var i = 0; i < cameras.length; i ++ ) {
  16786. updateCamera( cameras[ i ], parent );
  16787. }
  16788. // update camera and its children
  16789. camera.matrixWorld.copy( cameraVR.matrixWorld );
  16790. var children = camera.children;
  16791. for ( var i = 0, l = children.length; i < l; i ++ ) {
  16792. children[ i ].updateMatrixWorld( true );
  16793. }
  16794. return cameraVR;
  16795. }
  16796. return camera;
  16797. };
  16798. this.isPresenting = isPresenting;
  16799. // Animation Loop
  16800. var onAnimationFrameCallback = null;
  16801. function onAnimationFrame( time, frame ) {
  16802. pose = frame.getDevicePose( frameOfRef );
  16803. if ( pose !== null ) {
  16804. var layer = session.baseLayer;
  16805. var views = frame.views;
  16806. for ( var i = 0; i < views.length; i ++ ) {
  16807. var view = views[ i ];
  16808. var viewport = layer.getViewport( view );
  16809. var viewMatrix = pose.getViewMatrix( view );
  16810. var camera = cameraVR.cameras[ i ];
  16811. camera.matrix.fromArray( viewMatrix ).getInverse( camera.matrix );
  16812. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16813. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16814. if ( i === 0 ) {
  16815. cameraVR.matrix.copy( camera.matrix );
  16816. // HACK (mrdoob)
  16817. // https://github.com/w3c/webvr/issues/203
  16818. cameraVR.projectionMatrix.copy( camera.projectionMatrix );
  16819. }
  16820. }
  16821. }
  16822. //
  16823. for ( var i = 0; i < controllers.length; i ++ ) {
  16824. var controller = controllers[ i ];
  16825. var inputSource = inputSources[ i ];
  16826. if ( inputSource ) {
  16827. var inputPose = frame.getInputPose( inputSource, frameOfRef );
  16828. if ( inputPose !== null ) {
  16829. controller.matrix.elements = inputPose.pointerMatrix;
  16830. controller.matrix.decompose( controller.position, controller.rotation, controller.scale );
  16831. controller.visible = true;
  16832. continue;
  16833. }
  16834. }
  16835. controller.visible = false;
  16836. }
  16837. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16838. }
  16839. var animation = new WebGLAnimation();
  16840. animation.setAnimationLoop( onAnimationFrame );
  16841. this.setAnimationLoop = function ( callback ) {
  16842. onAnimationFrameCallback = callback;
  16843. };
  16844. this.dispose = function () {};
  16845. // DEPRECATED
  16846. this.getStandingMatrix = function () {
  16847. console.warn( 'THREE.WebXRManager: getStandingMatrix() is no longer needed.' );
  16848. return new THREE.Matrix4();
  16849. };
  16850. this.submitFrame = function () {};
  16851. }
  16852. /**
  16853. * @author supereggbert / http://www.paulbrunt.co.uk/
  16854. * @author mrdoob / http://mrdoob.com/
  16855. * @author alteredq / http://alteredqualia.com/
  16856. * @author szimek / https://github.com/szimek/
  16857. * @author tschw
  16858. */
  16859. function WebGLRenderer( parameters ) {
  16860. console.log( 'THREE.WebGLRenderer', REVISION );
  16861. parameters = parameters || {};
  16862. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  16863. _context = parameters.context !== undefined ? parameters.context : null,
  16864. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  16865. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16866. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16867. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16868. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16869. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16870. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default';
  16871. var currentRenderList = null;
  16872. var currentRenderState = null;
  16873. // public properties
  16874. this.domElement = _canvas;
  16875. this.context = null;
  16876. // clearing
  16877. this.autoClear = true;
  16878. this.autoClearColor = true;
  16879. this.autoClearDepth = true;
  16880. this.autoClearStencil = true;
  16881. // scene graph
  16882. this.sortObjects = true;
  16883. // user-defined clipping
  16884. this.clippingPlanes = [];
  16885. this.localClippingEnabled = false;
  16886. // physically based shading
  16887. this.gammaFactor = 2.0; // for backwards compatibility
  16888. this.gammaInput = false;
  16889. this.gammaOutput = false;
  16890. // physical lights
  16891. this.physicallyCorrectLights = false;
  16892. // tone mapping
  16893. this.toneMapping = LinearToneMapping;
  16894. this.toneMappingExposure = 1.0;
  16895. this.toneMappingWhitePoint = 1.0;
  16896. // morphs
  16897. this.maxMorphTargets = 8;
  16898. this.maxMorphNormals = 4;
  16899. // internal properties
  16900. var _this = this,
  16901. _isContextLost = false,
  16902. // internal state cache
  16903. _framebuffer = null,
  16904. _currentRenderTarget = null,
  16905. _currentFramebuffer = null,
  16906. _currentMaterialId = - 1,
  16907. // geometry and program caching
  16908. _currentGeometryProgram = {
  16909. geometry: null,
  16910. program: null,
  16911. wireframe: false
  16912. },
  16913. _currentCamera = null,
  16914. _currentArrayCamera = null,
  16915. _currentViewport = new Vector4(),
  16916. _currentScissor = new Vector4(),
  16917. _currentScissorTest = null,
  16918. //
  16919. _usedTextureUnits = 0,
  16920. //
  16921. _width = _canvas.width,
  16922. _height = _canvas.height,
  16923. _pixelRatio = 1,
  16924. _viewport = new Vector4( 0, 0, _width, _height ),
  16925. _scissor = new Vector4( 0, 0, _width, _height ),
  16926. _scissorTest = false,
  16927. // frustum
  16928. _frustum = new Frustum(),
  16929. // clipping
  16930. _clipping = new WebGLClipping(),
  16931. _clippingEnabled = false,
  16932. _localClippingEnabled = false,
  16933. // camera matrices cache
  16934. _projScreenMatrix = new Matrix4(),
  16935. _vector3 = new Vector3();
  16936. function getTargetPixelRatio() {
  16937. return _currentRenderTarget === null ? _pixelRatio : 1;
  16938. }
  16939. // initialize
  16940. var _gl;
  16941. try {
  16942. var contextAttributes = {
  16943. alpha: _alpha,
  16944. depth: _depth,
  16945. stencil: _stencil,
  16946. antialias: _antialias,
  16947. premultipliedAlpha: _premultipliedAlpha,
  16948. preserveDrawingBuffer: _preserveDrawingBuffer,
  16949. powerPreference: _powerPreference
  16950. };
  16951. // event listeners must be registered before WebGL context is created, see #12753
  16952. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16953. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16954. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  16955. if ( _gl === null ) {
  16956. if ( _canvas.getContext( 'webgl' ) !== null ) {
  16957. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16958. } else {
  16959. throw new Error( 'Error creating WebGL context.' );
  16960. }
  16961. }
  16962. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16963. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16964. _gl.getShaderPrecisionFormat = function () {
  16965. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16966. };
  16967. }
  16968. } catch ( error ) {
  16969. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16970. }
  16971. var extensions, capabilities, state, info;
  16972. var properties, textures, attributes, geometries, objects;
  16973. var programCache, renderLists, renderStates;
  16974. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16975. var utils;
  16976. function initGLContext() {
  16977. extensions = new WebGLExtensions( _gl );
  16978. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16979. if ( ! capabilities.isWebGL2 ) {
  16980. extensions.get( 'WEBGL_depth_texture' );
  16981. extensions.get( 'OES_texture_float' );
  16982. extensions.get( 'OES_texture_half_float' );
  16983. extensions.get( 'OES_texture_half_float_linear' );
  16984. extensions.get( 'OES_standard_derivatives' );
  16985. extensions.get( 'OES_element_index_uint' );
  16986. extensions.get( 'ANGLE_instanced_arrays' );
  16987. }
  16988. extensions.get( 'OES_texture_float_linear' );
  16989. utils = new WebGLUtils( _gl, extensions, capabilities );
  16990. state = new WebGLState( _gl, extensions, utils, capabilities );
  16991. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  16992. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  16993. info = new WebGLInfo( _gl );
  16994. properties = new WebGLProperties();
  16995. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16996. attributes = new WebGLAttributes( _gl );
  16997. geometries = new WebGLGeometries( _gl, attributes, info );
  16998. objects = new WebGLObjects( geometries, info );
  16999. morphtargets = new WebGLMorphtargets( _gl );
  17000. programCache = new WebGLPrograms( _this, extensions, capabilities );
  17001. renderLists = new WebGLRenderLists();
  17002. renderStates = new WebGLRenderStates();
  17003. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  17004. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  17005. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  17006. info.programs = programCache.programs;
  17007. _this.context = _gl;
  17008. _this.capabilities = capabilities;
  17009. _this.extensions = extensions;
  17010. _this.properties = properties;
  17011. _this.renderLists = renderLists;
  17012. _this.state = state;
  17013. _this.info = info;
  17014. }
  17015. initGLContext();
  17016. // vr
  17017. var vr = ( 'xr' in navigator ) ? new WebXRManager( _this ) : new WebVRManager( _this );
  17018. this.vr = vr;
  17019. // shadow map
  17020. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  17021. this.shadowMap = shadowMap;
  17022. // API
  17023. this.getContext = function () {
  17024. return _gl;
  17025. };
  17026. this.getContextAttributes = function () {
  17027. return _gl.getContextAttributes();
  17028. };
  17029. this.forceContextLoss = function () {
  17030. var extension = extensions.get( 'WEBGL_lose_context' );
  17031. if ( extension ) extension.loseContext();
  17032. };
  17033. this.forceContextRestore = function () {
  17034. var extension = extensions.get( 'WEBGL_lose_context' );
  17035. if ( extension ) extension.restoreContext();
  17036. };
  17037. this.getPixelRatio = function () {
  17038. return _pixelRatio;
  17039. };
  17040. this.setPixelRatio = function ( value ) {
  17041. if ( value === undefined ) return;
  17042. _pixelRatio = value;
  17043. this.setSize( _width, _height, false );
  17044. };
  17045. this.getSize = function () {
  17046. return {
  17047. width: _width,
  17048. height: _height
  17049. };
  17050. };
  17051. this.setSize = function ( width, height, updateStyle ) {
  17052. if ( vr.isPresenting() ) {
  17053. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17054. return;
  17055. }
  17056. _width = width;
  17057. _height = height;
  17058. _canvas.width = width * _pixelRatio;
  17059. _canvas.height = height * _pixelRatio;
  17060. if ( updateStyle !== false ) {
  17061. _canvas.style.width = width + 'px';
  17062. _canvas.style.height = height + 'px';
  17063. }
  17064. this.setViewport( 0, 0, width, height );
  17065. };
  17066. this.getDrawingBufferSize = function () {
  17067. return {
  17068. width: _width * _pixelRatio,
  17069. height: _height * _pixelRatio
  17070. };
  17071. };
  17072. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17073. _width = width;
  17074. _height = height;
  17075. _pixelRatio = pixelRatio;
  17076. _canvas.width = width * pixelRatio;
  17077. _canvas.height = height * pixelRatio;
  17078. this.setViewport( 0, 0, width, height );
  17079. };
  17080. this.getCurrentViewport = function () {
  17081. return _currentViewport;
  17082. };
  17083. this.setViewport = function ( x, y, width, height ) {
  17084. _viewport.set( x, _height - y - height, width, height );
  17085. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  17086. };
  17087. this.setScissor = function ( x, y, width, height ) {
  17088. _scissor.set( x, _height - y - height, width, height );
  17089. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  17090. };
  17091. this.setScissorTest = function ( boolean ) {
  17092. state.setScissorTest( _scissorTest = boolean );
  17093. };
  17094. // Clearing
  17095. this.getClearColor = function () {
  17096. return background.getClearColor();
  17097. };
  17098. this.setClearColor = function () {
  17099. background.setClearColor.apply( background, arguments );
  17100. };
  17101. this.getClearAlpha = function () {
  17102. return background.getClearAlpha();
  17103. };
  17104. this.setClearAlpha = function () {
  17105. background.setClearAlpha.apply( background, arguments );
  17106. };
  17107. this.clear = function ( color, depth, stencil ) {
  17108. var bits = 0;
  17109. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  17110. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17111. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  17112. _gl.clear( bits );
  17113. };
  17114. this.clearColor = function () {
  17115. this.clear( true, false, false );
  17116. };
  17117. this.clearDepth = function () {
  17118. this.clear( false, true, false );
  17119. };
  17120. this.clearStencil = function () {
  17121. this.clear( false, false, true );
  17122. };
  17123. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  17124. this.setRenderTarget( renderTarget );
  17125. this.clear( color, depth, stencil );
  17126. };
  17127. //
  17128. this.dispose = function () {
  17129. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17130. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17131. renderLists.dispose();
  17132. renderStates.dispose();
  17133. properties.dispose();
  17134. objects.dispose();
  17135. vr.dispose();
  17136. animation.stop();
  17137. };
  17138. // Events
  17139. function onContextLost( event ) {
  17140. event.preventDefault();
  17141. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17142. _isContextLost = true;
  17143. }
  17144. function onContextRestore( /* event */ ) {
  17145. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17146. _isContextLost = false;
  17147. initGLContext();
  17148. }
  17149. function onMaterialDispose( event ) {
  17150. var material = event.target;
  17151. material.removeEventListener( 'dispose', onMaterialDispose );
  17152. deallocateMaterial( material );
  17153. }
  17154. // Buffer deallocation
  17155. function deallocateMaterial( material ) {
  17156. releaseMaterialProgramReference( material );
  17157. properties.remove( material );
  17158. }
  17159. function releaseMaterialProgramReference( material ) {
  17160. var programInfo = properties.get( material ).program;
  17161. material.program = undefined;
  17162. if ( programInfo !== undefined ) {
  17163. programCache.releaseProgram( programInfo );
  17164. }
  17165. }
  17166. // Buffer rendering
  17167. function renderObjectImmediate( object, program ) {
  17168. object.render( function ( object ) {
  17169. _this.renderBufferImmediate( object, program );
  17170. } );
  17171. }
  17172. this.renderBufferImmediate = function ( object, program ) {
  17173. state.initAttributes();
  17174. var buffers = properties.get( object );
  17175. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  17176. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  17177. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  17178. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  17179. var programAttributes = program.getAttributes();
  17180. if ( object.hasPositions ) {
  17181. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  17182. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  17183. state.enableAttribute( programAttributes.position );
  17184. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  17185. }
  17186. if ( object.hasNormals ) {
  17187. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  17188. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  17189. state.enableAttribute( programAttributes.normal );
  17190. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  17191. }
  17192. if ( object.hasUvs ) {
  17193. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  17194. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  17195. state.enableAttribute( programAttributes.uv );
  17196. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  17197. }
  17198. if ( object.hasColors ) {
  17199. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  17200. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  17201. state.enableAttribute( programAttributes.color );
  17202. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  17203. }
  17204. state.disableUnusedAttributes();
  17205. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  17206. object.count = 0;
  17207. };
  17208. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  17209. var frontFaceCW = ( object.isMesh && object.normalMatrix.determinant() < 0 );
  17210. state.setMaterial( material, frontFaceCW );
  17211. var program = setProgram( camera, fog, material, object );
  17212. var updateBuffers = false;
  17213. if ( _currentGeometryProgram.geometry !== geometry.id ||
  17214. _currentGeometryProgram.program !== program.id ||
  17215. _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) {
  17216. _currentGeometryProgram.geometry = geometry.id;
  17217. _currentGeometryProgram.program = program.id;
  17218. _currentGeometryProgram.wireframe = material.wireframe === true;
  17219. updateBuffers = true;
  17220. }
  17221. if ( object.morphTargetInfluences ) {
  17222. morphtargets.update( object, geometry, material, program );
  17223. updateBuffers = true;
  17224. }
  17225. //
  17226. var index = geometry.index;
  17227. var position = geometry.attributes.position;
  17228. var rangeFactor = 1;
  17229. if ( material.wireframe === true ) {
  17230. index = geometries.getWireframeAttribute( geometry );
  17231. rangeFactor = 2;
  17232. }
  17233. var attribute;
  17234. var renderer = bufferRenderer;
  17235. if ( index !== null ) {
  17236. attribute = attributes.get( index );
  17237. renderer = indexedBufferRenderer;
  17238. renderer.setIndex( attribute );
  17239. }
  17240. if ( updateBuffers ) {
  17241. setupVertexAttributes( material, program, geometry );
  17242. if ( index !== null ) {
  17243. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  17244. }
  17245. }
  17246. //
  17247. var dataCount = Infinity;
  17248. if ( index !== null ) {
  17249. dataCount = index.count;
  17250. } else if ( position !== undefined ) {
  17251. dataCount = position.count;
  17252. }
  17253. var rangeStart = geometry.drawRange.start * rangeFactor;
  17254. var rangeCount = geometry.drawRange.count * rangeFactor;
  17255. var groupStart = group !== null ? group.start * rangeFactor : 0;
  17256. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  17257. var drawStart = Math.max( rangeStart, groupStart );
  17258. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  17259. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  17260. if ( drawCount === 0 ) return;
  17261. //
  17262. if ( object.isMesh ) {
  17263. if ( material.wireframe === true ) {
  17264. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17265. renderer.setMode( _gl.LINES );
  17266. } else {
  17267. switch ( object.drawMode ) {
  17268. case TrianglesDrawMode:
  17269. renderer.setMode( _gl.TRIANGLES );
  17270. break;
  17271. case TriangleStripDrawMode:
  17272. renderer.setMode( _gl.TRIANGLE_STRIP );
  17273. break;
  17274. case TriangleFanDrawMode:
  17275. renderer.setMode( _gl.TRIANGLE_FAN );
  17276. break;
  17277. }
  17278. }
  17279. } else if ( object.isLine ) {
  17280. var lineWidth = material.linewidth;
  17281. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17282. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17283. if ( object.isLineSegments ) {
  17284. renderer.setMode( _gl.LINES );
  17285. } else if ( object.isLineLoop ) {
  17286. renderer.setMode( _gl.LINE_LOOP );
  17287. } else {
  17288. renderer.setMode( _gl.LINE_STRIP );
  17289. }
  17290. } else if ( object.isPoints ) {
  17291. renderer.setMode( _gl.POINTS );
  17292. } else if ( object.isSprite ) {
  17293. renderer.setMode( _gl.TRIANGLES );
  17294. }
  17295. if ( geometry && geometry.isInstancedBufferGeometry ) {
  17296. if ( geometry.maxInstancedCount > 0 ) {
  17297. renderer.renderInstances( geometry, drawStart, drawCount );
  17298. }
  17299. } else {
  17300. renderer.render( drawStart, drawCount );
  17301. }
  17302. };
  17303. function setupVertexAttributes( material, program, geometry ) {
  17304. if ( geometry && geometry.isInstancedBufferGeometry & ! capabilities.isWebGL2 ) {
  17305. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  17306. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  17307. return;
  17308. }
  17309. }
  17310. state.initAttributes();
  17311. var geometryAttributes = geometry.attributes;
  17312. var programAttributes = program.getAttributes();
  17313. var materialDefaultAttributeValues = material.defaultAttributeValues;
  17314. for ( var name in programAttributes ) {
  17315. var programAttribute = programAttributes[ name ];
  17316. if ( programAttribute >= 0 ) {
  17317. var geometryAttribute = geometryAttributes[ name ];
  17318. if ( geometryAttribute !== undefined ) {
  17319. var normalized = geometryAttribute.normalized;
  17320. var size = geometryAttribute.itemSize;
  17321. var attribute = attributes.get( geometryAttribute );
  17322. // TODO Attribute may not be available on context restore
  17323. if ( attribute === undefined ) continue;
  17324. var buffer = attribute.buffer;
  17325. var type = attribute.type;
  17326. var bytesPerElement = attribute.bytesPerElement;
  17327. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  17328. var data = geometryAttribute.data;
  17329. var stride = data.stride;
  17330. var offset = geometryAttribute.offset;
  17331. if ( data && data.isInstancedInterleavedBuffer ) {
  17332. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  17333. if ( geometry.maxInstancedCount === undefined ) {
  17334. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  17335. }
  17336. } else {
  17337. state.enableAttribute( programAttribute );
  17338. }
  17339. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  17340. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  17341. } else {
  17342. if ( geometryAttribute.isInstancedBufferAttribute ) {
  17343. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  17344. if ( geometry.maxInstancedCount === undefined ) {
  17345. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  17346. }
  17347. } else {
  17348. state.enableAttribute( programAttribute );
  17349. }
  17350. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  17351. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  17352. }
  17353. } else if ( materialDefaultAttributeValues !== undefined ) {
  17354. var value = materialDefaultAttributeValues[ name ];
  17355. if ( value !== undefined ) {
  17356. switch ( value.length ) {
  17357. case 2:
  17358. _gl.vertexAttrib2fv( programAttribute, value );
  17359. break;
  17360. case 3:
  17361. _gl.vertexAttrib3fv( programAttribute, value );
  17362. break;
  17363. case 4:
  17364. _gl.vertexAttrib4fv( programAttribute, value );
  17365. break;
  17366. default:
  17367. _gl.vertexAttrib1fv( programAttribute, value );
  17368. }
  17369. }
  17370. }
  17371. }
  17372. }
  17373. state.disableUnusedAttributes();
  17374. }
  17375. // Compile
  17376. this.compile = function ( scene, camera ) {
  17377. currentRenderState = renderStates.get( scene, camera );
  17378. currentRenderState.init();
  17379. scene.traverse( function ( object ) {
  17380. if ( object.isLight ) {
  17381. currentRenderState.pushLight( object );
  17382. if ( object.castShadow ) {
  17383. currentRenderState.pushShadow( object );
  17384. }
  17385. }
  17386. } );
  17387. currentRenderState.setupLights( camera );
  17388. scene.traverse( function ( object ) {
  17389. if ( object.material ) {
  17390. if ( Array.isArray( object.material ) ) {
  17391. for ( var i = 0; i < object.material.length; i ++ ) {
  17392. initMaterial( object.material[ i ], scene.fog, object );
  17393. }
  17394. } else {
  17395. initMaterial( object.material, scene.fog, object );
  17396. }
  17397. }
  17398. } );
  17399. };
  17400. // Animation Loop
  17401. var onAnimationFrameCallback = null;
  17402. function onAnimationFrame( time ) {
  17403. if ( vr.isPresenting() ) return;
  17404. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17405. }
  17406. var animation = new WebGLAnimation();
  17407. animation.setAnimationLoop( onAnimationFrame );
  17408. if ( typeof window !== 'undefined' ) animation.setContext( window );
  17409. this.setAnimationLoop = function ( callback ) {
  17410. onAnimationFrameCallback = callback;
  17411. vr.setAnimationLoop( callback );
  17412. animation.start();
  17413. };
  17414. // Rendering
  17415. this.render = function ( scene, camera, renderTarget, forceClear ) {
  17416. if ( ! ( camera && camera.isCamera ) ) {
  17417. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17418. return;
  17419. }
  17420. if ( _isContextLost ) return;
  17421. // reset caching for this frame
  17422. _currentGeometryProgram.geometry = null;
  17423. _currentGeometryProgram.program = null;
  17424. _currentGeometryProgram.wireframe = false;
  17425. _currentMaterialId = - 1;
  17426. _currentCamera = null;
  17427. // update scene graph
  17428. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  17429. // update camera matrices and frustum
  17430. if ( camera.parent === null ) camera.updateMatrixWorld();
  17431. if ( vr.enabled ) {
  17432. camera = vr.getCamera( camera );
  17433. }
  17434. //
  17435. currentRenderState = renderStates.get( scene, camera );
  17436. currentRenderState.init();
  17437. scene.onBeforeRender( _this, scene, camera, renderTarget );
  17438. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17439. _frustum.setFromMatrix( _projScreenMatrix );
  17440. _localClippingEnabled = this.localClippingEnabled;
  17441. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  17442. currentRenderList = renderLists.get( scene, camera );
  17443. currentRenderList.init();
  17444. projectObject( scene, camera, _this.sortObjects );
  17445. if ( _this.sortObjects === true ) {
  17446. currentRenderList.sort();
  17447. }
  17448. //
  17449. if ( _clippingEnabled ) _clipping.beginShadows();
  17450. var shadowsArray = currentRenderState.state.shadowsArray;
  17451. shadowMap.render( shadowsArray, scene, camera );
  17452. currentRenderState.setupLights( camera );
  17453. if ( _clippingEnabled ) _clipping.endShadows();
  17454. //
  17455. if ( this.info.autoReset ) this.info.reset();
  17456. if ( renderTarget === undefined ) {
  17457. renderTarget = null;
  17458. }
  17459. this.setRenderTarget( renderTarget );
  17460. //
  17461. background.render( currentRenderList, scene, camera, forceClear );
  17462. // render scene
  17463. var opaqueObjects = currentRenderList.opaque;
  17464. var transparentObjects = currentRenderList.transparent;
  17465. if ( scene.overrideMaterial ) {
  17466. var overrideMaterial = scene.overrideMaterial;
  17467. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  17468. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  17469. } else {
  17470. // opaque pass (front-to-back order)
  17471. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  17472. // transparent pass (back-to-front order)
  17473. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  17474. }
  17475. // Generate mipmap if we're using any kind of mipmap filtering
  17476. if ( renderTarget ) {
  17477. textures.updateRenderTargetMipmap( renderTarget );
  17478. }
  17479. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17480. state.buffers.depth.setTest( true );
  17481. state.buffers.depth.setMask( true );
  17482. state.buffers.color.setMask( true );
  17483. state.setPolygonOffset( false );
  17484. scene.onAfterRender( _this, scene, camera );
  17485. if ( vr.enabled ) {
  17486. vr.submitFrame();
  17487. }
  17488. // _gl.finish();
  17489. currentRenderList = null;
  17490. currentRenderState = null;
  17491. };
  17492. /*
  17493. // TODO Duplicated code (Frustum)
  17494. var _sphere = new Sphere();
  17495. function isObjectViewable( object ) {
  17496. var geometry = object.geometry;
  17497. if ( geometry.boundingSphere === null )
  17498. geometry.computeBoundingSphere();
  17499. _sphere.copy( geometry.boundingSphere ).
  17500. applyMatrix4( object.matrixWorld );
  17501. return isSphereViewable( _sphere );
  17502. }
  17503. function isSpriteViewable( sprite ) {
  17504. _sphere.center.set( 0, 0, 0 );
  17505. _sphere.radius = 0.7071067811865476;
  17506. _sphere.applyMatrix4( sprite.matrixWorld );
  17507. return isSphereViewable( _sphere );
  17508. }
  17509. function isSphereViewable( sphere ) {
  17510. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  17511. var numPlanes = _clipping.numPlanes;
  17512. if ( numPlanes === 0 ) return true;
  17513. var planes = _this.clippingPlanes,
  17514. center = sphere.center,
  17515. negRad = - sphere.radius,
  17516. i = 0;
  17517. do {
  17518. // out when deeper than radius in the negative halfspace
  17519. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  17520. } while ( ++ i !== numPlanes );
  17521. return true;
  17522. }
  17523. */
  17524. function projectObject( object, camera, sortObjects ) {
  17525. if ( object.visible === false ) return;
  17526. var visible = object.layers.test( camera.layers );
  17527. if ( visible ) {
  17528. if ( object.isLight ) {
  17529. currentRenderState.pushLight( object );
  17530. if ( object.castShadow ) {
  17531. currentRenderState.pushShadow( object );
  17532. }
  17533. } else if ( object.isSprite ) {
  17534. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17535. if ( sortObjects ) {
  17536. _vector3.setFromMatrixPosition( object.matrixWorld )
  17537. .applyMatrix4( _projScreenMatrix );
  17538. }
  17539. var geometry = objects.update( object );
  17540. var material = object.material;
  17541. currentRenderList.push( object, geometry, material, _vector3.z, null );
  17542. }
  17543. } else if ( object.isImmediateRenderObject ) {
  17544. if ( sortObjects ) {
  17545. _vector3.setFromMatrixPosition( object.matrixWorld )
  17546. .applyMatrix4( _projScreenMatrix );
  17547. }
  17548. currentRenderList.push( object, null, object.material, _vector3.z, null );
  17549. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17550. if ( object.isSkinnedMesh ) {
  17551. object.skeleton.update();
  17552. }
  17553. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17554. if ( sortObjects ) {
  17555. _vector3.setFromMatrixPosition( object.matrixWorld )
  17556. .applyMatrix4( _projScreenMatrix );
  17557. }
  17558. var geometry = objects.update( object );
  17559. var material = object.material;
  17560. if ( Array.isArray( material ) ) {
  17561. var groups = geometry.groups;
  17562. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  17563. var group = groups[ i ];
  17564. var groupMaterial = material[ group.materialIndex ];
  17565. if ( groupMaterial && groupMaterial.visible ) {
  17566. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  17567. }
  17568. }
  17569. } else if ( material.visible ) {
  17570. currentRenderList.push( object, geometry, material, _vector3.z, null );
  17571. }
  17572. }
  17573. }
  17574. }
  17575. var children = object.children;
  17576. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17577. projectObject( children[ i ], camera, sortObjects );
  17578. }
  17579. }
  17580. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  17581. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  17582. var renderItem = renderList[ i ];
  17583. var object = renderItem.object;
  17584. var geometry = renderItem.geometry;
  17585. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  17586. var group = renderItem.group;
  17587. if ( camera.isArrayCamera ) {
  17588. _currentArrayCamera = camera;
  17589. var cameras = camera.cameras;
  17590. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  17591. var camera2 = cameras[ j ];
  17592. if ( object.layers.test( camera2.layers ) ) {
  17593. if ( 'viewport' in camera2 ) { // XR
  17594. state.viewport( _currentViewport.copy( camera2.viewport ) );
  17595. } else {
  17596. var bounds = camera2.bounds;
  17597. var x = bounds.x * _width;
  17598. var y = bounds.y * _height;
  17599. var width = bounds.z * _width;
  17600. var height = bounds.w * _height;
  17601. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  17602. }
  17603. renderObject( object, scene, camera2, geometry, material, group );
  17604. }
  17605. }
  17606. } else {
  17607. _currentArrayCamera = null;
  17608. renderObject( object, scene, camera, geometry, material, group );
  17609. }
  17610. }
  17611. }
  17612. function renderObject( object, scene, camera, geometry, material, group ) {
  17613. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17614. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  17615. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17616. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17617. if ( object.isImmediateRenderObject ) {
  17618. state.setMaterial( material );
  17619. var program = setProgram( camera, scene.fog, material, object );
  17620. _currentGeometryProgram.geometry = null;
  17621. _currentGeometryProgram.program = null;
  17622. _currentGeometryProgram.wireframe = false;
  17623. renderObjectImmediate( object, program );
  17624. } else {
  17625. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  17626. }
  17627. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17628. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  17629. }
  17630. function initMaterial( material, fog, object ) {
  17631. var materialProperties = properties.get( material );
  17632. var lights = currentRenderState.state.lights;
  17633. var shadowsArray = currentRenderState.state.shadowsArray;
  17634. var lightsHash = materialProperties.lightsHash;
  17635. var lightsStateHash = lights.state.hash;
  17636. var parameters = programCache.getParameters(
  17637. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  17638. var code = programCache.getProgramCode( material, parameters );
  17639. var program = materialProperties.program;
  17640. var programChange = true;
  17641. if ( program === undefined ) {
  17642. // new material
  17643. material.addEventListener( 'dispose', onMaterialDispose );
  17644. } else if ( program.code !== code ) {
  17645. // changed glsl or parameters
  17646. releaseMaterialProgramReference( material );
  17647. } else if ( lightsHash.stateID !== lightsStateHash.stateID ||
  17648. lightsHash.directionalLength !== lightsStateHash.directionalLength ||
  17649. lightsHash.pointLength !== lightsStateHash.pointLength ||
  17650. lightsHash.spotLength !== lightsStateHash.spotLength ||
  17651. lightsHash.rectAreaLength !== lightsStateHash.rectAreaLength ||
  17652. lightsHash.hemiLength !== lightsStateHash.hemiLength ||
  17653. lightsHash.shadowsLength !== lightsStateHash.shadowsLength ) {
  17654. lightsHash.stateID = lightsStateHash.stateID;
  17655. lightsHash.directionalLength = lightsStateHash.directionalLength;
  17656. lightsHash.pointLength = lightsStateHash.pointLength;
  17657. lightsHash.spotLength = lightsStateHash.spotLength;
  17658. lightsHash.rectAreaLength = lightsStateHash.rectAreaLength;
  17659. lightsHash.hemiLength = lightsStateHash.hemiLength;
  17660. lightsHash.shadowsLength = lightsStateHash.shadowsLength;
  17661. programChange = false;
  17662. } else if ( parameters.shaderID !== undefined ) {
  17663. // same glsl and uniform list
  17664. return;
  17665. } else {
  17666. // only rebuild uniform list
  17667. programChange = false;
  17668. }
  17669. if ( programChange ) {
  17670. if ( parameters.shaderID ) {
  17671. var shader = ShaderLib[ parameters.shaderID ];
  17672. materialProperties.shader = {
  17673. name: material.type,
  17674. uniforms: UniformsUtils.clone( shader.uniforms ),
  17675. vertexShader: shader.vertexShader,
  17676. fragmentShader: shader.fragmentShader
  17677. };
  17678. } else {
  17679. materialProperties.shader = {
  17680. name: material.type,
  17681. uniforms: material.uniforms,
  17682. vertexShader: material.vertexShader,
  17683. fragmentShader: material.fragmentShader
  17684. };
  17685. }
  17686. material.onBeforeCompile( materialProperties.shader, _this );
  17687. // Computing code again as onBeforeCompile may have changed the shaders
  17688. code = programCache.getProgramCode( material, parameters );
  17689. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  17690. materialProperties.program = program;
  17691. material.program = program;
  17692. }
  17693. var programAttributes = program.getAttributes();
  17694. if ( material.morphTargets ) {
  17695. material.numSupportedMorphTargets = 0;
  17696. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  17697. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  17698. material.numSupportedMorphTargets ++;
  17699. }
  17700. }
  17701. }
  17702. if ( material.morphNormals ) {
  17703. material.numSupportedMorphNormals = 0;
  17704. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  17705. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  17706. material.numSupportedMorphNormals ++;
  17707. }
  17708. }
  17709. }
  17710. var uniforms = materialProperties.shader.uniforms;
  17711. if ( ! material.isShaderMaterial &&
  17712. ! material.isRawShaderMaterial ||
  17713. material.clipping === true ) {
  17714. materialProperties.numClippingPlanes = _clipping.numPlanes;
  17715. materialProperties.numIntersection = _clipping.numIntersection;
  17716. uniforms.clippingPlanes = _clipping.uniform;
  17717. }
  17718. materialProperties.fog = fog;
  17719. // store the light setup it was created for
  17720. if ( lightsHash === undefined ) {
  17721. materialProperties.lightsHash = lightsHash = {};
  17722. }
  17723. lightsHash.stateID = lightsStateHash.stateID;
  17724. lightsHash.directionalLength = lightsStateHash.directionalLength;
  17725. lightsHash.pointLength = lightsStateHash.pointLength;
  17726. lightsHash.spotLength = lightsStateHash.spotLength;
  17727. lightsHash.rectAreaLength = lightsStateHash.rectAreaLength;
  17728. lightsHash.hemiLength = lightsStateHash.hemiLength;
  17729. lightsHash.shadowsLength = lightsStateHash.shadowsLength;
  17730. if ( material.lights ) {
  17731. // wire up the material to this renderer's lighting state
  17732. uniforms.ambientLightColor.value = lights.state.ambient;
  17733. uniforms.directionalLights.value = lights.state.directional;
  17734. uniforms.spotLights.value = lights.state.spot;
  17735. uniforms.rectAreaLights.value = lights.state.rectArea;
  17736. uniforms.pointLights.value = lights.state.point;
  17737. uniforms.hemisphereLights.value = lights.state.hemi;
  17738. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17739. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17740. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17741. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  17742. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17743. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17744. // TODO (abelnation): add area lights shadow info to uniforms
  17745. }
  17746. var progUniforms = materialProperties.program.getUniforms(),
  17747. uniformsList =
  17748. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17749. materialProperties.uniformsList = uniformsList;
  17750. }
  17751. function setProgram( camera, fog, material, object ) {
  17752. _usedTextureUnits = 0;
  17753. var materialProperties = properties.get( material );
  17754. var lights = currentRenderState.state.lights;
  17755. var lightsHash = materialProperties.lightsHash;
  17756. var lightsStateHash = lights.state.hash;
  17757. if ( _clippingEnabled ) {
  17758. if ( _localClippingEnabled || camera !== _currentCamera ) {
  17759. var useCache =
  17760. camera === _currentCamera &&
  17761. material.id === _currentMaterialId;
  17762. // we might want to call this function with some ClippingGroup
  17763. // object instead of the material, once it becomes feasible
  17764. // (#8465, #8379)
  17765. _clipping.setState(
  17766. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  17767. camera, materialProperties, useCache );
  17768. }
  17769. }
  17770. if ( material.needsUpdate === false ) {
  17771. if ( materialProperties.program === undefined ) {
  17772. material.needsUpdate = true;
  17773. } else if ( material.fog && materialProperties.fog !== fog ) {
  17774. material.needsUpdate = true;
  17775. } else if ( material.lights && ( lightsHash.stateID !== lightsStateHash.stateID ||
  17776. lightsHash.directionalLength !== lightsStateHash.directionalLength ||
  17777. lightsHash.pointLength !== lightsStateHash.pointLength ||
  17778. lightsHash.spotLength !== lightsStateHash.spotLength ||
  17779. lightsHash.rectAreaLength !== lightsStateHash.rectAreaLength ||
  17780. lightsHash.hemiLength !== lightsStateHash.hemiLength ||
  17781. lightsHash.shadowsLength !== lightsStateHash.shadowsLength ) ) {
  17782. material.needsUpdate = true;
  17783. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17784. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  17785. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  17786. material.needsUpdate = true;
  17787. }
  17788. }
  17789. if ( material.needsUpdate ) {
  17790. initMaterial( material, fog, object );
  17791. material.needsUpdate = false;
  17792. }
  17793. var refreshProgram = false;
  17794. var refreshMaterial = false;
  17795. var refreshLights = false;
  17796. var program = materialProperties.program,
  17797. p_uniforms = program.getUniforms(),
  17798. m_uniforms = materialProperties.shader.uniforms;
  17799. if ( state.useProgram( program.program ) ) {
  17800. refreshProgram = true;
  17801. refreshMaterial = true;
  17802. refreshLights = true;
  17803. }
  17804. if ( material.id !== _currentMaterialId ) {
  17805. _currentMaterialId = material.id;
  17806. refreshMaterial = true;
  17807. }
  17808. if ( refreshProgram || camera !== _currentCamera ) {
  17809. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17810. if ( capabilities.logarithmicDepthBuffer ) {
  17811. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17812. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17813. }
  17814. // Avoid unneeded uniform updates per ArrayCamera's sub-camera
  17815. if ( _currentCamera !== ( _currentArrayCamera || camera ) ) {
  17816. _currentCamera = ( _currentArrayCamera || camera );
  17817. // lighting uniforms depend on the camera so enforce an update
  17818. // now, in case this material supports lights - or later, when
  17819. // the next material that does gets activated:
  17820. refreshMaterial = true; // set to true on material change
  17821. refreshLights = true; // remains set until update done
  17822. }
  17823. // load material specific uniforms
  17824. // (shader material also gets them for the sake of genericity)
  17825. if ( material.isShaderMaterial ||
  17826. material.isMeshPhongMaterial ||
  17827. material.isMeshStandardMaterial ||
  17828. material.envMap ) {
  17829. var uCamPos = p_uniforms.map.cameraPosition;
  17830. if ( uCamPos !== undefined ) {
  17831. uCamPos.setValue( _gl,
  17832. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17833. }
  17834. }
  17835. if ( material.isMeshPhongMaterial ||
  17836. material.isMeshLambertMaterial ||
  17837. material.isMeshBasicMaterial ||
  17838. material.isMeshStandardMaterial ||
  17839. material.isShaderMaterial ||
  17840. material.skinning ) {
  17841. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17842. }
  17843. }
  17844. // skinning uniforms must be set even if material didn't change
  17845. // auto-setting of texture unit for bone texture must go before other textures
  17846. // not sure why, but otherwise weird things happen
  17847. if ( material.skinning ) {
  17848. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17849. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17850. var skeleton = object.skeleton;
  17851. if ( skeleton ) {
  17852. var bones = skeleton.bones;
  17853. if ( capabilities.floatVertexTextures ) {
  17854. if ( skeleton.boneTexture === undefined ) {
  17855. // layout (1 matrix = 4 pixels)
  17856. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17857. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17858. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17859. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17860. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17861. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  17862. size = _Math.ceilPowerOfTwo( size );
  17863. size = Math.max( size, 4 );
  17864. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17865. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  17866. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17867. boneTexture.needsUpdate = true;
  17868. skeleton.boneMatrices = boneMatrices;
  17869. skeleton.boneTexture = boneTexture;
  17870. skeleton.boneTextureSize = size;
  17871. }
  17872. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  17873. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17874. } else {
  17875. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  17876. }
  17877. }
  17878. }
  17879. if ( refreshMaterial ) {
  17880. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17881. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  17882. if ( material.lights ) {
  17883. // the current material requires lighting info
  17884. // note: all lighting uniforms are always set correctly
  17885. // they simply reference the renderer's state for their
  17886. // values
  17887. //
  17888. // use the current material's .needsUpdate flags to set
  17889. // the GL state when required
  17890. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17891. }
  17892. // refresh uniforms common to several materials
  17893. if ( fog && material.fog ) {
  17894. refreshUniformsFog( m_uniforms, fog );
  17895. }
  17896. if ( material.isMeshBasicMaterial ) {
  17897. refreshUniformsCommon( m_uniforms, material );
  17898. } else if ( material.isMeshLambertMaterial ) {
  17899. refreshUniformsCommon( m_uniforms, material );
  17900. refreshUniformsLambert( m_uniforms, material );
  17901. } else if ( material.isMeshPhongMaterial ) {
  17902. refreshUniformsCommon( m_uniforms, material );
  17903. if ( material.isMeshToonMaterial ) {
  17904. refreshUniformsToon( m_uniforms, material );
  17905. } else {
  17906. refreshUniformsPhong( m_uniforms, material );
  17907. }
  17908. } else if ( material.isMeshStandardMaterial ) {
  17909. refreshUniformsCommon( m_uniforms, material );
  17910. if ( material.isMeshPhysicalMaterial ) {
  17911. refreshUniformsPhysical( m_uniforms, material );
  17912. } else {
  17913. refreshUniformsStandard( m_uniforms, material );
  17914. }
  17915. } else if ( material.isMeshDepthMaterial ) {
  17916. refreshUniformsCommon( m_uniforms, material );
  17917. refreshUniformsDepth( m_uniforms, material );
  17918. } else if ( material.isMeshDistanceMaterial ) {
  17919. refreshUniformsCommon( m_uniforms, material );
  17920. refreshUniformsDistance( m_uniforms, material );
  17921. } else if ( material.isMeshNormalMaterial ) {
  17922. refreshUniformsCommon( m_uniforms, material );
  17923. refreshUniformsNormal( m_uniforms, material );
  17924. } else if ( material.isLineBasicMaterial ) {
  17925. refreshUniformsLine( m_uniforms, material );
  17926. if ( material.isLineDashedMaterial ) {
  17927. refreshUniformsDash( m_uniforms, material );
  17928. }
  17929. } else if ( material.isPointsMaterial ) {
  17930. refreshUniformsPoints( m_uniforms, material );
  17931. } else if ( material.isSpriteMaterial ) {
  17932. refreshUniformsSprites( m_uniforms, material );
  17933. } else if ( material.isShadowMaterial ) {
  17934. m_uniforms.color.value = material.color;
  17935. m_uniforms.opacity.value = material.opacity;
  17936. }
  17937. // RectAreaLight Texture
  17938. // TODO (mrdoob): Find a nicer implementation
  17939. if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  17940. if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  17941. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  17942. }
  17943. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17944. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  17945. material.uniformsNeedUpdate = false;
  17946. }
  17947. if ( material.isSpriteMaterial ) {
  17948. p_uniforms.setValue( _gl, 'center', object.center );
  17949. }
  17950. // common matrices
  17951. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17952. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17953. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17954. return program;
  17955. }
  17956. // Uniforms (refresh uniforms objects)
  17957. function refreshUniformsCommon( uniforms, material ) {
  17958. uniforms.opacity.value = material.opacity;
  17959. if ( material.color ) {
  17960. uniforms.diffuse.value = material.color;
  17961. }
  17962. if ( material.emissive ) {
  17963. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  17964. }
  17965. if ( material.map ) {
  17966. uniforms.map.value = material.map;
  17967. }
  17968. if ( material.alphaMap ) {
  17969. uniforms.alphaMap.value = material.alphaMap;
  17970. }
  17971. if ( material.specularMap ) {
  17972. uniforms.specularMap.value = material.specularMap;
  17973. }
  17974. if ( material.envMap ) {
  17975. uniforms.envMap.value = material.envMap;
  17976. // don't flip CubeTexture envMaps, flip everything else:
  17977. // WebGLRenderTargetCube will be flipped for backwards compatibility
  17978. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  17979. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  17980. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  17981. uniforms.reflectivity.value = material.reflectivity;
  17982. uniforms.refractionRatio.value = material.refractionRatio;
  17983. uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel;
  17984. }
  17985. if ( material.lightMap ) {
  17986. uniforms.lightMap.value = material.lightMap;
  17987. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  17988. }
  17989. if ( material.aoMap ) {
  17990. uniforms.aoMap.value = material.aoMap;
  17991. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  17992. }
  17993. // uv repeat and offset setting priorities
  17994. // 1. color map
  17995. // 2. specular map
  17996. // 3. normal map
  17997. // 4. bump map
  17998. // 5. alpha map
  17999. // 6. emissive map
  18000. var uvScaleMap;
  18001. if ( material.map ) {
  18002. uvScaleMap = material.map;
  18003. } else if ( material.specularMap ) {
  18004. uvScaleMap = material.specularMap;
  18005. } else if ( material.displacementMap ) {
  18006. uvScaleMap = material.displacementMap;
  18007. } else if ( material.normalMap ) {
  18008. uvScaleMap = material.normalMap;
  18009. } else if ( material.bumpMap ) {
  18010. uvScaleMap = material.bumpMap;
  18011. } else if ( material.roughnessMap ) {
  18012. uvScaleMap = material.roughnessMap;
  18013. } else if ( material.metalnessMap ) {
  18014. uvScaleMap = material.metalnessMap;
  18015. } else if ( material.alphaMap ) {
  18016. uvScaleMap = material.alphaMap;
  18017. } else if ( material.emissiveMap ) {
  18018. uvScaleMap = material.emissiveMap;
  18019. }
  18020. if ( uvScaleMap !== undefined ) {
  18021. // backwards compatibility
  18022. if ( uvScaleMap.isWebGLRenderTarget ) {
  18023. uvScaleMap = uvScaleMap.texture;
  18024. }
  18025. if ( uvScaleMap.matrixAutoUpdate === true ) {
  18026. uvScaleMap.updateMatrix();
  18027. }
  18028. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  18029. }
  18030. }
  18031. function refreshUniformsLine( uniforms, material ) {
  18032. uniforms.diffuse.value = material.color;
  18033. uniforms.opacity.value = material.opacity;
  18034. }
  18035. function refreshUniformsDash( uniforms, material ) {
  18036. uniforms.dashSize.value = material.dashSize;
  18037. uniforms.totalSize.value = material.dashSize + material.gapSize;
  18038. uniforms.scale.value = material.scale;
  18039. }
  18040. function refreshUniformsPoints( uniforms, material ) {
  18041. uniforms.diffuse.value = material.color;
  18042. uniforms.opacity.value = material.opacity;
  18043. uniforms.size.value = material.size * _pixelRatio;
  18044. uniforms.scale.value = _height * 0.5;
  18045. uniforms.map.value = material.map;
  18046. if ( material.map !== null ) {
  18047. if ( material.map.matrixAutoUpdate === true ) {
  18048. material.map.updateMatrix();
  18049. }
  18050. uniforms.uvTransform.value.copy( material.map.matrix );
  18051. }
  18052. }
  18053. function refreshUniformsSprites( uniforms, material ) {
  18054. uniforms.diffuse.value = material.color;
  18055. uniforms.opacity.value = material.opacity;
  18056. uniforms.rotation.value = material.rotation;
  18057. uniforms.map.value = material.map;
  18058. if ( material.map !== null ) {
  18059. if ( material.map.matrixAutoUpdate === true ) {
  18060. material.map.updateMatrix();
  18061. }
  18062. uniforms.uvTransform.value.copy( material.map.matrix );
  18063. }
  18064. }
  18065. function refreshUniformsFog( uniforms, fog ) {
  18066. uniforms.fogColor.value = fog.color;
  18067. if ( fog.isFog ) {
  18068. uniforms.fogNear.value = fog.near;
  18069. uniforms.fogFar.value = fog.far;
  18070. } else if ( fog.isFogExp2 ) {
  18071. uniforms.fogDensity.value = fog.density;
  18072. }
  18073. }
  18074. function refreshUniformsLambert( uniforms, material ) {
  18075. if ( material.emissiveMap ) {
  18076. uniforms.emissiveMap.value = material.emissiveMap;
  18077. }
  18078. }
  18079. function refreshUniformsPhong( uniforms, material ) {
  18080. uniforms.specular.value = material.specular;
  18081. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  18082. if ( material.emissiveMap ) {
  18083. uniforms.emissiveMap.value = material.emissiveMap;
  18084. }
  18085. if ( material.bumpMap ) {
  18086. uniforms.bumpMap.value = material.bumpMap;
  18087. uniforms.bumpScale.value = material.bumpScale;
  18088. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  18089. }
  18090. if ( material.normalMap ) {
  18091. uniforms.normalMap.value = material.normalMap;
  18092. uniforms.normalScale.value.copy( material.normalScale );
  18093. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  18094. }
  18095. if ( material.displacementMap ) {
  18096. uniforms.displacementMap.value = material.displacementMap;
  18097. uniforms.displacementScale.value = material.displacementScale;
  18098. uniforms.displacementBias.value = material.displacementBias;
  18099. }
  18100. }
  18101. function refreshUniformsToon( uniforms, material ) {
  18102. refreshUniformsPhong( uniforms, material );
  18103. if ( material.gradientMap ) {
  18104. uniforms.gradientMap.value = material.gradientMap;
  18105. }
  18106. }
  18107. function refreshUniformsStandard( uniforms, material ) {
  18108. uniforms.roughness.value = material.roughness;
  18109. uniforms.metalness.value = material.metalness;
  18110. if ( material.roughnessMap ) {
  18111. uniforms.roughnessMap.value = material.roughnessMap;
  18112. }
  18113. if ( material.metalnessMap ) {
  18114. uniforms.metalnessMap.value = material.metalnessMap;
  18115. }
  18116. if ( material.emissiveMap ) {
  18117. uniforms.emissiveMap.value = material.emissiveMap;
  18118. }
  18119. if ( material.bumpMap ) {
  18120. uniforms.bumpMap.value = material.bumpMap;
  18121. uniforms.bumpScale.value = material.bumpScale;
  18122. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  18123. }
  18124. if ( material.normalMap ) {
  18125. uniforms.normalMap.value = material.normalMap;
  18126. uniforms.normalScale.value.copy( material.normalScale );
  18127. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  18128. }
  18129. if ( material.displacementMap ) {
  18130. uniforms.displacementMap.value = material.displacementMap;
  18131. uniforms.displacementScale.value = material.displacementScale;
  18132. uniforms.displacementBias.value = material.displacementBias;
  18133. }
  18134. if ( material.envMap ) {
  18135. //uniforms.envMap.value = material.envMap; // part of uniforms common
  18136. uniforms.envMapIntensity.value = material.envMapIntensity;
  18137. }
  18138. }
  18139. function refreshUniformsPhysical( uniforms, material ) {
  18140. refreshUniformsStandard( uniforms, material );
  18141. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  18142. uniforms.clearCoat.value = material.clearCoat;
  18143. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  18144. }
  18145. function refreshUniformsDepth( uniforms, material ) {
  18146. if ( material.displacementMap ) {
  18147. uniforms.displacementMap.value = material.displacementMap;
  18148. uniforms.displacementScale.value = material.displacementScale;
  18149. uniforms.displacementBias.value = material.displacementBias;
  18150. }
  18151. }
  18152. function refreshUniformsDistance( uniforms, material ) {
  18153. if ( material.displacementMap ) {
  18154. uniforms.displacementMap.value = material.displacementMap;
  18155. uniforms.displacementScale.value = material.displacementScale;
  18156. uniforms.displacementBias.value = material.displacementBias;
  18157. }
  18158. uniforms.referencePosition.value.copy( material.referencePosition );
  18159. uniforms.nearDistance.value = material.nearDistance;
  18160. uniforms.farDistance.value = material.farDistance;
  18161. }
  18162. function refreshUniformsNormal( uniforms, material ) {
  18163. if ( material.bumpMap ) {
  18164. uniforms.bumpMap.value = material.bumpMap;
  18165. uniforms.bumpScale.value = material.bumpScale;
  18166. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  18167. }
  18168. if ( material.normalMap ) {
  18169. uniforms.normalMap.value = material.normalMap;
  18170. uniforms.normalScale.value.copy( material.normalScale );
  18171. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  18172. }
  18173. if ( material.displacementMap ) {
  18174. uniforms.displacementMap.value = material.displacementMap;
  18175. uniforms.displacementScale.value = material.displacementScale;
  18176. uniforms.displacementBias.value = material.displacementBias;
  18177. }
  18178. }
  18179. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  18180. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  18181. uniforms.ambientLightColor.needsUpdate = value;
  18182. uniforms.directionalLights.needsUpdate = value;
  18183. uniforms.pointLights.needsUpdate = value;
  18184. uniforms.spotLights.needsUpdate = value;
  18185. uniforms.rectAreaLights.needsUpdate = value;
  18186. uniforms.hemisphereLights.needsUpdate = value;
  18187. }
  18188. // Textures
  18189. function allocTextureUnit() {
  18190. var textureUnit = _usedTextureUnits;
  18191. if ( textureUnit >= capabilities.maxTextures ) {
  18192. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  18193. }
  18194. _usedTextureUnits += 1;
  18195. return textureUnit;
  18196. }
  18197. this.allocTextureUnit = allocTextureUnit;
  18198. // this.setTexture2D = setTexture2D;
  18199. this.setTexture2D = ( function () {
  18200. var warned = false;
  18201. // backwards compatibility: peel texture.texture
  18202. return function setTexture2D( texture, slot ) {
  18203. if ( texture && texture.isWebGLRenderTarget ) {
  18204. if ( ! warned ) {
  18205. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  18206. warned = true;
  18207. }
  18208. texture = texture.texture;
  18209. }
  18210. textures.setTexture2D( texture, slot );
  18211. };
  18212. }() );
  18213. this.setTexture = ( function () {
  18214. var warned = false;
  18215. return function setTexture( texture, slot ) {
  18216. if ( ! warned ) {
  18217. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  18218. warned = true;
  18219. }
  18220. textures.setTexture2D( texture, slot );
  18221. };
  18222. }() );
  18223. this.setTextureCube = ( function () {
  18224. var warned = false;
  18225. return function setTextureCube( texture, slot ) {
  18226. // backwards compatibility: peel texture.texture
  18227. if ( texture && texture.isWebGLRenderTargetCube ) {
  18228. if ( ! warned ) {
  18229. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  18230. warned = true;
  18231. }
  18232. texture = texture.texture;
  18233. }
  18234. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  18235. // TODO: unify these code paths
  18236. if ( ( texture && texture.isCubeTexture ) ||
  18237. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  18238. // CompressedTexture can have Array in image :/
  18239. // this function alone should take care of cube textures
  18240. textures.setTextureCube( texture, slot );
  18241. } else {
  18242. // assumed: texture property of THREE.WebGLRenderTargetCube
  18243. textures.setTextureCubeDynamic( texture, slot );
  18244. }
  18245. };
  18246. }() );
  18247. //
  18248. this.setFramebuffer = function ( value ) {
  18249. _framebuffer = value;
  18250. };
  18251. this.getRenderTarget = function () {
  18252. return _currentRenderTarget;
  18253. };
  18254. this.setRenderTarget = function ( renderTarget ) {
  18255. _currentRenderTarget = renderTarget;
  18256. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  18257. textures.setupRenderTarget( renderTarget );
  18258. }
  18259. var framebuffer = _framebuffer;
  18260. var isCube = false;
  18261. if ( renderTarget ) {
  18262. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18263. if ( renderTarget.isWebGLRenderTargetCube ) {
  18264. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  18265. isCube = true;
  18266. } else {
  18267. framebuffer = __webglFramebuffer;
  18268. }
  18269. _currentViewport.copy( renderTarget.viewport );
  18270. _currentScissor.copy( renderTarget.scissor );
  18271. _currentScissorTest = renderTarget.scissorTest;
  18272. } else {
  18273. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  18274. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  18275. _currentScissorTest = _scissorTest;
  18276. }
  18277. if ( _currentFramebuffer !== framebuffer ) {
  18278. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18279. _currentFramebuffer = framebuffer;
  18280. }
  18281. state.viewport( _currentViewport );
  18282. state.scissor( _currentScissor );
  18283. state.setScissorTest( _currentScissorTest );
  18284. if ( isCube ) {
  18285. var textureProperties = properties.get( renderTarget.texture );
  18286. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  18287. }
  18288. };
  18289. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  18290. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18291. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18292. return;
  18293. }
  18294. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18295. if ( framebuffer ) {
  18296. var restore = false;
  18297. if ( framebuffer !== _currentFramebuffer ) {
  18298. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18299. restore = true;
  18300. }
  18301. try {
  18302. var texture = renderTarget.texture;
  18303. var textureFormat = texture.format;
  18304. var textureType = texture.type;
  18305. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  18306. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18307. return;
  18308. }
  18309. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  18310. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  18311. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  18312. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18313. return;
  18314. }
  18315. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  18316. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18317. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18318. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18319. }
  18320. } else {
  18321. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  18322. }
  18323. } finally {
  18324. if ( restore ) {
  18325. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  18326. }
  18327. }
  18328. }
  18329. };
  18330. this.copyFramebufferToTexture = function ( position, texture, level ) {
  18331. var width = texture.image.width;
  18332. var height = texture.image.height;
  18333. var glFormat = utils.convert( texture.format );
  18334. this.setTexture2D( texture, 0 );
  18335. _gl.copyTexImage2D( _gl.TEXTURE_2D, level || 0, glFormat, position.x, position.y, width, height, 0 );
  18336. };
  18337. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  18338. var width = srcTexture.image.width;
  18339. var height = srcTexture.image.height;
  18340. var glFormat = utils.convert( dstTexture.format );
  18341. var glType = utils.convert( dstTexture.type );
  18342. this.setTexture2D( dstTexture, 0 );
  18343. if ( srcTexture.isDataTexture ) {
  18344. _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  18345. } else {
  18346. _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, glFormat, glType, srcTexture.image );
  18347. }
  18348. };
  18349. }
  18350. /**
  18351. * @author mrdoob / http://mrdoob.com/
  18352. * @author alteredq / http://alteredqualia.com/
  18353. */
  18354. function FogExp2( color, density ) {
  18355. this.name = '';
  18356. this.color = new Color( color );
  18357. this.density = ( density !== undefined ) ? density : 0.00025;
  18358. }
  18359. FogExp2.prototype.isFogExp2 = true;
  18360. FogExp2.prototype.clone = function () {
  18361. return new FogExp2( this.color, this.density );
  18362. };
  18363. FogExp2.prototype.toJSON = function ( /* meta */ ) {
  18364. return {
  18365. type: 'FogExp2',
  18366. color: this.color.getHex(),
  18367. density: this.density
  18368. };
  18369. };
  18370. /**
  18371. * @author mrdoob / http://mrdoob.com/
  18372. * @author alteredq / http://alteredqualia.com/
  18373. */
  18374. function Fog( color, near, far ) {
  18375. this.name = '';
  18376. this.color = new Color( color );
  18377. this.near = ( near !== undefined ) ? near : 1;
  18378. this.far = ( far !== undefined ) ? far : 1000;
  18379. }
  18380. Fog.prototype.isFog = true;
  18381. Fog.prototype.clone = function () {
  18382. return new Fog( this.color, this.near, this.far );
  18383. };
  18384. Fog.prototype.toJSON = function ( /* meta */ ) {
  18385. return {
  18386. type: 'Fog',
  18387. color: this.color.getHex(),
  18388. near: this.near,
  18389. far: this.far
  18390. };
  18391. };
  18392. /**
  18393. * @author mrdoob / http://mrdoob.com/
  18394. */
  18395. function Scene() {
  18396. Object3D.call( this );
  18397. this.type = 'Scene';
  18398. this.background = null;
  18399. this.fog = null;
  18400. this.overrideMaterial = null;
  18401. this.autoUpdate = true; // checked by the renderer
  18402. }
  18403. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18404. constructor: Scene,
  18405. copy: function ( source, recursive ) {
  18406. Object3D.prototype.copy.call( this, source, recursive );
  18407. if ( source.background !== null ) this.background = source.background.clone();
  18408. if ( source.fog !== null ) this.fog = source.fog.clone();
  18409. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18410. this.autoUpdate = source.autoUpdate;
  18411. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18412. return this;
  18413. },
  18414. toJSON: function ( meta ) {
  18415. var data = Object3D.prototype.toJSON.call( this, meta );
  18416. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  18417. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18418. return data;
  18419. }
  18420. } );
  18421. /**
  18422. * @author benaadams / https://twitter.com/ben_a_adams
  18423. */
  18424. function InterleavedBuffer( array, stride ) {
  18425. this.array = array;
  18426. this.stride = stride;
  18427. this.count = array !== undefined ? array.length / stride : 0;
  18428. this.dynamic = false;
  18429. this.updateRange = { offset: 0, count: - 1 };
  18430. this.version = 0;
  18431. }
  18432. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  18433. set: function ( value ) {
  18434. if ( value === true ) this.version ++;
  18435. }
  18436. } );
  18437. Object.assign( InterleavedBuffer.prototype, {
  18438. isInterleavedBuffer: true,
  18439. onUploadCallback: function () {},
  18440. setArray: function ( array ) {
  18441. if ( Array.isArray( array ) ) {
  18442. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  18443. }
  18444. this.count = array !== undefined ? array.length / this.stride : 0;
  18445. this.array = array;
  18446. return this;
  18447. },
  18448. setDynamic: function ( value ) {
  18449. this.dynamic = value;
  18450. return this;
  18451. },
  18452. copy: function ( source ) {
  18453. this.array = new source.array.constructor( source.array );
  18454. this.count = source.count;
  18455. this.stride = source.stride;
  18456. this.dynamic = source.dynamic;
  18457. return this;
  18458. },
  18459. copyAt: function ( index1, attribute, index2 ) {
  18460. index1 *= this.stride;
  18461. index2 *= attribute.stride;
  18462. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  18463. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18464. }
  18465. return this;
  18466. },
  18467. set: function ( value, offset ) {
  18468. if ( offset === undefined ) offset = 0;
  18469. this.array.set( value, offset );
  18470. return this;
  18471. },
  18472. clone: function () {
  18473. return new this.constructor().copy( this );
  18474. },
  18475. onUpload: function ( callback ) {
  18476. this.onUploadCallback = callback;
  18477. return this;
  18478. }
  18479. } );
  18480. /**
  18481. * @author benaadams / https://twitter.com/ben_a_adams
  18482. */
  18483. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  18484. this.data = interleavedBuffer;
  18485. this.itemSize = itemSize;
  18486. this.offset = offset;
  18487. this.normalized = normalized === true;
  18488. }
  18489. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  18490. count: {
  18491. get: function () {
  18492. return this.data.count;
  18493. }
  18494. },
  18495. array: {
  18496. get: function () {
  18497. return this.data.array;
  18498. }
  18499. }
  18500. } );
  18501. Object.assign( InterleavedBufferAttribute.prototype, {
  18502. isInterleavedBufferAttribute: true,
  18503. setX: function ( index, x ) {
  18504. this.data.array[ index * this.data.stride + this.offset ] = x;
  18505. return this;
  18506. },
  18507. setY: function ( index, y ) {
  18508. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18509. return this;
  18510. },
  18511. setZ: function ( index, z ) {
  18512. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18513. return this;
  18514. },
  18515. setW: function ( index, w ) {
  18516. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18517. return this;
  18518. },
  18519. getX: function ( index ) {
  18520. return this.data.array[ index * this.data.stride + this.offset ];
  18521. },
  18522. getY: function ( index ) {
  18523. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  18524. },
  18525. getZ: function ( index ) {
  18526. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  18527. },
  18528. getW: function ( index ) {
  18529. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  18530. },
  18531. setXY: function ( index, x, y ) {
  18532. index = index * this.data.stride + this.offset;
  18533. this.data.array[ index + 0 ] = x;
  18534. this.data.array[ index + 1 ] = y;
  18535. return this;
  18536. },
  18537. setXYZ: function ( index, x, y, z ) {
  18538. index = index * this.data.stride + this.offset;
  18539. this.data.array[ index + 0 ] = x;
  18540. this.data.array[ index + 1 ] = y;
  18541. this.data.array[ index + 2 ] = z;
  18542. return this;
  18543. },
  18544. setXYZW: function ( index, x, y, z, w ) {
  18545. index = index * this.data.stride + this.offset;
  18546. this.data.array[ index + 0 ] = x;
  18547. this.data.array[ index + 1 ] = y;
  18548. this.data.array[ index + 2 ] = z;
  18549. this.data.array[ index + 3 ] = w;
  18550. return this;
  18551. }
  18552. } );
  18553. /**
  18554. * @author alteredq / http://alteredqualia.com/
  18555. *
  18556. * parameters = {
  18557. * color: <hex>,
  18558. * opacity: <float>,
  18559. * map: new THREE.Texture( <Image> ),
  18560. *
  18561. * uvOffset: new THREE.Vector2(),
  18562. * uvScale: new THREE.Vector2()
  18563. * }
  18564. */
  18565. function SpriteMaterial( parameters ) {
  18566. Material.call( this );
  18567. this.type = 'SpriteMaterial';
  18568. this.color = new Color( 0xffffff );
  18569. this.map = null;
  18570. this.rotation = 0;
  18571. this.lights = false;
  18572. this.transparent = true;
  18573. this.setValues( parameters );
  18574. }
  18575. SpriteMaterial.prototype = Object.create( Material.prototype );
  18576. SpriteMaterial.prototype.constructor = SpriteMaterial;
  18577. SpriteMaterial.prototype.isSpriteMaterial = true;
  18578. SpriteMaterial.prototype.copy = function ( source ) {
  18579. Material.prototype.copy.call( this, source );
  18580. this.color.copy( source.color );
  18581. this.map = source.map;
  18582. this.rotation = source.rotation;
  18583. return this;
  18584. };
  18585. /**
  18586. * @author mikael emtinger / http://gomo.se/
  18587. * @author alteredq / http://alteredqualia.com/
  18588. */
  18589. var geometry;
  18590. function Sprite( material ) {
  18591. Object3D.call( this );
  18592. this.type = 'Sprite';
  18593. if ( geometry === undefined ) {
  18594. geometry = new BufferGeometry();
  18595. var float32Array = new Float32Array( [
  18596. - 0.5, - 0.5, 0, 0, 0,
  18597. 0.5, - 0.5, 0, 1, 0,
  18598. 0.5, 0.5, 0, 1, 1,
  18599. - 0.5, 0.5, 0, 0, 1
  18600. ] );
  18601. var interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18602. geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18603. geometry.addAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18604. geometry.addAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18605. }
  18606. this.geometry = geometry;
  18607. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18608. this.center = new Vector2( 0.5, 0.5 );
  18609. }
  18610. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18611. constructor: Sprite,
  18612. isSprite: true,
  18613. raycast: ( function () {
  18614. var intersectPoint = new Vector3();
  18615. var worldScale = new Vector3();
  18616. var mvPosition = new Vector3();
  18617. var alignedPosition = new Vector2();
  18618. var rotatedPosition = new Vector2();
  18619. var viewWorldMatrix = new Matrix4();
  18620. var vA = new Vector3();
  18621. var vB = new Vector3();
  18622. var vC = new Vector3();
  18623. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18624. // compute position in camera space
  18625. alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18626. // to check if rotation is not zero
  18627. if ( sin !== undefined ) {
  18628. rotatedPosition.x = ( cos * alignedPosition.x ) - ( sin * alignedPosition.y );
  18629. rotatedPosition.y = ( sin * alignedPosition.x ) + ( cos * alignedPosition.y );
  18630. } else {
  18631. rotatedPosition.copy( alignedPosition );
  18632. }
  18633. vertexPosition.copy( mvPosition );
  18634. vertexPosition.x += rotatedPosition.x;
  18635. vertexPosition.y += rotatedPosition.y;
  18636. // transform to world space
  18637. vertexPosition.applyMatrix4( viewWorldMatrix );
  18638. }
  18639. return function raycast( raycaster, intersects ) {
  18640. worldScale.setFromMatrixScale( this.matrixWorld );
  18641. viewWorldMatrix.getInverse( this.modelViewMatrix ).premultiply( this.matrixWorld );
  18642. mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18643. var rotation = this.material.rotation;
  18644. var sin, cos;
  18645. if ( rotation !== 0 ) {
  18646. cos = Math.cos( rotation );
  18647. sin = Math.sin( rotation );
  18648. }
  18649. var center = this.center;
  18650. transformVertex( vA.set( - 0.5, - 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  18651. transformVertex( vB.set( 0.5, - 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  18652. transformVertex( vC.set( 0.5, 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  18653. // check first triangle
  18654. var intersect = raycaster.ray.intersectTriangle( vA, vB, vC, false, intersectPoint );
  18655. if ( intersect === null ) {
  18656. // check second triangle
  18657. transformVertex( vB.set( - 0.5, 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  18658. intersect = raycaster.ray.intersectTriangle( vA, vC, vB, false, intersectPoint );
  18659. if ( intersect === null ) {
  18660. return;
  18661. }
  18662. }
  18663. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18664. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18665. intersects.push( {
  18666. distance: distance,
  18667. point: intersectPoint.clone(),
  18668. face: null,
  18669. object: this
  18670. } );
  18671. };
  18672. }() ),
  18673. clone: function () {
  18674. return new this.constructor( this.material ).copy( this );
  18675. },
  18676. copy: function ( source ) {
  18677. Object3D.prototype.copy.call( this, source );
  18678. if ( source.center !== undefined ) this.center.copy( source.center );
  18679. return this;
  18680. }
  18681. } );
  18682. /**
  18683. * @author mikael emtinger / http://gomo.se/
  18684. * @author alteredq / http://alteredqualia.com/
  18685. * @author mrdoob / http://mrdoob.com/
  18686. */
  18687. function LOD() {
  18688. Object3D.call( this );
  18689. this.type = 'LOD';
  18690. Object.defineProperties( this, {
  18691. levels: {
  18692. enumerable: true,
  18693. value: []
  18694. }
  18695. } );
  18696. }
  18697. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18698. constructor: LOD,
  18699. copy: function ( source ) {
  18700. Object3D.prototype.copy.call( this, source, false );
  18701. var levels = source.levels;
  18702. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18703. var level = levels[ i ];
  18704. this.addLevel( level.object.clone(), level.distance );
  18705. }
  18706. return this;
  18707. },
  18708. addLevel: function ( object, distance ) {
  18709. if ( distance === undefined ) distance = 0;
  18710. distance = Math.abs( distance );
  18711. var levels = this.levels;
  18712. for ( var l = 0; l < levels.length; l ++ ) {
  18713. if ( distance < levels[ l ].distance ) {
  18714. break;
  18715. }
  18716. }
  18717. levels.splice( l, 0, { distance: distance, object: object } );
  18718. this.add( object );
  18719. },
  18720. getObjectForDistance: function ( distance ) {
  18721. var levels = this.levels;
  18722. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18723. if ( distance < levels[ i ].distance ) {
  18724. break;
  18725. }
  18726. }
  18727. return levels[ i - 1 ].object;
  18728. },
  18729. raycast: ( function () {
  18730. var matrixPosition = new Vector3();
  18731. return function raycast( raycaster, intersects ) {
  18732. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  18733. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  18734. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18735. };
  18736. }() ),
  18737. update: function () {
  18738. var v1 = new Vector3();
  18739. var v2 = new Vector3();
  18740. return function update( camera ) {
  18741. var levels = this.levels;
  18742. if ( levels.length > 1 ) {
  18743. v1.setFromMatrixPosition( camera.matrixWorld );
  18744. v2.setFromMatrixPosition( this.matrixWorld );
  18745. var distance = v1.distanceTo( v2 );
  18746. levels[ 0 ].object.visible = true;
  18747. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18748. if ( distance >= levels[ i ].distance ) {
  18749. levels[ i - 1 ].object.visible = false;
  18750. levels[ i ].object.visible = true;
  18751. } else {
  18752. break;
  18753. }
  18754. }
  18755. for ( ; i < l; i ++ ) {
  18756. levels[ i ].object.visible = false;
  18757. }
  18758. }
  18759. };
  18760. }(),
  18761. toJSON: function ( meta ) {
  18762. var data = Object3D.prototype.toJSON.call( this, meta );
  18763. data.object.levels = [];
  18764. var levels = this.levels;
  18765. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18766. var level = levels[ i ];
  18767. data.object.levels.push( {
  18768. object: level.object.uuid,
  18769. distance: level.distance
  18770. } );
  18771. }
  18772. return data;
  18773. }
  18774. } );
  18775. /**
  18776. * @author mikael emtinger / http://gomo.se/
  18777. * @author alteredq / http://alteredqualia.com/
  18778. * @author michael guerrero / http://realitymeltdown.com
  18779. * @author ikerr / http://verold.com
  18780. */
  18781. function Skeleton( bones, boneInverses ) {
  18782. // copy the bone array
  18783. bones = bones || [];
  18784. this.bones = bones.slice( 0 );
  18785. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  18786. // use the supplied bone inverses or calculate the inverses
  18787. if ( boneInverses === undefined ) {
  18788. this.calculateInverses();
  18789. } else {
  18790. if ( this.bones.length === boneInverses.length ) {
  18791. this.boneInverses = boneInverses.slice( 0 );
  18792. } else {
  18793. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  18794. this.boneInverses = [];
  18795. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18796. this.boneInverses.push( new Matrix4() );
  18797. }
  18798. }
  18799. }
  18800. }
  18801. Object.assign( Skeleton.prototype, {
  18802. calculateInverses: function () {
  18803. this.boneInverses = [];
  18804. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18805. var inverse = new Matrix4();
  18806. if ( this.bones[ i ] ) {
  18807. inverse.getInverse( this.bones[ i ].matrixWorld );
  18808. }
  18809. this.boneInverses.push( inverse );
  18810. }
  18811. },
  18812. pose: function () {
  18813. var bone, i, il;
  18814. // recover the bind-time world matrices
  18815. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  18816. bone = this.bones[ i ];
  18817. if ( bone ) {
  18818. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  18819. }
  18820. }
  18821. // compute the local matrices, positions, rotations and scales
  18822. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  18823. bone = this.bones[ i ];
  18824. if ( bone ) {
  18825. if ( bone.parent && bone.parent.isBone ) {
  18826. bone.matrix.getInverse( bone.parent.matrixWorld );
  18827. bone.matrix.multiply( bone.matrixWorld );
  18828. } else {
  18829. bone.matrix.copy( bone.matrixWorld );
  18830. }
  18831. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18832. }
  18833. }
  18834. },
  18835. update: ( function () {
  18836. var offsetMatrix = new Matrix4();
  18837. var identityMatrix = new Matrix4();
  18838. return function update() {
  18839. var bones = this.bones;
  18840. var boneInverses = this.boneInverses;
  18841. var boneMatrices = this.boneMatrices;
  18842. var boneTexture = this.boneTexture;
  18843. // flatten bone matrices to array
  18844. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  18845. // compute the offset between the current and the original transform
  18846. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  18847. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18848. offsetMatrix.toArray( boneMatrices, i * 16 );
  18849. }
  18850. if ( boneTexture !== undefined ) {
  18851. boneTexture.needsUpdate = true;
  18852. }
  18853. };
  18854. } )(),
  18855. clone: function () {
  18856. return new Skeleton( this.bones, this.boneInverses );
  18857. },
  18858. getBoneByName: function ( name ) {
  18859. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18860. var bone = this.bones[ i ];
  18861. if ( bone.name === name ) {
  18862. return bone;
  18863. }
  18864. }
  18865. return undefined;
  18866. }
  18867. } );
  18868. /**
  18869. * @author mikael emtinger / http://gomo.se/
  18870. * @author alteredq / http://alteredqualia.com/
  18871. * @author ikerr / http://verold.com
  18872. */
  18873. function Bone() {
  18874. Object3D.call( this );
  18875. this.type = 'Bone';
  18876. }
  18877. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18878. constructor: Bone,
  18879. isBone: true
  18880. } );
  18881. /**
  18882. * @author mikael emtinger / http://gomo.se/
  18883. * @author alteredq / http://alteredqualia.com/
  18884. * @author ikerr / http://verold.com
  18885. */
  18886. function SkinnedMesh( geometry, material ) {
  18887. Mesh.call( this, geometry, material );
  18888. this.type = 'SkinnedMesh';
  18889. this.bindMode = 'attached';
  18890. this.bindMatrix = new Matrix4();
  18891. this.bindMatrixInverse = new Matrix4();
  18892. var bones = this.initBones();
  18893. var skeleton = new Skeleton( bones );
  18894. this.bind( skeleton, this.matrixWorld );
  18895. this.normalizeSkinWeights();
  18896. }
  18897. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  18898. constructor: SkinnedMesh,
  18899. isSkinnedMesh: true,
  18900. initBones: function () {
  18901. var bones = [], bone, gbone;
  18902. var i, il;
  18903. if ( this.geometry && this.geometry.bones !== undefined ) {
  18904. // first, create array of 'Bone' objects from geometry data
  18905. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  18906. gbone = this.geometry.bones[ i ];
  18907. // create new 'Bone' object
  18908. bone = new Bone();
  18909. bones.push( bone );
  18910. // apply values
  18911. bone.name = gbone.name;
  18912. bone.position.fromArray( gbone.pos );
  18913. bone.quaternion.fromArray( gbone.rotq );
  18914. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  18915. }
  18916. // second, create bone hierarchy
  18917. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  18918. gbone = this.geometry.bones[ i ];
  18919. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  18920. // subsequent bones in the hierarchy
  18921. bones[ gbone.parent ].add( bones[ i ] );
  18922. } else {
  18923. // topmost bone, immediate child of the skinned mesh
  18924. this.add( bones[ i ] );
  18925. }
  18926. }
  18927. }
  18928. // now the bones are part of the scene graph and children of the skinned mesh.
  18929. // let's update the corresponding matrices
  18930. this.updateMatrixWorld( true );
  18931. return bones;
  18932. },
  18933. bind: function ( skeleton, bindMatrix ) {
  18934. this.skeleton = skeleton;
  18935. if ( bindMatrix === undefined ) {
  18936. this.updateMatrixWorld( true );
  18937. this.skeleton.calculateInverses();
  18938. bindMatrix = this.matrixWorld;
  18939. }
  18940. this.bindMatrix.copy( bindMatrix );
  18941. this.bindMatrixInverse.getInverse( bindMatrix );
  18942. },
  18943. pose: function () {
  18944. this.skeleton.pose();
  18945. },
  18946. normalizeSkinWeights: function () {
  18947. var scale, i;
  18948. if ( this.geometry && this.geometry.isGeometry ) {
  18949. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  18950. var sw = this.geometry.skinWeights[ i ];
  18951. scale = 1.0 / sw.manhattanLength();
  18952. if ( scale !== Infinity ) {
  18953. sw.multiplyScalar( scale );
  18954. } else {
  18955. sw.set( 1, 0, 0, 0 ); // do something reasonable
  18956. }
  18957. }
  18958. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  18959. var vec = new Vector4();
  18960. var skinWeight = this.geometry.attributes.skinWeight;
  18961. for ( i = 0; i < skinWeight.count; i ++ ) {
  18962. vec.x = skinWeight.getX( i );
  18963. vec.y = skinWeight.getY( i );
  18964. vec.z = skinWeight.getZ( i );
  18965. vec.w = skinWeight.getW( i );
  18966. scale = 1.0 / vec.manhattanLength();
  18967. if ( scale !== Infinity ) {
  18968. vec.multiplyScalar( scale );
  18969. } else {
  18970. vec.set( 1, 0, 0, 0 ); // do something reasonable
  18971. }
  18972. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  18973. }
  18974. }
  18975. },
  18976. updateMatrixWorld: function ( force ) {
  18977. Mesh.prototype.updateMatrixWorld.call( this, force );
  18978. if ( this.bindMode === 'attached' ) {
  18979. this.bindMatrixInverse.getInverse( this.matrixWorld );
  18980. } else if ( this.bindMode === 'detached' ) {
  18981. this.bindMatrixInverse.getInverse( this.bindMatrix );
  18982. } else {
  18983. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18984. }
  18985. },
  18986. clone: function () {
  18987. return new this.constructor( this.geometry, this.material ).copy( this );
  18988. }
  18989. } );
  18990. /**
  18991. * @author mrdoob / http://mrdoob.com/
  18992. * @author alteredq / http://alteredqualia.com/
  18993. *
  18994. * parameters = {
  18995. * color: <hex>,
  18996. * opacity: <float>,
  18997. *
  18998. * linewidth: <float>,
  18999. * linecap: "round",
  19000. * linejoin: "round"
  19001. * }
  19002. */
  19003. function LineBasicMaterial( parameters ) {
  19004. Material.call( this );
  19005. this.type = 'LineBasicMaterial';
  19006. this.color = new Color( 0xffffff );
  19007. this.linewidth = 1;
  19008. this.linecap = 'round';
  19009. this.linejoin = 'round';
  19010. this.lights = false;
  19011. this.setValues( parameters );
  19012. }
  19013. LineBasicMaterial.prototype = Object.create( Material.prototype );
  19014. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  19015. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  19016. LineBasicMaterial.prototype.copy = function ( source ) {
  19017. Material.prototype.copy.call( this, source );
  19018. this.color.copy( source.color );
  19019. this.linewidth = source.linewidth;
  19020. this.linecap = source.linecap;
  19021. this.linejoin = source.linejoin;
  19022. return this;
  19023. };
  19024. /**
  19025. * @author mrdoob / http://mrdoob.com/
  19026. */
  19027. function Line( geometry, material, mode ) {
  19028. if ( mode === 1 ) {
  19029. console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' );
  19030. }
  19031. Object3D.call( this );
  19032. this.type = 'Line';
  19033. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  19034. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  19035. }
  19036. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19037. constructor: Line,
  19038. isLine: true,
  19039. computeLineDistances: ( function () {
  19040. var start = new Vector3();
  19041. var end = new Vector3();
  19042. return function computeLineDistances() {
  19043. var geometry = this.geometry;
  19044. if ( geometry.isBufferGeometry ) {
  19045. // we assume non-indexed geometry
  19046. if ( geometry.index === null ) {
  19047. var positionAttribute = geometry.attributes.position;
  19048. var lineDistances = [ 0 ];
  19049. for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) {
  19050. start.fromBufferAttribute( positionAttribute, i - 1 );
  19051. end.fromBufferAttribute( positionAttribute, i );
  19052. lineDistances[ i ] = lineDistances[ i - 1 ];
  19053. lineDistances[ i ] += start.distanceTo( end );
  19054. }
  19055. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19056. } else {
  19057. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19058. }
  19059. } else if ( geometry.isGeometry ) {
  19060. var vertices = geometry.vertices;
  19061. var lineDistances = geometry.lineDistances;
  19062. lineDistances[ 0 ] = 0;
  19063. for ( var i = 1, l = vertices.length; i < l; i ++ ) {
  19064. lineDistances[ i ] = lineDistances[ i - 1 ];
  19065. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  19066. }
  19067. }
  19068. return this;
  19069. };
  19070. }() ),
  19071. raycast: ( function () {
  19072. var inverseMatrix = new Matrix4();
  19073. var ray = new Ray();
  19074. var sphere = new Sphere();
  19075. return function raycast( raycaster, intersects ) {
  19076. var precision = raycaster.linePrecision;
  19077. var precisionSq = precision * precision;
  19078. var geometry = this.geometry;
  19079. var matrixWorld = this.matrixWorld;
  19080. // Checking boundingSphere distance to ray
  19081. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19082. sphere.copy( geometry.boundingSphere );
  19083. sphere.applyMatrix4( matrixWorld );
  19084. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  19085. //
  19086. inverseMatrix.getInverse( matrixWorld );
  19087. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  19088. var vStart = new Vector3();
  19089. var vEnd = new Vector3();
  19090. var interSegment = new Vector3();
  19091. var interRay = new Vector3();
  19092. var step = ( this && this.isLineSegments ) ? 2 : 1;
  19093. if ( geometry.isBufferGeometry ) {
  19094. var index = geometry.index;
  19095. var attributes = geometry.attributes;
  19096. var positions = attributes.position.array;
  19097. if ( index !== null ) {
  19098. var indices = index.array;
  19099. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  19100. var a = indices[ i ];
  19101. var b = indices[ i + 1 ];
  19102. vStart.fromArray( positions, a * 3 );
  19103. vEnd.fromArray( positions, b * 3 );
  19104. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19105. if ( distSq > precisionSq ) continue;
  19106. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19107. var distance = raycaster.ray.origin.distanceTo( interRay );
  19108. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19109. intersects.push( {
  19110. distance: distance,
  19111. // What do we want? intersection point on the ray or on the segment??
  19112. // point: raycaster.ray.at( distance ),
  19113. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19114. index: i,
  19115. face: null,
  19116. faceIndex: null,
  19117. object: this
  19118. } );
  19119. }
  19120. } else {
  19121. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  19122. vStart.fromArray( positions, 3 * i );
  19123. vEnd.fromArray( positions, 3 * i + 3 );
  19124. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19125. if ( distSq > precisionSq ) continue;
  19126. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19127. var distance = raycaster.ray.origin.distanceTo( interRay );
  19128. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19129. intersects.push( {
  19130. distance: distance,
  19131. // What do we want? intersection point on the ray or on the segment??
  19132. // point: raycaster.ray.at( distance ),
  19133. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19134. index: i,
  19135. face: null,
  19136. faceIndex: null,
  19137. object: this
  19138. } );
  19139. }
  19140. }
  19141. } else if ( geometry.isGeometry ) {
  19142. var vertices = geometry.vertices;
  19143. var nbVertices = vertices.length;
  19144. for ( var i = 0; i < nbVertices - 1; i += step ) {
  19145. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  19146. if ( distSq > precisionSq ) continue;
  19147. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19148. var distance = raycaster.ray.origin.distanceTo( interRay );
  19149. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19150. intersects.push( {
  19151. distance: distance,
  19152. // What do we want? intersection point on the ray or on the segment??
  19153. // point: raycaster.ray.at( distance ),
  19154. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19155. index: i,
  19156. face: null,
  19157. faceIndex: null,
  19158. object: this
  19159. } );
  19160. }
  19161. }
  19162. };
  19163. }() ),
  19164. clone: function () {
  19165. return new this.constructor( this.geometry, this.material ).copy( this );
  19166. }
  19167. } );
  19168. /**
  19169. * @author mrdoob / http://mrdoob.com/
  19170. */
  19171. function LineSegments( geometry, material ) {
  19172. Line.call( this, geometry, material );
  19173. this.type = 'LineSegments';
  19174. }
  19175. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  19176. constructor: LineSegments,
  19177. isLineSegments: true,
  19178. computeLineDistances: ( function () {
  19179. var start = new Vector3();
  19180. var end = new Vector3();
  19181. return function computeLineDistances() {
  19182. var geometry = this.geometry;
  19183. if ( geometry.isBufferGeometry ) {
  19184. // we assume non-indexed geometry
  19185. if ( geometry.index === null ) {
  19186. var positionAttribute = geometry.attributes.position;
  19187. var lineDistances = [];
  19188. for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  19189. start.fromBufferAttribute( positionAttribute, i );
  19190. end.fromBufferAttribute( positionAttribute, i + 1 );
  19191. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  19192. lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end );
  19193. }
  19194. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19195. } else {
  19196. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19197. }
  19198. } else if ( geometry.isGeometry ) {
  19199. var vertices = geometry.vertices;
  19200. var lineDistances = geometry.lineDistances;
  19201. for ( var i = 0, l = vertices.length; i < l; i += 2 ) {
  19202. start.copy( vertices[ i ] );
  19203. end.copy( vertices[ i + 1 ] );
  19204. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  19205. lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end );
  19206. }
  19207. }
  19208. return this;
  19209. };
  19210. }() )
  19211. } );
  19212. /**
  19213. * @author mgreter / http://github.com/mgreter
  19214. */
  19215. function LineLoop( geometry, material ) {
  19216. Line.call( this, geometry, material );
  19217. this.type = 'LineLoop';
  19218. }
  19219. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  19220. constructor: LineLoop,
  19221. isLineLoop: true,
  19222. } );
  19223. /**
  19224. * @author mrdoob / http://mrdoob.com/
  19225. * @author alteredq / http://alteredqualia.com/
  19226. *
  19227. * parameters = {
  19228. * color: <hex>,
  19229. * opacity: <float>,
  19230. * map: new THREE.Texture( <Image> ),
  19231. *
  19232. * size: <float>,
  19233. * sizeAttenuation: <bool>
  19234. *
  19235. * morphTargets: <bool>
  19236. * }
  19237. */
  19238. function PointsMaterial( parameters ) {
  19239. Material.call( this );
  19240. this.type = 'PointsMaterial';
  19241. this.color = new Color( 0xffffff );
  19242. this.map = null;
  19243. this.size = 1;
  19244. this.sizeAttenuation = true;
  19245. this.morphTargets = false;
  19246. this.lights = false;
  19247. this.setValues( parameters );
  19248. }
  19249. PointsMaterial.prototype = Object.create( Material.prototype );
  19250. PointsMaterial.prototype.constructor = PointsMaterial;
  19251. PointsMaterial.prototype.isPointsMaterial = true;
  19252. PointsMaterial.prototype.copy = function ( source ) {
  19253. Material.prototype.copy.call( this, source );
  19254. this.color.copy( source.color );
  19255. this.map = source.map;
  19256. this.size = source.size;
  19257. this.sizeAttenuation = source.sizeAttenuation;
  19258. this.morphTargets = source.morphTargets;
  19259. return this;
  19260. };
  19261. /**
  19262. * @author alteredq / http://alteredqualia.com/
  19263. */
  19264. function Points( geometry, material ) {
  19265. Object3D.call( this );
  19266. this.type = 'Points';
  19267. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  19268. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  19269. }
  19270. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19271. constructor: Points,
  19272. isPoints: true,
  19273. raycast: ( function () {
  19274. var inverseMatrix = new Matrix4();
  19275. var ray = new Ray();
  19276. var sphere = new Sphere();
  19277. return function raycast( raycaster, intersects ) {
  19278. var object = this;
  19279. var geometry = this.geometry;
  19280. var matrixWorld = this.matrixWorld;
  19281. var threshold = raycaster.params.Points.threshold;
  19282. // Checking boundingSphere distance to ray
  19283. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19284. sphere.copy( geometry.boundingSphere );
  19285. sphere.applyMatrix4( matrixWorld );
  19286. sphere.radius += threshold;
  19287. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  19288. //
  19289. inverseMatrix.getInverse( matrixWorld );
  19290. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  19291. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19292. var localThresholdSq = localThreshold * localThreshold;
  19293. var position = new Vector3();
  19294. var intersectPoint = new Vector3();
  19295. function testPoint( point, index ) {
  19296. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  19297. if ( rayPointDistanceSq < localThresholdSq ) {
  19298. ray.closestPointToPoint( point, intersectPoint );
  19299. intersectPoint.applyMatrix4( matrixWorld );
  19300. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  19301. if ( distance < raycaster.near || distance > raycaster.far ) return;
  19302. intersects.push( {
  19303. distance: distance,
  19304. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  19305. point: intersectPoint.clone(),
  19306. index: index,
  19307. face: null,
  19308. object: object
  19309. } );
  19310. }
  19311. }
  19312. if ( geometry.isBufferGeometry ) {
  19313. var index = geometry.index;
  19314. var attributes = geometry.attributes;
  19315. var positions = attributes.position.array;
  19316. if ( index !== null ) {
  19317. var indices = index.array;
  19318. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  19319. var a = indices[ i ];
  19320. position.fromArray( positions, a * 3 );
  19321. testPoint( position, a );
  19322. }
  19323. } else {
  19324. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  19325. position.fromArray( positions, i * 3 );
  19326. testPoint( position, i );
  19327. }
  19328. }
  19329. } else {
  19330. var vertices = geometry.vertices;
  19331. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19332. testPoint( vertices[ i ], i );
  19333. }
  19334. }
  19335. };
  19336. }() ),
  19337. clone: function () {
  19338. return new this.constructor( this.geometry, this.material ).copy( this );
  19339. }
  19340. } );
  19341. /**
  19342. * @author mrdoob / http://mrdoob.com/
  19343. */
  19344. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19345. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19346. this.generateMipmaps = false;
  19347. }
  19348. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  19349. constructor: VideoTexture,
  19350. isVideoTexture: true,
  19351. update: function () {
  19352. var video = this.image;
  19353. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  19354. this.needsUpdate = true;
  19355. }
  19356. }
  19357. } );
  19358. /**
  19359. * @author alteredq / http://alteredqualia.com/
  19360. */
  19361. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  19362. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  19363. this.image = { width: width, height: height };
  19364. this.mipmaps = mipmaps;
  19365. // no flipping for cube textures
  19366. // (also flipping doesn't work for compressed textures )
  19367. this.flipY = false;
  19368. // can't generate mipmaps for compressed textures
  19369. // mips must be embedded in DDS files
  19370. this.generateMipmaps = false;
  19371. }
  19372. CompressedTexture.prototype = Object.create( Texture.prototype );
  19373. CompressedTexture.prototype.constructor = CompressedTexture;
  19374. CompressedTexture.prototype.isCompressedTexture = true;
  19375. /**
  19376. * @author mrdoob / http://mrdoob.com/
  19377. */
  19378. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19379. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19380. this.needsUpdate = true;
  19381. }
  19382. CanvasTexture.prototype = Object.create( Texture.prototype );
  19383. CanvasTexture.prototype.constructor = CanvasTexture;
  19384. CanvasTexture.prototype.isCanvasTexture = true;
  19385. /**
  19386. * @author Matt DesLauriers / @mattdesl
  19387. * @author atix / arthursilber.de
  19388. */
  19389. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  19390. format = format !== undefined ? format : DepthFormat;
  19391. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  19392. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  19393. }
  19394. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  19395. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  19396. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19397. this.image = { width: width, height: height };
  19398. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  19399. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  19400. this.flipY = false;
  19401. this.generateMipmaps = false;
  19402. }
  19403. DepthTexture.prototype = Object.create( Texture.prototype );
  19404. DepthTexture.prototype.constructor = DepthTexture;
  19405. DepthTexture.prototype.isDepthTexture = true;
  19406. /**
  19407. * @author mrdoob / http://mrdoob.com/
  19408. * @author Mugen87 / https://github.com/Mugen87
  19409. */
  19410. function WireframeGeometry( geometry ) {
  19411. BufferGeometry.call( this );
  19412. this.type = 'WireframeGeometry';
  19413. // buffer
  19414. var vertices = [];
  19415. // helper variables
  19416. var i, j, l, o, ol;
  19417. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  19418. var key, keys = [ 'a', 'b', 'c' ];
  19419. var vertex;
  19420. // different logic for Geometry and BufferGeometry
  19421. if ( geometry && geometry.isGeometry ) {
  19422. // create a data structure that contains all edges without duplicates
  19423. var faces = geometry.faces;
  19424. for ( i = 0, l = faces.length; i < l; i ++ ) {
  19425. var face = faces[ i ];
  19426. for ( j = 0; j < 3; j ++ ) {
  19427. edge1 = face[ keys[ j ] ];
  19428. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  19429. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19430. edge[ 1 ] = Math.max( edge1, edge2 );
  19431. key = edge[ 0 ] + ',' + edge[ 1 ];
  19432. if ( edges[ key ] === undefined ) {
  19433. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19434. }
  19435. }
  19436. }
  19437. // generate vertices
  19438. for ( key in edges ) {
  19439. e = edges[ key ];
  19440. vertex = geometry.vertices[ e.index1 ];
  19441. vertices.push( vertex.x, vertex.y, vertex.z );
  19442. vertex = geometry.vertices[ e.index2 ];
  19443. vertices.push( vertex.x, vertex.y, vertex.z );
  19444. }
  19445. } else if ( geometry && geometry.isBufferGeometry ) {
  19446. var position, indices, groups;
  19447. var group, start, count;
  19448. var index1, index2;
  19449. vertex = new Vector3();
  19450. if ( geometry.index !== null ) {
  19451. // indexed BufferGeometry
  19452. position = geometry.attributes.position;
  19453. indices = geometry.index;
  19454. groups = geometry.groups;
  19455. if ( groups.length === 0 ) {
  19456. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  19457. }
  19458. // create a data structure that contains all eges without duplicates
  19459. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  19460. group = groups[ o ];
  19461. start = group.start;
  19462. count = group.count;
  19463. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  19464. for ( j = 0; j < 3; j ++ ) {
  19465. edge1 = indices.getX( i + j );
  19466. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  19467. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19468. edge[ 1 ] = Math.max( edge1, edge2 );
  19469. key = edge[ 0 ] + ',' + edge[ 1 ];
  19470. if ( edges[ key ] === undefined ) {
  19471. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19472. }
  19473. }
  19474. }
  19475. }
  19476. // generate vertices
  19477. for ( key in edges ) {
  19478. e = edges[ key ];
  19479. vertex.fromBufferAttribute( position, e.index1 );
  19480. vertices.push( vertex.x, vertex.y, vertex.z );
  19481. vertex.fromBufferAttribute( position, e.index2 );
  19482. vertices.push( vertex.x, vertex.y, vertex.z );
  19483. }
  19484. } else {
  19485. // non-indexed BufferGeometry
  19486. position = geometry.attributes.position;
  19487. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  19488. for ( j = 0; j < 3; j ++ ) {
  19489. // three edges per triangle, an edge is represented as (index1, index2)
  19490. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  19491. index1 = 3 * i + j;
  19492. vertex.fromBufferAttribute( position, index1 );
  19493. vertices.push( vertex.x, vertex.y, vertex.z );
  19494. index2 = 3 * i + ( ( j + 1 ) % 3 );
  19495. vertex.fromBufferAttribute( position, index2 );
  19496. vertices.push( vertex.x, vertex.y, vertex.z );
  19497. }
  19498. }
  19499. }
  19500. }
  19501. // build geometry
  19502. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19503. }
  19504. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  19505. WireframeGeometry.prototype.constructor = WireframeGeometry;
  19506. /**
  19507. * @author zz85 / https://github.com/zz85
  19508. * @author Mugen87 / https://github.com/Mugen87
  19509. *
  19510. * Parametric Surfaces Geometry
  19511. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19512. */
  19513. // ParametricGeometry
  19514. function ParametricGeometry( func, slices, stacks ) {
  19515. Geometry.call( this );
  19516. this.type = 'ParametricGeometry';
  19517. this.parameters = {
  19518. func: func,
  19519. slices: slices,
  19520. stacks: stacks
  19521. };
  19522. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  19523. this.mergeVertices();
  19524. }
  19525. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  19526. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19527. // ParametricBufferGeometry
  19528. function ParametricBufferGeometry( func, slices, stacks ) {
  19529. BufferGeometry.call( this );
  19530. this.type = 'ParametricBufferGeometry';
  19531. this.parameters = {
  19532. func: func,
  19533. slices: slices,
  19534. stacks: stacks
  19535. };
  19536. // buffers
  19537. var indices = [];
  19538. var vertices = [];
  19539. var normals = [];
  19540. var uvs = [];
  19541. var EPS = 0.00001;
  19542. var normal = new Vector3();
  19543. var p0 = new Vector3(), p1 = new Vector3();
  19544. var pu = new Vector3(), pv = new Vector3();
  19545. var i, j;
  19546. if ( func.length < 3 ) {
  19547. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  19548. }
  19549. // generate vertices, normals and uvs
  19550. var sliceCount = slices + 1;
  19551. for ( i = 0; i <= stacks; i ++ ) {
  19552. var v = i / stacks;
  19553. for ( j = 0; j <= slices; j ++ ) {
  19554. var u = j / slices;
  19555. // vertex
  19556. func( u, v, p0 );
  19557. vertices.push( p0.x, p0.y, p0.z );
  19558. // normal
  19559. // approximate tangent vectors via finite differences
  19560. if ( u - EPS >= 0 ) {
  19561. func( u - EPS, v, p1 );
  19562. pu.subVectors( p0, p1 );
  19563. } else {
  19564. func( u + EPS, v, p1 );
  19565. pu.subVectors( p1, p0 );
  19566. }
  19567. if ( v - EPS >= 0 ) {
  19568. func( u, v - EPS, p1 );
  19569. pv.subVectors( p0, p1 );
  19570. } else {
  19571. func( u, v + EPS, p1 );
  19572. pv.subVectors( p1, p0 );
  19573. }
  19574. // cross product of tangent vectors returns surface normal
  19575. normal.crossVectors( pu, pv ).normalize();
  19576. normals.push( normal.x, normal.y, normal.z );
  19577. // uv
  19578. uvs.push( u, v );
  19579. }
  19580. }
  19581. // generate indices
  19582. for ( i = 0; i < stacks; i ++ ) {
  19583. for ( j = 0; j < slices; j ++ ) {
  19584. var a = i * sliceCount + j;
  19585. var b = i * sliceCount + j + 1;
  19586. var c = ( i + 1 ) * sliceCount + j + 1;
  19587. var d = ( i + 1 ) * sliceCount + j;
  19588. // faces one and two
  19589. indices.push( a, b, d );
  19590. indices.push( b, c, d );
  19591. }
  19592. }
  19593. // build geometry
  19594. this.setIndex( indices );
  19595. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19596. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19597. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19598. }
  19599. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19600. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19601. /**
  19602. * @author clockworkgeek / https://github.com/clockworkgeek
  19603. * @author timothypratley / https://github.com/timothypratley
  19604. * @author WestLangley / http://github.com/WestLangley
  19605. * @author Mugen87 / https://github.com/Mugen87
  19606. */
  19607. // PolyhedronGeometry
  19608. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  19609. Geometry.call( this );
  19610. this.type = 'PolyhedronGeometry';
  19611. this.parameters = {
  19612. vertices: vertices,
  19613. indices: indices,
  19614. radius: radius,
  19615. detail: detail
  19616. };
  19617. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  19618. this.mergeVertices();
  19619. }
  19620. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  19621. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  19622. // PolyhedronBufferGeometry
  19623. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  19624. BufferGeometry.call( this );
  19625. this.type = 'PolyhedronBufferGeometry';
  19626. this.parameters = {
  19627. vertices: vertices,
  19628. indices: indices,
  19629. radius: radius,
  19630. detail: detail
  19631. };
  19632. radius = radius || 1;
  19633. detail = detail || 0;
  19634. // default buffer data
  19635. var vertexBuffer = [];
  19636. var uvBuffer = [];
  19637. // the subdivision creates the vertex buffer data
  19638. subdivide( detail );
  19639. // all vertices should lie on a conceptual sphere with a given radius
  19640. appplyRadius( radius );
  19641. // finally, create the uv data
  19642. generateUVs();
  19643. // build non-indexed geometry
  19644. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19645. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19646. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19647. if ( detail === 0 ) {
  19648. this.computeVertexNormals(); // flat normals
  19649. } else {
  19650. this.normalizeNormals(); // smooth normals
  19651. }
  19652. // helper functions
  19653. function subdivide( detail ) {
  19654. var a = new Vector3();
  19655. var b = new Vector3();
  19656. var c = new Vector3();
  19657. // iterate over all faces and apply a subdivison with the given detail value
  19658. for ( var i = 0; i < indices.length; i += 3 ) {
  19659. // get the vertices of the face
  19660. getVertexByIndex( indices[ i + 0 ], a );
  19661. getVertexByIndex( indices[ i + 1 ], b );
  19662. getVertexByIndex( indices[ i + 2 ], c );
  19663. // perform subdivision
  19664. subdivideFace( a, b, c, detail );
  19665. }
  19666. }
  19667. function subdivideFace( a, b, c, detail ) {
  19668. var cols = Math.pow( 2, detail );
  19669. // we use this multidimensional array as a data structure for creating the subdivision
  19670. var v = [];
  19671. var i, j;
  19672. // construct all of the vertices for this subdivision
  19673. for ( i = 0; i <= cols; i ++ ) {
  19674. v[ i ] = [];
  19675. var aj = a.clone().lerp( c, i / cols );
  19676. var bj = b.clone().lerp( c, i / cols );
  19677. var rows = cols - i;
  19678. for ( j = 0; j <= rows; j ++ ) {
  19679. if ( j === 0 && i === cols ) {
  19680. v[ i ][ j ] = aj;
  19681. } else {
  19682. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19683. }
  19684. }
  19685. }
  19686. // construct all of the faces
  19687. for ( i = 0; i < cols; i ++ ) {
  19688. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19689. var k = Math.floor( j / 2 );
  19690. if ( j % 2 === 0 ) {
  19691. pushVertex( v[ i ][ k + 1 ] );
  19692. pushVertex( v[ i + 1 ][ k ] );
  19693. pushVertex( v[ i ][ k ] );
  19694. } else {
  19695. pushVertex( v[ i ][ k + 1 ] );
  19696. pushVertex( v[ i + 1 ][ k + 1 ] );
  19697. pushVertex( v[ i + 1 ][ k ] );
  19698. }
  19699. }
  19700. }
  19701. }
  19702. function appplyRadius( radius ) {
  19703. var vertex = new Vector3();
  19704. // iterate over the entire buffer and apply the radius to each vertex
  19705. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19706. vertex.x = vertexBuffer[ i + 0 ];
  19707. vertex.y = vertexBuffer[ i + 1 ];
  19708. vertex.z = vertexBuffer[ i + 2 ];
  19709. vertex.normalize().multiplyScalar( radius );
  19710. vertexBuffer[ i + 0 ] = vertex.x;
  19711. vertexBuffer[ i + 1 ] = vertex.y;
  19712. vertexBuffer[ i + 2 ] = vertex.z;
  19713. }
  19714. }
  19715. function generateUVs() {
  19716. var vertex = new Vector3();
  19717. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19718. vertex.x = vertexBuffer[ i + 0 ];
  19719. vertex.y = vertexBuffer[ i + 1 ];
  19720. vertex.z = vertexBuffer[ i + 2 ];
  19721. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19722. var v = inclination( vertex ) / Math.PI + 0.5;
  19723. uvBuffer.push( u, 1 - v );
  19724. }
  19725. correctUVs();
  19726. correctSeam();
  19727. }
  19728. function correctSeam() {
  19729. // handle case when face straddles the seam, see #3269
  19730. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  19731. // uv data of a single face
  19732. var x0 = uvBuffer[ i + 0 ];
  19733. var x1 = uvBuffer[ i + 2 ];
  19734. var x2 = uvBuffer[ i + 4 ];
  19735. var max = Math.max( x0, x1, x2 );
  19736. var min = Math.min( x0, x1, x2 );
  19737. // 0.9 is somewhat arbitrary
  19738. if ( max > 0.9 && min < 0.1 ) {
  19739. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  19740. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  19741. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  19742. }
  19743. }
  19744. }
  19745. function pushVertex( vertex ) {
  19746. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  19747. }
  19748. function getVertexByIndex( index, vertex ) {
  19749. var stride = index * 3;
  19750. vertex.x = vertices[ stride + 0 ];
  19751. vertex.y = vertices[ stride + 1 ];
  19752. vertex.z = vertices[ stride + 2 ];
  19753. }
  19754. function correctUVs() {
  19755. var a = new Vector3();
  19756. var b = new Vector3();
  19757. var c = new Vector3();
  19758. var centroid = new Vector3();
  19759. var uvA = new Vector2();
  19760. var uvB = new Vector2();
  19761. var uvC = new Vector2();
  19762. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  19763. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  19764. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  19765. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  19766. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  19767. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  19768. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  19769. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  19770. var azi = azimuth( centroid );
  19771. correctUV( uvA, j + 0, a, azi );
  19772. correctUV( uvB, j + 2, b, azi );
  19773. correctUV( uvC, j + 4, c, azi );
  19774. }
  19775. }
  19776. function correctUV( uv, stride, vector, azimuth ) {
  19777. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  19778. uvBuffer[ stride ] = uv.x - 1;
  19779. }
  19780. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  19781. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  19782. }
  19783. }
  19784. // Angle around the Y axis, counter-clockwise when looking from above.
  19785. function azimuth( vector ) {
  19786. return Math.atan2( vector.z, - vector.x );
  19787. }
  19788. // Angle above the XZ plane.
  19789. function inclination( vector ) {
  19790. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19791. }
  19792. }
  19793. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19794. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  19795. /**
  19796. * @author timothypratley / https://github.com/timothypratley
  19797. * @author Mugen87 / https://github.com/Mugen87
  19798. */
  19799. // TetrahedronGeometry
  19800. function TetrahedronGeometry( radius, detail ) {
  19801. Geometry.call( this );
  19802. this.type = 'TetrahedronGeometry';
  19803. this.parameters = {
  19804. radius: radius,
  19805. detail: detail
  19806. };
  19807. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  19808. this.mergeVertices();
  19809. }
  19810. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  19811. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  19812. // TetrahedronBufferGeometry
  19813. function TetrahedronBufferGeometry( radius, detail ) {
  19814. var vertices = [
  19815. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  19816. ];
  19817. var indices = [
  19818. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19819. ];
  19820. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19821. this.type = 'TetrahedronBufferGeometry';
  19822. this.parameters = {
  19823. radius: radius,
  19824. detail: detail
  19825. };
  19826. }
  19827. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19828. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  19829. /**
  19830. * @author timothypratley / https://github.com/timothypratley
  19831. * @author Mugen87 / https://github.com/Mugen87
  19832. */
  19833. // OctahedronGeometry
  19834. function OctahedronGeometry( radius, detail ) {
  19835. Geometry.call( this );
  19836. this.type = 'OctahedronGeometry';
  19837. this.parameters = {
  19838. radius: radius,
  19839. detail: detail
  19840. };
  19841. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  19842. this.mergeVertices();
  19843. }
  19844. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  19845. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  19846. // OctahedronBufferGeometry
  19847. function OctahedronBufferGeometry( radius, detail ) {
  19848. var vertices = [
  19849. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  19850. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  19851. ];
  19852. var indices = [
  19853. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  19854. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  19855. 1, 3, 4, 1, 4, 2
  19856. ];
  19857. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19858. this.type = 'OctahedronBufferGeometry';
  19859. this.parameters = {
  19860. radius: radius,
  19861. detail: detail
  19862. };
  19863. }
  19864. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19865. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  19866. /**
  19867. * @author timothypratley / https://github.com/timothypratley
  19868. * @author Mugen87 / https://github.com/Mugen87
  19869. */
  19870. // IcosahedronGeometry
  19871. function IcosahedronGeometry( radius, detail ) {
  19872. Geometry.call( this );
  19873. this.type = 'IcosahedronGeometry';
  19874. this.parameters = {
  19875. radius: radius,
  19876. detail: detail
  19877. };
  19878. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  19879. this.mergeVertices();
  19880. }
  19881. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  19882. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  19883. // IcosahedronBufferGeometry
  19884. function IcosahedronBufferGeometry( radius, detail ) {
  19885. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19886. var vertices = [
  19887. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19888. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19889. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19890. ];
  19891. var indices = [
  19892. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19893. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19894. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19895. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19896. ];
  19897. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19898. this.type = 'IcosahedronBufferGeometry';
  19899. this.parameters = {
  19900. radius: radius,
  19901. detail: detail
  19902. };
  19903. }
  19904. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19905. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  19906. /**
  19907. * @author Abe Pazos / https://hamoid.com
  19908. * @author Mugen87 / https://github.com/Mugen87
  19909. */
  19910. // DodecahedronGeometry
  19911. function DodecahedronGeometry( radius, detail ) {
  19912. Geometry.call( this );
  19913. this.type = 'DodecahedronGeometry';
  19914. this.parameters = {
  19915. radius: radius,
  19916. detail: detail
  19917. };
  19918. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  19919. this.mergeVertices();
  19920. }
  19921. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  19922. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  19923. // DodecahedronBufferGeometry
  19924. function DodecahedronBufferGeometry( radius, detail ) {
  19925. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19926. var r = 1 / t;
  19927. var vertices = [
  19928. // (±1, ±1, ±1)
  19929. - 1, - 1, - 1, - 1, - 1, 1,
  19930. - 1, 1, - 1, - 1, 1, 1,
  19931. 1, - 1, - 1, 1, - 1, 1,
  19932. 1, 1, - 1, 1, 1, 1,
  19933. // (0, ±1/φ, ±φ)
  19934. 0, - r, - t, 0, - r, t,
  19935. 0, r, - t, 0, r, t,
  19936. // (±1/φ, ±φ, 0)
  19937. - r, - t, 0, - r, t, 0,
  19938. r, - t, 0, r, t, 0,
  19939. // (±φ, 0, ±1/φ)
  19940. - t, 0, - r, t, 0, - r,
  19941. - t, 0, r, t, 0, r
  19942. ];
  19943. var indices = [
  19944. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19945. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19946. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19947. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19948. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19949. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19950. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19951. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19952. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19953. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19954. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19955. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19956. ];
  19957. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19958. this.type = 'DodecahedronBufferGeometry';
  19959. this.parameters = {
  19960. radius: radius,
  19961. detail: detail
  19962. };
  19963. }
  19964. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19965. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  19966. /**
  19967. * @author oosmoxiecode / https://github.com/oosmoxiecode
  19968. * @author WestLangley / https://github.com/WestLangley
  19969. * @author zz85 / https://github.com/zz85
  19970. * @author miningold / https://github.com/miningold
  19971. * @author jonobr1 / https://github.com/jonobr1
  19972. * @author Mugen87 / https://github.com/Mugen87
  19973. *
  19974. */
  19975. // TubeGeometry
  19976. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  19977. Geometry.call( this );
  19978. this.type = 'TubeGeometry';
  19979. this.parameters = {
  19980. path: path,
  19981. tubularSegments: tubularSegments,
  19982. radius: radius,
  19983. radialSegments: radialSegments,
  19984. closed: closed
  19985. };
  19986. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  19987. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  19988. // expose internals
  19989. this.tangents = bufferGeometry.tangents;
  19990. this.normals = bufferGeometry.normals;
  19991. this.binormals = bufferGeometry.binormals;
  19992. // create geometry
  19993. this.fromBufferGeometry( bufferGeometry );
  19994. this.mergeVertices();
  19995. }
  19996. TubeGeometry.prototype = Object.create( Geometry.prototype );
  19997. TubeGeometry.prototype.constructor = TubeGeometry;
  19998. // TubeBufferGeometry
  19999. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  20000. BufferGeometry.call( this );
  20001. this.type = 'TubeBufferGeometry';
  20002. this.parameters = {
  20003. path: path,
  20004. tubularSegments: tubularSegments,
  20005. radius: radius,
  20006. radialSegments: radialSegments,
  20007. closed: closed
  20008. };
  20009. tubularSegments = tubularSegments || 64;
  20010. radius = radius || 1;
  20011. radialSegments = radialSegments || 8;
  20012. closed = closed || false;
  20013. var frames = path.computeFrenetFrames( tubularSegments, closed );
  20014. // expose internals
  20015. this.tangents = frames.tangents;
  20016. this.normals = frames.normals;
  20017. this.binormals = frames.binormals;
  20018. // helper variables
  20019. var vertex = new Vector3();
  20020. var normal = new Vector3();
  20021. var uv = new Vector2();
  20022. var P = new Vector3();
  20023. var i, j;
  20024. // buffer
  20025. var vertices = [];
  20026. var normals = [];
  20027. var uvs = [];
  20028. var indices = [];
  20029. // create buffer data
  20030. generateBufferData();
  20031. // build geometry
  20032. this.setIndex( indices );
  20033. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20034. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20035. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20036. // functions
  20037. function generateBufferData() {
  20038. for ( i = 0; i < tubularSegments; i ++ ) {
  20039. generateSegment( i );
  20040. }
  20041. // if the geometry is not closed, generate the last row of vertices and normals
  20042. // at the regular position on the given path
  20043. //
  20044. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20045. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  20046. // uvs are generated in a separate function.
  20047. // this makes it easy compute correct values for closed geometries
  20048. generateUVs();
  20049. // finally create faces
  20050. generateIndices();
  20051. }
  20052. function generateSegment( i ) {
  20053. // we use getPointAt to sample evenly distributed points from the given path
  20054. P = path.getPointAt( i / tubularSegments, P );
  20055. // retrieve corresponding normal and binormal
  20056. var N = frames.normals[ i ];
  20057. var B = frames.binormals[ i ];
  20058. // generate normals and vertices for the current segment
  20059. for ( j = 0; j <= radialSegments; j ++ ) {
  20060. var v = j / radialSegments * Math.PI * 2;
  20061. var sin = Math.sin( v );
  20062. var cos = - Math.cos( v );
  20063. // normal
  20064. normal.x = ( cos * N.x + sin * B.x );
  20065. normal.y = ( cos * N.y + sin * B.y );
  20066. normal.z = ( cos * N.z + sin * B.z );
  20067. normal.normalize();
  20068. normals.push( normal.x, normal.y, normal.z );
  20069. // vertex
  20070. vertex.x = P.x + radius * normal.x;
  20071. vertex.y = P.y + radius * normal.y;
  20072. vertex.z = P.z + radius * normal.z;
  20073. vertices.push( vertex.x, vertex.y, vertex.z );
  20074. }
  20075. }
  20076. function generateIndices() {
  20077. for ( j = 1; j <= tubularSegments; j ++ ) {
  20078. for ( i = 1; i <= radialSegments; i ++ ) {
  20079. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20080. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  20081. var c = ( radialSegments + 1 ) * j + i;
  20082. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20083. // faces
  20084. indices.push( a, b, d );
  20085. indices.push( b, c, d );
  20086. }
  20087. }
  20088. }
  20089. function generateUVs() {
  20090. for ( i = 0; i <= tubularSegments; i ++ ) {
  20091. for ( j = 0; j <= radialSegments; j ++ ) {
  20092. uv.x = i / tubularSegments;
  20093. uv.y = j / radialSegments;
  20094. uvs.push( uv.x, uv.y );
  20095. }
  20096. }
  20097. }
  20098. }
  20099. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20100. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  20101. /**
  20102. * @author oosmoxiecode
  20103. * @author Mugen87 / https://github.com/Mugen87
  20104. *
  20105. * based on http://www.blackpawn.com/texts/pqtorus/
  20106. */
  20107. // TorusKnotGeometry
  20108. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  20109. Geometry.call( this );
  20110. this.type = 'TorusKnotGeometry';
  20111. this.parameters = {
  20112. radius: radius,
  20113. tube: tube,
  20114. tubularSegments: tubularSegments,
  20115. radialSegments: radialSegments,
  20116. p: p,
  20117. q: q
  20118. };
  20119. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  20120. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  20121. this.mergeVertices();
  20122. }
  20123. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  20124. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  20125. // TorusKnotBufferGeometry
  20126. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  20127. BufferGeometry.call( this );
  20128. this.type = 'TorusKnotBufferGeometry';
  20129. this.parameters = {
  20130. radius: radius,
  20131. tube: tube,
  20132. tubularSegments: tubularSegments,
  20133. radialSegments: radialSegments,
  20134. p: p,
  20135. q: q
  20136. };
  20137. radius = radius || 1;
  20138. tube = tube || 0.4;
  20139. tubularSegments = Math.floor( tubularSegments ) || 64;
  20140. radialSegments = Math.floor( radialSegments ) || 8;
  20141. p = p || 2;
  20142. q = q || 3;
  20143. // buffers
  20144. var indices = [];
  20145. var vertices = [];
  20146. var normals = [];
  20147. var uvs = [];
  20148. // helper variables
  20149. var i, j;
  20150. var vertex = new Vector3();
  20151. var normal = new Vector3();
  20152. var P1 = new Vector3();
  20153. var P2 = new Vector3();
  20154. var B = new Vector3();
  20155. var T = new Vector3();
  20156. var N = new Vector3();
  20157. // generate vertices, normals and uvs
  20158. for ( i = 0; i <= tubularSegments; ++ i ) {
  20159. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20160. var u = i / tubularSegments * p * Math.PI * 2;
  20161. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20162. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20163. calculatePositionOnCurve( u, p, q, radius, P1 );
  20164. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20165. // calculate orthonormal basis
  20166. T.subVectors( P2, P1 );
  20167. N.addVectors( P2, P1 );
  20168. B.crossVectors( T, N );
  20169. N.crossVectors( B, T );
  20170. // normalize B, N. T can be ignored, we don't use it
  20171. B.normalize();
  20172. N.normalize();
  20173. for ( j = 0; j <= radialSegments; ++ j ) {
  20174. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20175. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20176. var v = j / radialSegments * Math.PI * 2;
  20177. var cx = - tube * Math.cos( v );
  20178. var cy = tube * Math.sin( v );
  20179. // now calculate the final vertex position.
  20180. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20181. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20182. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20183. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20184. vertices.push( vertex.x, vertex.y, vertex.z );
  20185. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20186. normal.subVectors( vertex, P1 ).normalize();
  20187. normals.push( normal.x, normal.y, normal.z );
  20188. // uv
  20189. uvs.push( i / tubularSegments );
  20190. uvs.push( j / radialSegments );
  20191. }
  20192. }
  20193. // generate indices
  20194. for ( j = 1; j <= tubularSegments; j ++ ) {
  20195. for ( i = 1; i <= radialSegments; i ++ ) {
  20196. // indices
  20197. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20198. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  20199. var c = ( radialSegments + 1 ) * j + i;
  20200. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20201. // faces
  20202. indices.push( a, b, d );
  20203. indices.push( b, c, d );
  20204. }
  20205. }
  20206. // build geometry
  20207. this.setIndex( indices );
  20208. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20209. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20210. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20211. // this function calculates the current position on the torus curve
  20212. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20213. var cu = Math.cos( u );
  20214. var su = Math.sin( u );
  20215. var quOverP = q / p * u;
  20216. var cs = Math.cos( quOverP );
  20217. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20218. position.y = radius * ( 2 + cs ) * su * 0.5;
  20219. position.z = radius * Math.sin( quOverP ) * 0.5;
  20220. }
  20221. }
  20222. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20223. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  20224. /**
  20225. * @author oosmoxiecode
  20226. * @author mrdoob / http://mrdoob.com/
  20227. * @author Mugen87 / https://github.com/Mugen87
  20228. */
  20229. // TorusGeometry
  20230. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  20231. Geometry.call( this );
  20232. this.type = 'TorusGeometry';
  20233. this.parameters = {
  20234. radius: radius,
  20235. tube: tube,
  20236. radialSegments: radialSegments,
  20237. tubularSegments: tubularSegments,
  20238. arc: arc
  20239. };
  20240. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  20241. this.mergeVertices();
  20242. }
  20243. TorusGeometry.prototype = Object.create( Geometry.prototype );
  20244. TorusGeometry.prototype.constructor = TorusGeometry;
  20245. // TorusBufferGeometry
  20246. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  20247. BufferGeometry.call( this );
  20248. this.type = 'TorusBufferGeometry';
  20249. this.parameters = {
  20250. radius: radius,
  20251. tube: tube,
  20252. radialSegments: radialSegments,
  20253. tubularSegments: tubularSegments,
  20254. arc: arc
  20255. };
  20256. radius = radius || 1;
  20257. tube = tube || 0.4;
  20258. radialSegments = Math.floor( radialSegments ) || 8;
  20259. tubularSegments = Math.floor( tubularSegments ) || 6;
  20260. arc = arc || Math.PI * 2;
  20261. // buffers
  20262. var indices = [];
  20263. var vertices = [];
  20264. var normals = [];
  20265. var uvs = [];
  20266. // helper variables
  20267. var center = new Vector3();
  20268. var vertex = new Vector3();
  20269. var normal = new Vector3();
  20270. var j, i;
  20271. // generate vertices, normals and uvs
  20272. for ( j = 0; j <= radialSegments; j ++ ) {
  20273. for ( i = 0; i <= tubularSegments; i ++ ) {
  20274. var u = i / tubularSegments * arc;
  20275. var v = j / radialSegments * Math.PI * 2;
  20276. // vertex
  20277. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20278. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20279. vertex.z = tube * Math.sin( v );
  20280. vertices.push( vertex.x, vertex.y, vertex.z );
  20281. // normal
  20282. center.x = radius * Math.cos( u );
  20283. center.y = radius * Math.sin( u );
  20284. normal.subVectors( vertex, center ).normalize();
  20285. normals.push( normal.x, normal.y, normal.z );
  20286. // uv
  20287. uvs.push( i / tubularSegments );
  20288. uvs.push( j / radialSegments );
  20289. }
  20290. }
  20291. // generate indices
  20292. for ( j = 1; j <= radialSegments; j ++ ) {
  20293. for ( i = 1; i <= tubularSegments; i ++ ) {
  20294. // indices
  20295. var a = ( tubularSegments + 1 ) * j + i - 1;
  20296. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20297. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20298. var d = ( tubularSegments + 1 ) * j + i;
  20299. // faces
  20300. indices.push( a, b, d );
  20301. indices.push( b, c, d );
  20302. }
  20303. }
  20304. // build geometry
  20305. this.setIndex( indices );
  20306. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20307. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20308. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20309. }
  20310. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20311. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  20312. /**
  20313. * @author Mugen87 / https://github.com/Mugen87
  20314. * Port from https://github.com/mapbox/earcut (v2.1.2)
  20315. */
  20316. var Earcut = {
  20317. triangulate: function ( data, holeIndices, dim ) {
  20318. dim = dim || 2;
  20319. var hasHoles = holeIndices && holeIndices.length,
  20320. outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
  20321. outerNode = linkedList( data, 0, outerLen, dim, true ),
  20322. triangles = [];
  20323. if ( ! outerNode ) return triangles;
  20324. var minX, minY, maxX, maxY, x, y, invSize;
  20325. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20326. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20327. if ( data.length > 80 * dim ) {
  20328. minX = maxX = data[ 0 ];
  20329. minY = maxY = data[ 1 ];
  20330. for ( var i = dim; i < outerLen; i += dim ) {
  20331. x = data[ i ];
  20332. y = data[ i + 1 ];
  20333. if ( x < minX ) minX = x;
  20334. if ( y < minY ) minY = y;
  20335. if ( x > maxX ) maxX = x;
  20336. if ( y > maxY ) maxY = y;
  20337. }
  20338. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20339. invSize = Math.max( maxX - minX, maxY - minY );
  20340. invSize = invSize !== 0 ? 1 / invSize : 0;
  20341. }
  20342. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  20343. return triangles;
  20344. }
  20345. };
  20346. // create a circular doubly linked list from polygon points in the specified winding order
  20347. function linkedList( data, start, end, dim, clockwise ) {
  20348. var i, last;
  20349. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20350. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20351. } else {
  20352. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20353. }
  20354. if ( last && equals( last, last.next ) ) {
  20355. removeNode( last );
  20356. last = last.next;
  20357. }
  20358. return last;
  20359. }
  20360. // eliminate colinear or duplicate points
  20361. function filterPoints( start, end ) {
  20362. if ( ! start ) return start;
  20363. if ( ! end ) end = start;
  20364. var p = start, again;
  20365. do {
  20366. again = false;
  20367. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20368. removeNode( p );
  20369. p = end = p.prev;
  20370. if ( p === p.next ) break;
  20371. again = true;
  20372. } else {
  20373. p = p.next;
  20374. }
  20375. } while ( again || p !== end );
  20376. return end;
  20377. }
  20378. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20379. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20380. if ( ! ear ) return;
  20381. // interlink polygon nodes in z-order
  20382. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20383. var stop = ear, prev, next;
  20384. // iterate through ears, slicing them one by one
  20385. while ( ear.prev !== ear.next ) {
  20386. prev = ear.prev;
  20387. next = ear.next;
  20388. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20389. // cut off the triangle
  20390. triangles.push( prev.i / dim );
  20391. triangles.push( ear.i / dim );
  20392. triangles.push( next.i / dim );
  20393. removeNode( ear );
  20394. // skipping the next vertice leads to less sliver triangles
  20395. ear = next.next;
  20396. stop = next.next;
  20397. continue;
  20398. }
  20399. ear = next;
  20400. // if we looped through the whole remaining polygon and can't find any more ears
  20401. if ( ear === stop ) {
  20402. // try filtering points and slicing again
  20403. if ( ! pass ) {
  20404. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20405. // if this didn't work, try curing all small self-intersections locally
  20406. } else if ( pass === 1 ) {
  20407. ear = cureLocalIntersections( ear, triangles, dim );
  20408. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20409. // as a last resort, try splitting the remaining polygon into two
  20410. } else if ( pass === 2 ) {
  20411. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20412. }
  20413. break;
  20414. }
  20415. }
  20416. }
  20417. // check whether a polygon node forms a valid ear with adjacent nodes
  20418. function isEar( ear ) {
  20419. var a = ear.prev,
  20420. b = ear,
  20421. c = ear.next;
  20422. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20423. // now make sure we don't have other points inside the potential ear
  20424. var p = ear.next.next;
  20425. while ( p !== ear.prev ) {
  20426. 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 ) {
  20427. return false;
  20428. }
  20429. p = p.next;
  20430. }
  20431. return true;
  20432. }
  20433. function isEarHashed( ear, minX, minY, invSize ) {
  20434. var a = ear.prev,
  20435. b = ear,
  20436. c = ear.next;
  20437. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20438. // triangle bbox; min & max are calculated like this for speed
  20439. var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  20440. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  20441. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  20442. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  20443. // z-order range for the current triangle bbox;
  20444. var minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  20445. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  20446. // first look for points inside the triangle in increasing z-order
  20447. var p = ear.nextZ;
  20448. while ( p && p.z <= maxZ ) {
  20449. if ( p !== ear.prev && p !== ear.next &&
  20450. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20451. area( p.prev, p, p.next ) >= 0 ) return false;
  20452. p = p.nextZ;
  20453. }
  20454. // then look for points in decreasing z-order
  20455. p = ear.prevZ;
  20456. while ( p && p.z >= minZ ) {
  20457. if ( p !== ear.prev && p !== ear.next &&
  20458. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20459. area( p.prev, p, p.next ) >= 0 ) return false;
  20460. p = p.prevZ;
  20461. }
  20462. return true;
  20463. }
  20464. // go through all polygon nodes and cure small local self-intersections
  20465. function cureLocalIntersections( start, triangles, dim ) {
  20466. var p = start;
  20467. do {
  20468. var a = p.prev, b = p.next.next;
  20469. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20470. triangles.push( a.i / dim );
  20471. triangles.push( p.i / dim );
  20472. triangles.push( b.i / dim );
  20473. // remove two nodes involved
  20474. removeNode( p );
  20475. removeNode( p.next );
  20476. p = start = b;
  20477. }
  20478. p = p.next;
  20479. } while ( p !== start );
  20480. return p;
  20481. }
  20482. // try splitting polygon into two and triangulate them independently
  20483. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20484. // look for a valid diagonal that divides the polygon into two
  20485. var a = start;
  20486. do {
  20487. var b = a.next.next;
  20488. while ( b !== a.prev ) {
  20489. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20490. // split the polygon in two by the diagonal
  20491. var c = splitPolygon( a, b );
  20492. // filter colinear points around the cuts
  20493. a = filterPoints( a, a.next );
  20494. c = filterPoints( c, c.next );
  20495. // run earcut on each half
  20496. earcutLinked( a, triangles, dim, minX, minY, invSize );
  20497. earcutLinked( c, triangles, dim, minX, minY, invSize );
  20498. return;
  20499. }
  20500. b = b.next;
  20501. }
  20502. a = a.next;
  20503. } while ( a !== start );
  20504. }
  20505. // link every hole into the outer loop, producing a single-ring polygon without holes
  20506. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20507. var queue = [], i, len, start, end, list;
  20508. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20509. start = holeIndices[ i ] * dim;
  20510. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20511. list = linkedList( data, start, end, dim, false );
  20512. if ( list === list.next ) list.steiner = true;
  20513. queue.push( getLeftmost( list ) );
  20514. }
  20515. queue.sort( compareX );
  20516. // process holes from left to right
  20517. for ( i = 0; i < queue.length; i ++ ) {
  20518. eliminateHole( queue[ i ], outerNode );
  20519. outerNode = filterPoints( outerNode, outerNode.next );
  20520. }
  20521. return outerNode;
  20522. }
  20523. function compareX( a, b ) {
  20524. return a.x - b.x;
  20525. }
  20526. // find a bridge between vertices that connects hole with an outer ring and and link it
  20527. function eliminateHole( hole, outerNode ) {
  20528. outerNode = findHoleBridge( hole, outerNode );
  20529. if ( outerNode ) {
  20530. var b = splitPolygon( outerNode, hole );
  20531. filterPoints( b, b.next );
  20532. }
  20533. }
  20534. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20535. function findHoleBridge( hole, outerNode ) {
  20536. var p = outerNode,
  20537. hx = hole.x,
  20538. hy = hole.y,
  20539. qx = - Infinity,
  20540. m;
  20541. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20542. // segment's endpoint with lesser x will be potential connection point
  20543. do {
  20544. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20545. var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20546. if ( x <= hx && x > qx ) {
  20547. qx = x;
  20548. if ( x === hx ) {
  20549. if ( hy === p.y ) return p;
  20550. if ( hy === p.next.y ) return p.next;
  20551. }
  20552. m = p.x < p.next.x ? p : p.next;
  20553. }
  20554. }
  20555. p = p.next;
  20556. } while ( p !== outerNode );
  20557. if ( ! m ) return null;
  20558. if ( hx === qx ) return m.prev; // hole touches outer segment; pick lower endpoint
  20559. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20560. // if there are no points found, we have a valid connection;
  20561. // otherwise choose the point of the minimum angle with the ray as connection point
  20562. var stop = m,
  20563. mx = m.x,
  20564. my = m.y,
  20565. tanMin = Infinity,
  20566. tan;
  20567. p = m.next;
  20568. while ( p !== stop ) {
  20569. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20570. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20571. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20572. if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) {
  20573. m = p;
  20574. tanMin = tan;
  20575. }
  20576. }
  20577. p = p.next;
  20578. }
  20579. return m;
  20580. }
  20581. // interlink polygon nodes in z-order
  20582. function indexCurve( start, minX, minY, invSize ) {
  20583. var p = start;
  20584. do {
  20585. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20586. p.prevZ = p.prev;
  20587. p.nextZ = p.next;
  20588. p = p.next;
  20589. } while ( p !== start );
  20590. p.prevZ.nextZ = null;
  20591. p.prevZ = null;
  20592. sortLinked( p );
  20593. }
  20594. // Simon Tatham's linked list merge sort algorithm
  20595. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20596. function sortLinked( list ) {
  20597. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  20598. do {
  20599. p = list;
  20600. list = null;
  20601. tail = null;
  20602. numMerges = 0;
  20603. while ( p ) {
  20604. numMerges ++;
  20605. q = p;
  20606. pSize = 0;
  20607. for ( i = 0; i < inSize; i ++ ) {
  20608. pSize ++;
  20609. q = q.nextZ;
  20610. if ( ! q ) break;
  20611. }
  20612. qSize = inSize;
  20613. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20614. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20615. e = p;
  20616. p = p.nextZ;
  20617. pSize --;
  20618. } else {
  20619. e = q;
  20620. q = q.nextZ;
  20621. qSize --;
  20622. }
  20623. if ( tail ) tail.nextZ = e;
  20624. else list = e;
  20625. e.prevZ = tail;
  20626. tail = e;
  20627. }
  20628. p = q;
  20629. }
  20630. tail.nextZ = null;
  20631. inSize *= 2;
  20632. } while ( numMerges > 1 );
  20633. return list;
  20634. }
  20635. // z-order of a point given coords and inverse of the longer side of data bbox
  20636. function zOrder( x, y, minX, minY, invSize ) {
  20637. // coords are transformed into non-negative 15-bit integer range
  20638. x = 32767 * ( x - minX ) * invSize;
  20639. y = 32767 * ( y - minY ) * invSize;
  20640. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20641. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20642. x = ( x | ( x << 2 ) ) & 0x33333333;
  20643. x = ( x | ( x << 1 ) ) & 0x55555555;
  20644. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20645. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20646. y = ( y | ( y << 2 ) ) & 0x33333333;
  20647. y = ( y | ( y << 1 ) ) & 0x55555555;
  20648. return x | ( y << 1 );
  20649. }
  20650. // find the leftmost node of a polygon ring
  20651. function getLeftmost( start ) {
  20652. var p = start, leftmost = start;
  20653. do {
  20654. if ( p.x < leftmost.x ) leftmost = p;
  20655. p = p.next;
  20656. } while ( p !== start );
  20657. return leftmost;
  20658. }
  20659. // check if a point lies within a convex triangle
  20660. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20661. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  20662. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  20663. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  20664. }
  20665. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20666. function isValidDiagonal( a, b ) {
  20667. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) &&
  20668. locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b );
  20669. }
  20670. // signed area of a triangle
  20671. function area( p, q, r ) {
  20672. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20673. }
  20674. // check if two points are equal
  20675. function equals( p1, p2 ) {
  20676. return p1.x === p2.x && p1.y === p2.y;
  20677. }
  20678. // check if two segments intersect
  20679. function intersects( p1, q1, p2, q2 ) {
  20680. if ( ( equals( p1, q1 ) && equals( p2, q2 ) ) ||
  20681. ( equals( p1, q2 ) && equals( p2, q1 ) ) ) return true;
  20682. return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 &&
  20683. area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0;
  20684. }
  20685. // check if a polygon diagonal intersects any polygon segments
  20686. function intersectsPolygon( a, b ) {
  20687. var p = a;
  20688. do {
  20689. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20690. intersects( p, p.next, a, b ) ) {
  20691. return true;
  20692. }
  20693. p = p.next;
  20694. } while ( p !== a );
  20695. return false;
  20696. }
  20697. // check if a polygon diagonal is locally inside the polygon
  20698. function locallyInside( a, b ) {
  20699. return area( a.prev, a, a.next ) < 0 ?
  20700. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20701. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20702. }
  20703. // check if the middle point of a polygon diagonal is inside the polygon
  20704. function middleInside( a, b ) {
  20705. var p = a,
  20706. inside = false,
  20707. px = ( a.x + b.x ) / 2,
  20708. py = ( a.y + b.y ) / 2;
  20709. do {
  20710. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20711. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) {
  20712. inside = ! inside;
  20713. }
  20714. p = p.next;
  20715. } while ( p !== a );
  20716. return inside;
  20717. }
  20718. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20719. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20720. function splitPolygon( a, b ) {
  20721. var a2 = new Node( a.i, a.x, a.y ),
  20722. b2 = new Node( b.i, b.x, b.y ),
  20723. an = a.next,
  20724. bp = b.prev;
  20725. a.next = b;
  20726. b.prev = a;
  20727. a2.next = an;
  20728. an.prev = a2;
  20729. b2.next = a2;
  20730. a2.prev = b2;
  20731. bp.next = b2;
  20732. b2.prev = bp;
  20733. return b2;
  20734. }
  20735. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20736. function insertNode( i, x, y, last ) {
  20737. var p = new Node( i, x, y );
  20738. if ( ! last ) {
  20739. p.prev = p;
  20740. p.next = p;
  20741. } else {
  20742. p.next = last.next;
  20743. p.prev = last;
  20744. last.next.prev = p;
  20745. last.next = p;
  20746. }
  20747. return p;
  20748. }
  20749. function removeNode( p ) {
  20750. p.next.prev = p.prev;
  20751. p.prev.next = p.next;
  20752. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20753. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20754. }
  20755. function Node( i, x, y ) {
  20756. // vertice index in coordinates array
  20757. this.i = i;
  20758. // vertex coordinates
  20759. this.x = x;
  20760. this.y = y;
  20761. // previous and next vertice nodes in a polygon ring
  20762. this.prev = null;
  20763. this.next = null;
  20764. // z-order curve value
  20765. this.z = null;
  20766. // previous and next nodes in z-order
  20767. this.prevZ = null;
  20768. this.nextZ = null;
  20769. // indicates whether this is a steiner point
  20770. this.steiner = false;
  20771. }
  20772. function signedArea( data, start, end, dim ) {
  20773. var sum = 0;
  20774. for ( var i = start, j = end - dim; i < end; i += dim ) {
  20775. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20776. j = i;
  20777. }
  20778. return sum;
  20779. }
  20780. /**
  20781. * @author zz85 / http://www.lab4games.net/zz85/blog
  20782. */
  20783. var ShapeUtils = {
  20784. // calculate area of the contour polygon
  20785. area: function ( contour ) {
  20786. var n = contour.length;
  20787. var a = 0.0;
  20788. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  20789. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20790. }
  20791. return a * 0.5;
  20792. },
  20793. isClockWise: function ( pts ) {
  20794. return ShapeUtils.area( pts ) < 0;
  20795. },
  20796. triangulateShape: function ( contour, holes ) {
  20797. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20798. var holeIndices = []; // array of hole indices
  20799. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20800. removeDupEndPts( contour );
  20801. addContour( vertices, contour );
  20802. //
  20803. var holeIndex = contour.length;
  20804. holes.forEach( removeDupEndPts );
  20805. for ( var i = 0; i < holes.length; i ++ ) {
  20806. holeIndices.push( holeIndex );
  20807. holeIndex += holes[ i ].length;
  20808. addContour( vertices, holes[ i ] );
  20809. }
  20810. //
  20811. var triangles = Earcut.triangulate( vertices, holeIndices );
  20812. //
  20813. for ( var i = 0; i < triangles.length; i += 3 ) {
  20814. faces.push( triangles.slice( i, i + 3 ) );
  20815. }
  20816. return faces;
  20817. }
  20818. };
  20819. function removeDupEndPts( points ) {
  20820. var l = points.length;
  20821. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20822. points.pop();
  20823. }
  20824. }
  20825. function addContour( vertices, contour ) {
  20826. for ( var i = 0; i < contour.length; i ++ ) {
  20827. vertices.push( contour[ i ].x );
  20828. vertices.push( contour[ i ].y );
  20829. }
  20830. }
  20831. /**
  20832. * @author zz85 / http://www.lab4games.net/zz85/blog
  20833. *
  20834. * Creates extruded geometry from a path shape.
  20835. *
  20836. * parameters = {
  20837. *
  20838. * curveSegments: <int>, // number of points on the curves
  20839. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20840. * depth: <float>, // Depth to extrude the shape
  20841. *
  20842. * bevelEnabled: <bool>, // turn on bevel
  20843. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20844. * bevelSize: <float>, // how far from shape outline is bevel
  20845. * bevelSegments: <int>, // number of bevel layers
  20846. *
  20847. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20848. *
  20849. * UVGenerator: <Object> // object that provides UV generator functions
  20850. *
  20851. * }
  20852. */
  20853. // ExtrudeGeometry
  20854. function ExtrudeGeometry( shapes, options ) {
  20855. Geometry.call( this );
  20856. this.type = 'ExtrudeGeometry';
  20857. this.parameters = {
  20858. shapes: shapes,
  20859. options: options
  20860. };
  20861. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  20862. this.mergeVertices();
  20863. }
  20864. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  20865. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  20866. ExtrudeGeometry.prototype.toJSON = function () {
  20867. var data = Geometry.prototype.toJSON.call( this );
  20868. var shapes = this.parameters.shapes;
  20869. var options = this.parameters.options;
  20870. return toJSON( shapes, options, data );
  20871. };
  20872. // ExtrudeBufferGeometry
  20873. function ExtrudeBufferGeometry( shapes, options ) {
  20874. BufferGeometry.call( this );
  20875. this.type = 'ExtrudeBufferGeometry';
  20876. this.parameters = {
  20877. shapes: shapes,
  20878. options: options
  20879. };
  20880. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20881. var scope = this;
  20882. var verticesArray = [];
  20883. var uvArray = [];
  20884. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  20885. var shape = shapes[ i ];
  20886. addShape( shape );
  20887. }
  20888. // build geometry
  20889. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  20890. this.addAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  20891. this.computeVertexNormals();
  20892. // functions
  20893. function addShape( shape ) {
  20894. var placeholder = [];
  20895. // options
  20896. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20897. var steps = options.steps !== undefined ? options.steps : 1;
  20898. var depth = options.depth !== undefined ? options.depth : 100;
  20899. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20900. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  20901. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  20902. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20903. var extrudePath = options.extrudePath;
  20904. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  20905. // deprecated options
  20906. if ( options.amount !== undefined ) {
  20907. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  20908. depth = options.amount;
  20909. }
  20910. //
  20911. var extrudePts, extrudeByPath = false;
  20912. var splineTube, binormal, normal, position2;
  20913. if ( extrudePath ) {
  20914. extrudePts = extrudePath.getSpacedPoints( steps );
  20915. extrudeByPath = true;
  20916. bevelEnabled = false; // bevels not supported for path extrusion
  20917. // SETUP TNB variables
  20918. // TODO1 - have a .isClosed in spline?
  20919. splineTube = extrudePath.computeFrenetFrames( steps, false );
  20920. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20921. binormal = new Vector3();
  20922. normal = new Vector3();
  20923. position2 = new Vector3();
  20924. }
  20925. // Safeguards if bevels are not enabled
  20926. if ( ! bevelEnabled ) {
  20927. bevelSegments = 0;
  20928. bevelThickness = 0;
  20929. bevelSize = 0;
  20930. }
  20931. // Variables initialization
  20932. var ahole, h, hl; // looping of holes
  20933. var shapePoints = shape.extractPoints( curveSegments );
  20934. var vertices = shapePoints.shape;
  20935. var holes = shapePoints.holes;
  20936. var reverse = ! ShapeUtils.isClockWise( vertices );
  20937. if ( reverse ) {
  20938. vertices = vertices.reverse();
  20939. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20940. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20941. ahole = holes[ h ];
  20942. if ( ShapeUtils.isClockWise( ahole ) ) {
  20943. holes[ h ] = ahole.reverse();
  20944. }
  20945. }
  20946. }
  20947. var faces = ShapeUtils.triangulateShape( vertices, holes );
  20948. /* Vertices */
  20949. var contour = vertices; // vertices has all points but contour has only points of circumference
  20950. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20951. ahole = holes[ h ];
  20952. vertices = vertices.concat( ahole );
  20953. }
  20954. function scalePt2( pt, vec, size ) {
  20955. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  20956. return vec.clone().multiplyScalar( size ).add( pt );
  20957. }
  20958. var b, bs, t, z,
  20959. vert, vlen = vertices.length,
  20960. face, flen = faces.length;
  20961. // Find directions for point movement
  20962. function getBevelVec( inPt, inPrev, inNext ) {
  20963. // computes for inPt the corresponding point inPt' on a new contour
  20964. // shifted by 1 unit (length of normalized vector) to the left
  20965. // if we walk along contour clockwise, this new contour is outside the old one
  20966. //
  20967. // inPt' is the intersection of the two lines parallel to the two
  20968. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20969. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20970. // good reading for geometry algorithms (here: line-line intersection)
  20971. // http://geomalgorithms.com/a05-_intersect-1.html
  20972. var v_prev_x = inPt.x - inPrev.x,
  20973. v_prev_y = inPt.y - inPrev.y;
  20974. var v_next_x = inNext.x - inPt.x,
  20975. v_next_y = inNext.y - inPt.y;
  20976. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20977. // check for collinear edges
  20978. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20979. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20980. // not collinear
  20981. // length of vectors for normalizing
  20982. var v_prev_len = Math.sqrt( v_prev_lensq );
  20983. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20984. // shift adjacent points by unit vectors to the left
  20985. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20986. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20987. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20988. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20989. // scaling factor for v_prev to intersection point
  20990. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20991. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20992. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20993. // vector from inPt to intersection point
  20994. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20995. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20996. // Don't normalize!, otherwise sharp corners become ugly
  20997. // but prevent crazy spikes
  20998. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20999. if ( v_trans_lensq <= 2 ) {
  21000. return new Vector2( v_trans_x, v_trans_y );
  21001. } else {
  21002. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21003. }
  21004. } else {
  21005. // handle special case of collinear edges
  21006. var direction_eq = false; // assumes: opposite
  21007. if ( v_prev_x > Number.EPSILON ) {
  21008. if ( v_next_x > Number.EPSILON ) {
  21009. direction_eq = true;
  21010. }
  21011. } else {
  21012. if ( v_prev_x < - Number.EPSILON ) {
  21013. if ( v_next_x < - Number.EPSILON ) {
  21014. direction_eq = true;
  21015. }
  21016. } else {
  21017. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21018. direction_eq = true;
  21019. }
  21020. }
  21021. }
  21022. if ( direction_eq ) {
  21023. // console.log("Warning: lines are a straight sequence");
  21024. v_trans_x = - v_prev_y;
  21025. v_trans_y = v_prev_x;
  21026. shrink_by = Math.sqrt( v_prev_lensq );
  21027. } else {
  21028. // console.log("Warning: lines are a straight spike");
  21029. v_trans_x = v_prev_x;
  21030. v_trans_y = v_prev_y;
  21031. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21032. }
  21033. }
  21034. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21035. }
  21036. var contourMovements = [];
  21037. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21038. if ( j === il ) j = 0;
  21039. if ( k === il ) k = 0;
  21040. // (j)---(i)---(k)
  21041. // console.log('i,j,k', i, j , k)
  21042. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21043. }
  21044. var holesMovements = [],
  21045. oneHoleMovements, verticesMovements = contourMovements.concat();
  21046. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21047. ahole = holes[ h ];
  21048. oneHoleMovements = [];
  21049. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21050. if ( j === il ) j = 0;
  21051. if ( k === il ) k = 0;
  21052. // (j)---(i)---(k)
  21053. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21054. }
  21055. holesMovements.push( oneHoleMovements );
  21056. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21057. }
  21058. // Loop bevelSegments, 1 for the front, 1 for the back
  21059. for ( b = 0; b < bevelSegments; b ++ ) {
  21060. //for ( b = bevelSegments; b > 0; b -- ) {
  21061. t = b / bevelSegments;
  21062. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21063. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  21064. // contract shape
  21065. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21066. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21067. v( vert.x, vert.y, - z );
  21068. }
  21069. // expand holes
  21070. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21071. ahole = holes[ h ];
  21072. oneHoleMovements = holesMovements[ h ];
  21073. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21074. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21075. v( vert.x, vert.y, - z );
  21076. }
  21077. }
  21078. }
  21079. bs = bevelSize;
  21080. // Back facing vertices
  21081. for ( i = 0; i < vlen; i ++ ) {
  21082. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21083. if ( ! extrudeByPath ) {
  21084. v( vert.x, vert.y, 0 );
  21085. } else {
  21086. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21087. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21088. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21089. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21090. v( position2.x, position2.y, position2.z );
  21091. }
  21092. }
  21093. // Add stepped vertices...
  21094. // Including front facing vertices
  21095. var s;
  21096. for ( s = 1; s <= steps; s ++ ) {
  21097. for ( i = 0; i < vlen; i ++ ) {
  21098. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21099. if ( ! extrudeByPath ) {
  21100. v( vert.x, vert.y, depth / steps * s );
  21101. } else {
  21102. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21103. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21104. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21105. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21106. v( position2.x, position2.y, position2.z );
  21107. }
  21108. }
  21109. }
  21110. // Add bevel segments planes
  21111. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21112. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  21113. t = b / bevelSegments;
  21114. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21115. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  21116. // contract shape
  21117. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21118. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21119. v( vert.x, vert.y, depth + z );
  21120. }
  21121. // expand holes
  21122. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21123. ahole = holes[ h ];
  21124. oneHoleMovements = holesMovements[ h ];
  21125. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21126. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21127. if ( ! extrudeByPath ) {
  21128. v( vert.x, vert.y, depth + z );
  21129. } else {
  21130. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21131. }
  21132. }
  21133. }
  21134. }
  21135. /* Faces */
  21136. // Top and bottom faces
  21137. buildLidFaces();
  21138. // Sides faces
  21139. buildSideFaces();
  21140. ///// Internal functions
  21141. function buildLidFaces() {
  21142. var start = verticesArray.length / 3;
  21143. if ( bevelEnabled ) {
  21144. var layer = 0; // steps + 1
  21145. var offset = vlen * layer;
  21146. // Bottom faces
  21147. for ( i = 0; i < flen; i ++ ) {
  21148. face = faces[ i ];
  21149. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21150. }
  21151. layer = steps + bevelSegments * 2;
  21152. offset = vlen * layer;
  21153. // Top faces
  21154. for ( i = 0; i < flen; i ++ ) {
  21155. face = faces[ i ];
  21156. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21157. }
  21158. } else {
  21159. // Bottom faces
  21160. for ( i = 0; i < flen; i ++ ) {
  21161. face = faces[ i ];
  21162. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21163. }
  21164. // Top faces
  21165. for ( i = 0; i < flen; i ++ ) {
  21166. face = faces[ i ];
  21167. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21168. }
  21169. }
  21170. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21171. }
  21172. // Create faces for the z-sides of the shape
  21173. function buildSideFaces() {
  21174. var start = verticesArray.length / 3;
  21175. var layeroffset = 0;
  21176. sidewalls( contour, layeroffset );
  21177. layeroffset += contour.length;
  21178. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21179. ahole = holes[ h ];
  21180. sidewalls( ahole, layeroffset );
  21181. //, true
  21182. layeroffset += ahole.length;
  21183. }
  21184. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21185. }
  21186. function sidewalls( contour, layeroffset ) {
  21187. var j, k;
  21188. i = contour.length;
  21189. while ( -- i >= 0 ) {
  21190. j = i;
  21191. k = i - 1;
  21192. if ( k < 0 ) k = contour.length - 1;
  21193. //console.log('b', i,j, i-1, k,vertices.length);
  21194. var s = 0,
  21195. sl = steps + bevelSegments * 2;
  21196. for ( s = 0; s < sl; s ++ ) {
  21197. var slen1 = vlen * s;
  21198. var slen2 = vlen * ( s + 1 );
  21199. var a = layeroffset + j + slen1,
  21200. b = layeroffset + k + slen1,
  21201. c = layeroffset + k + slen2,
  21202. d = layeroffset + j + slen2;
  21203. f4( a, b, c, d );
  21204. }
  21205. }
  21206. }
  21207. function v( x, y, z ) {
  21208. placeholder.push( x );
  21209. placeholder.push( y );
  21210. placeholder.push( z );
  21211. }
  21212. function f3( a, b, c ) {
  21213. addVertex( a );
  21214. addVertex( b );
  21215. addVertex( c );
  21216. var nextIndex = verticesArray.length / 3;
  21217. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21218. addUV( uvs[ 0 ] );
  21219. addUV( uvs[ 1 ] );
  21220. addUV( uvs[ 2 ] );
  21221. }
  21222. function f4( a, b, c, d ) {
  21223. addVertex( a );
  21224. addVertex( b );
  21225. addVertex( d );
  21226. addVertex( b );
  21227. addVertex( c );
  21228. addVertex( d );
  21229. var nextIndex = verticesArray.length / 3;
  21230. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21231. addUV( uvs[ 0 ] );
  21232. addUV( uvs[ 1 ] );
  21233. addUV( uvs[ 3 ] );
  21234. addUV( uvs[ 1 ] );
  21235. addUV( uvs[ 2 ] );
  21236. addUV( uvs[ 3 ] );
  21237. }
  21238. function addVertex( index ) {
  21239. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21240. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21241. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21242. }
  21243. function addUV( vector2 ) {
  21244. uvArray.push( vector2.x );
  21245. uvArray.push( vector2.y );
  21246. }
  21247. }
  21248. }
  21249. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21250. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  21251. ExtrudeBufferGeometry.prototype.toJSON = function () {
  21252. var data = BufferGeometry.prototype.toJSON.call( this );
  21253. var shapes = this.parameters.shapes;
  21254. var options = this.parameters.options;
  21255. return toJSON( shapes, options, data );
  21256. };
  21257. //
  21258. var WorldUVGenerator = {
  21259. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21260. var a_x = vertices[ indexA * 3 ];
  21261. var a_y = vertices[ indexA * 3 + 1 ];
  21262. var b_x = vertices[ indexB * 3 ];
  21263. var b_y = vertices[ indexB * 3 + 1 ];
  21264. var c_x = vertices[ indexC * 3 ];
  21265. var c_y = vertices[ indexC * 3 + 1 ];
  21266. return [
  21267. new Vector2( a_x, a_y ),
  21268. new Vector2( b_x, b_y ),
  21269. new Vector2( c_x, c_y )
  21270. ];
  21271. },
  21272. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21273. var a_x = vertices[ indexA * 3 ];
  21274. var a_y = vertices[ indexA * 3 + 1 ];
  21275. var a_z = vertices[ indexA * 3 + 2 ];
  21276. var b_x = vertices[ indexB * 3 ];
  21277. var b_y = vertices[ indexB * 3 + 1 ];
  21278. var b_z = vertices[ indexB * 3 + 2 ];
  21279. var c_x = vertices[ indexC * 3 ];
  21280. var c_y = vertices[ indexC * 3 + 1 ];
  21281. var c_z = vertices[ indexC * 3 + 2 ];
  21282. var d_x = vertices[ indexD * 3 ];
  21283. var d_y = vertices[ indexD * 3 + 1 ];
  21284. var d_z = vertices[ indexD * 3 + 2 ];
  21285. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  21286. return [
  21287. new Vector2( a_x, 1 - a_z ),
  21288. new Vector2( b_x, 1 - b_z ),
  21289. new Vector2( c_x, 1 - c_z ),
  21290. new Vector2( d_x, 1 - d_z )
  21291. ];
  21292. } else {
  21293. return [
  21294. new Vector2( a_y, 1 - a_z ),
  21295. new Vector2( b_y, 1 - b_z ),
  21296. new Vector2( c_y, 1 - c_z ),
  21297. new Vector2( d_y, 1 - d_z )
  21298. ];
  21299. }
  21300. }
  21301. };
  21302. function toJSON( shapes, options, data ) {
  21303. //
  21304. data.shapes = [];
  21305. if ( Array.isArray( shapes ) ) {
  21306. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  21307. var shape = shapes[ i ];
  21308. data.shapes.push( shape.uuid );
  21309. }
  21310. } else {
  21311. data.shapes.push( shapes.uuid );
  21312. }
  21313. //
  21314. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21315. return data;
  21316. }
  21317. /**
  21318. * @author zz85 / http://www.lab4games.net/zz85/blog
  21319. * @author alteredq / http://alteredqualia.com/
  21320. *
  21321. * Text = 3D Text
  21322. *
  21323. * parameters = {
  21324. * font: <THREE.Font>, // font
  21325. *
  21326. * size: <float>, // size of the text
  21327. * height: <float>, // thickness to extrude text
  21328. * curveSegments: <int>, // number of points on the curves
  21329. *
  21330. * bevelEnabled: <bool>, // turn on bevel
  21331. * bevelThickness: <float>, // how deep into text bevel goes
  21332. * bevelSize: <float> // how far from text outline is bevel
  21333. * }
  21334. */
  21335. // TextGeometry
  21336. function TextGeometry( text, parameters ) {
  21337. Geometry.call( this );
  21338. this.type = 'TextGeometry';
  21339. this.parameters = {
  21340. text: text,
  21341. parameters: parameters
  21342. };
  21343. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  21344. this.mergeVertices();
  21345. }
  21346. TextGeometry.prototype = Object.create( Geometry.prototype );
  21347. TextGeometry.prototype.constructor = TextGeometry;
  21348. // TextBufferGeometry
  21349. function TextBufferGeometry( text, parameters ) {
  21350. parameters = parameters || {};
  21351. var font = parameters.font;
  21352. if ( ! ( font && font.isFont ) ) {
  21353. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  21354. return new Geometry();
  21355. }
  21356. var shapes = font.generateShapes( text, parameters.size );
  21357. // translate parameters to ExtrudeGeometry API
  21358. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  21359. // defaults
  21360. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  21361. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  21362. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  21363. ExtrudeBufferGeometry.call( this, shapes, parameters );
  21364. this.type = 'TextBufferGeometry';
  21365. }
  21366. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  21367. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  21368. /**
  21369. * @author mrdoob / http://mrdoob.com/
  21370. * @author benaadams / https://twitter.com/ben_a_adams
  21371. * @author Mugen87 / https://github.com/Mugen87
  21372. */
  21373. // SphereGeometry
  21374. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21375. Geometry.call( this );
  21376. this.type = 'SphereGeometry';
  21377. this.parameters = {
  21378. radius: radius,
  21379. widthSegments: widthSegments,
  21380. heightSegments: heightSegments,
  21381. phiStart: phiStart,
  21382. phiLength: phiLength,
  21383. thetaStart: thetaStart,
  21384. thetaLength: thetaLength
  21385. };
  21386. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  21387. this.mergeVertices();
  21388. }
  21389. SphereGeometry.prototype = Object.create( Geometry.prototype );
  21390. SphereGeometry.prototype.constructor = SphereGeometry;
  21391. // SphereBufferGeometry
  21392. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21393. BufferGeometry.call( this );
  21394. this.type = 'SphereBufferGeometry';
  21395. this.parameters = {
  21396. radius: radius,
  21397. widthSegments: widthSegments,
  21398. heightSegments: heightSegments,
  21399. phiStart: phiStart,
  21400. phiLength: phiLength,
  21401. thetaStart: thetaStart,
  21402. thetaLength: thetaLength
  21403. };
  21404. radius = radius || 1;
  21405. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  21406. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  21407. phiStart = phiStart !== undefined ? phiStart : 0;
  21408. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  21409. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21410. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  21411. var thetaEnd = thetaStart + thetaLength;
  21412. var ix, iy;
  21413. var index = 0;
  21414. var grid = [];
  21415. var vertex = new Vector3();
  21416. var normal = new Vector3();
  21417. // buffers
  21418. var indices = [];
  21419. var vertices = [];
  21420. var normals = [];
  21421. var uvs = [];
  21422. // generate vertices, normals and uvs
  21423. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  21424. var verticesRow = [];
  21425. var v = iy / heightSegments;
  21426. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  21427. var u = ix / widthSegments;
  21428. // vertex
  21429. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21430. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21431. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21432. vertices.push( vertex.x, vertex.y, vertex.z );
  21433. // normal
  21434. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  21435. normals.push( normal.x, normal.y, normal.z );
  21436. // uv
  21437. uvs.push( u, 1 - v );
  21438. verticesRow.push( index ++ );
  21439. }
  21440. grid.push( verticesRow );
  21441. }
  21442. // indices
  21443. for ( iy = 0; iy < heightSegments; iy ++ ) {
  21444. for ( ix = 0; ix < widthSegments; ix ++ ) {
  21445. var a = grid[ iy ][ ix + 1 ];
  21446. var b = grid[ iy ][ ix ];
  21447. var c = grid[ iy + 1 ][ ix ];
  21448. var d = grid[ iy + 1 ][ ix + 1 ];
  21449. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21450. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21451. }
  21452. }
  21453. // build geometry
  21454. this.setIndex( indices );
  21455. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21456. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21457. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21458. }
  21459. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21460. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  21461. /**
  21462. * @author Kaleb Murphy
  21463. * @author Mugen87 / https://github.com/Mugen87
  21464. */
  21465. // RingGeometry
  21466. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21467. Geometry.call( this );
  21468. this.type = 'RingGeometry';
  21469. this.parameters = {
  21470. innerRadius: innerRadius,
  21471. outerRadius: outerRadius,
  21472. thetaSegments: thetaSegments,
  21473. phiSegments: phiSegments,
  21474. thetaStart: thetaStart,
  21475. thetaLength: thetaLength
  21476. };
  21477. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  21478. this.mergeVertices();
  21479. }
  21480. RingGeometry.prototype = Object.create( Geometry.prototype );
  21481. RingGeometry.prototype.constructor = RingGeometry;
  21482. // RingBufferGeometry
  21483. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21484. BufferGeometry.call( this );
  21485. this.type = 'RingBufferGeometry';
  21486. this.parameters = {
  21487. innerRadius: innerRadius,
  21488. outerRadius: outerRadius,
  21489. thetaSegments: thetaSegments,
  21490. phiSegments: phiSegments,
  21491. thetaStart: thetaStart,
  21492. thetaLength: thetaLength
  21493. };
  21494. innerRadius = innerRadius || 0.5;
  21495. outerRadius = outerRadius || 1;
  21496. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21497. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21498. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  21499. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  21500. // buffers
  21501. var indices = [];
  21502. var vertices = [];
  21503. var normals = [];
  21504. var uvs = [];
  21505. // some helper variables
  21506. var segment;
  21507. var radius = innerRadius;
  21508. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21509. var vertex = new Vector3();
  21510. var uv = new Vector2();
  21511. var j, i;
  21512. // generate vertices, normals and uvs
  21513. for ( j = 0; j <= phiSegments; j ++ ) {
  21514. for ( i = 0; i <= thetaSegments; i ++ ) {
  21515. // values are generate from the inside of the ring to the outside
  21516. segment = thetaStart + i / thetaSegments * thetaLength;
  21517. // vertex
  21518. vertex.x = radius * Math.cos( segment );
  21519. vertex.y = radius * Math.sin( segment );
  21520. vertices.push( vertex.x, vertex.y, vertex.z );
  21521. // normal
  21522. normals.push( 0, 0, 1 );
  21523. // uv
  21524. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21525. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21526. uvs.push( uv.x, uv.y );
  21527. }
  21528. // increase the radius for next row of vertices
  21529. radius += radiusStep;
  21530. }
  21531. // indices
  21532. for ( j = 0; j < phiSegments; j ++ ) {
  21533. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  21534. for ( i = 0; i < thetaSegments; i ++ ) {
  21535. segment = i + thetaSegmentLevel;
  21536. var a = segment;
  21537. var b = segment + thetaSegments + 1;
  21538. var c = segment + thetaSegments + 2;
  21539. var d = segment + 1;
  21540. // faces
  21541. indices.push( a, b, d );
  21542. indices.push( b, c, d );
  21543. }
  21544. }
  21545. // build geometry
  21546. this.setIndex( indices );
  21547. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21548. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21549. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21550. }
  21551. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21552. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  21553. /**
  21554. * @author astrodud / http://astrodud.isgreat.org/
  21555. * @author zz85 / https://github.com/zz85
  21556. * @author bhouston / http://clara.io
  21557. * @author Mugen87 / https://github.com/Mugen87
  21558. */
  21559. // LatheGeometry
  21560. function LatheGeometry( points, segments, phiStart, phiLength ) {
  21561. Geometry.call( this );
  21562. this.type = 'LatheGeometry';
  21563. this.parameters = {
  21564. points: points,
  21565. segments: segments,
  21566. phiStart: phiStart,
  21567. phiLength: phiLength
  21568. };
  21569. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  21570. this.mergeVertices();
  21571. }
  21572. LatheGeometry.prototype = Object.create( Geometry.prototype );
  21573. LatheGeometry.prototype.constructor = LatheGeometry;
  21574. // LatheBufferGeometry
  21575. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  21576. BufferGeometry.call( this );
  21577. this.type = 'LatheBufferGeometry';
  21578. this.parameters = {
  21579. points: points,
  21580. segments: segments,
  21581. phiStart: phiStart,
  21582. phiLength: phiLength
  21583. };
  21584. segments = Math.floor( segments ) || 12;
  21585. phiStart = phiStart || 0;
  21586. phiLength = phiLength || Math.PI * 2;
  21587. // clamp phiLength so it's in range of [ 0, 2PI ]
  21588. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  21589. // buffers
  21590. var indices = [];
  21591. var vertices = [];
  21592. var uvs = [];
  21593. // helper variables
  21594. var base;
  21595. var inverseSegments = 1.0 / segments;
  21596. var vertex = new Vector3();
  21597. var uv = new Vector2();
  21598. var i, j;
  21599. // generate vertices and uvs
  21600. for ( i = 0; i <= segments; i ++ ) {
  21601. var phi = phiStart + i * inverseSegments * phiLength;
  21602. var sin = Math.sin( phi );
  21603. var cos = Math.cos( phi );
  21604. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  21605. // vertex
  21606. vertex.x = points[ j ].x * sin;
  21607. vertex.y = points[ j ].y;
  21608. vertex.z = points[ j ].x * cos;
  21609. vertices.push( vertex.x, vertex.y, vertex.z );
  21610. // uv
  21611. uv.x = i / segments;
  21612. uv.y = j / ( points.length - 1 );
  21613. uvs.push( uv.x, uv.y );
  21614. }
  21615. }
  21616. // indices
  21617. for ( i = 0; i < segments; i ++ ) {
  21618. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  21619. base = j + i * points.length;
  21620. var a = base;
  21621. var b = base + points.length;
  21622. var c = base + points.length + 1;
  21623. var d = base + 1;
  21624. // faces
  21625. indices.push( a, b, d );
  21626. indices.push( b, c, d );
  21627. }
  21628. }
  21629. // build geometry
  21630. this.setIndex( indices );
  21631. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21632. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21633. // generate normals
  21634. this.computeVertexNormals();
  21635. // if the geometry is closed, we need to average the normals along the seam.
  21636. // because the corresponding vertices are identical (but still have different UVs).
  21637. if ( phiLength === Math.PI * 2 ) {
  21638. var normals = this.attributes.normal.array;
  21639. var n1 = new Vector3();
  21640. var n2 = new Vector3();
  21641. var n = new Vector3();
  21642. // this is the buffer offset for the last line of vertices
  21643. base = segments * points.length * 3;
  21644. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  21645. // select the normal of the vertex in the first line
  21646. n1.x = normals[ j + 0 ];
  21647. n1.y = normals[ j + 1 ];
  21648. n1.z = normals[ j + 2 ];
  21649. // select the normal of the vertex in the last line
  21650. n2.x = normals[ base + j + 0 ];
  21651. n2.y = normals[ base + j + 1 ];
  21652. n2.z = normals[ base + j + 2 ];
  21653. // average normals
  21654. n.addVectors( n1, n2 ).normalize();
  21655. // assign the new values to both normals
  21656. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  21657. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  21658. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  21659. }
  21660. }
  21661. }
  21662. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21663. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  21664. /**
  21665. * @author jonobr1 / http://jonobr1.com
  21666. * @author Mugen87 / https://github.com/Mugen87
  21667. */
  21668. // ShapeGeometry
  21669. function ShapeGeometry( shapes, curveSegments ) {
  21670. Geometry.call( this );
  21671. this.type = 'ShapeGeometry';
  21672. if ( typeof curveSegments === 'object' ) {
  21673. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  21674. curveSegments = curveSegments.curveSegments;
  21675. }
  21676. this.parameters = {
  21677. shapes: shapes,
  21678. curveSegments: curveSegments
  21679. };
  21680. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  21681. this.mergeVertices();
  21682. }
  21683. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  21684. ShapeGeometry.prototype.constructor = ShapeGeometry;
  21685. ShapeGeometry.prototype.toJSON = function () {
  21686. var data = Geometry.prototype.toJSON.call( this );
  21687. var shapes = this.parameters.shapes;
  21688. return toJSON$1( shapes, data );
  21689. };
  21690. // ShapeBufferGeometry
  21691. function ShapeBufferGeometry( shapes, curveSegments ) {
  21692. BufferGeometry.call( this );
  21693. this.type = 'ShapeBufferGeometry';
  21694. this.parameters = {
  21695. shapes: shapes,
  21696. curveSegments: curveSegments
  21697. };
  21698. curveSegments = curveSegments || 12;
  21699. // buffers
  21700. var indices = [];
  21701. var vertices = [];
  21702. var normals = [];
  21703. var uvs = [];
  21704. // helper variables
  21705. var groupStart = 0;
  21706. var groupCount = 0;
  21707. // allow single and array values for "shapes" parameter
  21708. if ( Array.isArray( shapes ) === false ) {
  21709. addShape( shapes );
  21710. } else {
  21711. for ( var i = 0; i < shapes.length; i ++ ) {
  21712. addShape( shapes[ i ] );
  21713. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21714. groupStart += groupCount;
  21715. groupCount = 0;
  21716. }
  21717. }
  21718. // build geometry
  21719. this.setIndex( indices );
  21720. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21721. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21722. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21723. // helper functions
  21724. function addShape( shape ) {
  21725. var i, l, shapeHole;
  21726. var indexOffset = vertices.length / 3;
  21727. var points = shape.extractPoints( curveSegments );
  21728. var shapeVertices = points.shape;
  21729. var shapeHoles = points.holes;
  21730. // check direction of vertices
  21731. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21732. shapeVertices = shapeVertices.reverse();
  21733. // also check if holes are in the opposite direction
  21734. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21735. shapeHole = shapeHoles[ i ];
  21736. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21737. shapeHoles[ i ] = shapeHole.reverse();
  21738. }
  21739. }
  21740. }
  21741. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21742. // join vertices of inner and outer paths to a single array
  21743. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21744. shapeHole = shapeHoles[ i ];
  21745. shapeVertices = shapeVertices.concat( shapeHole );
  21746. }
  21747. // vertices, normals, uvs
  21748. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21749. var vertex = shapeVertices[ i ];
  21750. vertices.push( vertex.x, vertex.y, 0 );
  21751. normals.push( 0, 0, 1 );
  21752. uvs.push( vertex.x, vertex.y ); // world uvs
  21753. }
  21754. // incides
  21755. for ( i = 0, l = faces.length; i < l; i ++ ) {
  21756. var face = faces[ i ];
  21757. var a = face[ 0 ] + indexOffset;
  21758. var b = face[ 1 ] + indexOffset;
  21759. var c = face[ 2 ] + indexOffset;
  21760. indices.push( a, b, c );
  21761. groupCount += 3;
  21762. }
  21763. }
  21764. }
  21765. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21766. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  21767. ShapeBufferGeometry.prototype.toJSON = function () {
  21768. var data = BufferGeometry.prototype.toJSON.call( this );
  21769. var shapes = this.parameters.shapes;
  21770. return toJSON$1( shapes, data );
  21771. };
  21772. //
  21773. function toJSON$1( shapes, data ) {
  21774. data.shapes = [];
  21775. if ( Array.isArray( shapes ) ) {
  21776. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  21777. var shape = shapes[ i ];
  21778. data.shapes.push( shape.uuid );
  21779. }
  21780. } else {
  21781. data.shapes.push( shapes.uuid );
  21782. }
  21783. return data;
  21784. }
  21785. /**
  21786. * @author WestLangley / http://github.com/WestLangley
  21787. * @author Mugen87 / https://github.com/Mugen87
  21788. */
  21789. function EdgesGeometry( geometry, thresholdAngle ) {
  21790. BufferGeometry.call( this );
  21791. this.type = 'EdgesGeometry';
  21792. this.parameters = {
  21793. thresholdAngle: thresholdAngle
  21794. };
  21795. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  21796. // buffer
  21797. var vertices = [];
  21798. // helper variables
  21799. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  21800. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  21801. var key, keys = [ 'a', 'b', 'c' ];
  21802. // prepare source geometry
  21803. var geometry2;
  21804. if ( geometry.isBufferGeometry ) {
  21805. geometry2 = new Geometry();
  21806. geometry2.fromBufferGeometry( geometry );
  21807. } else {
  21808. geometry2 = geometry.clone();
  21809. }
  21810. geometry2.mergeVertices();
  21811. geometry2.computeFaceNormals();
  21812. var sourceVertices = geometry2.vertices;
  21813. var faces = geometry2.faces;
  21814. // now create a data structure where each entry represents an edge with its adjoining faces
  21815. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21816. var face = faces[ i ];
  21817. for ( var j = 0; j < 3; j ++ ) {
  21818. edge1 = face[ keys[ j ] ];
  21819. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  21820. edge[ 0 ] = Math.min( edge1, edge2 );
  21821. edge[ 1 ] = Math.max( edge1, edge2 );
  21822. key = edge[ 0 ] + ',' + edge[ 1 ];
  21823. if ( edges[ key ] === undefined ) {
  21824. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  21825. } else {
  21826. edges[ key ].face2 = i;
  21827. }
  21828. }
  21829. }
  21830. // generate vertices
  21831. for ( key in edges ) {
  21832. var e = edges[ key ];
  21833. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  21834. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  21835. var vertex = sourceVertices[ e.index1 ];
  21836. vertices.push( vertex.x, vertex.y, vertex.z );
  21837. vertex = sourceVertices[ e.index2 ];
  21838. vertices.push( vertex.x, vertex.y, vertex.z );
  21839. }
  21840. }
  21841. // build geometry
  21842. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21843. }
  21844. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  21845. EdgesGeometry.prototype.constructor = EdgesGeometry;
  21846. /**
  21847. * @author mrdoob / http://mrdoob.com/
  21848. * @author Mugen87 / https://github.com/Mugen87
  21849. */
  21850. // CylinderGeometry
  21851. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21852. Geometry.call( this );
  21853. this.type = 'CylinderGeometry';
  21854. this.parameters = {
  21855. radiusTop: radiusTop,
  21856. radiusBottom: radiusBottom,
  21857. height: height,
  21858. radialSegments: radialSegments,
  21859. heightSegments: heightSegments,
  21860. openEnded: openEnded,
  21861. thetaStart: thetaStart,
  21862. thetaLength: thetaLength
  21863. };
  21864. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  21865. this.mergeVertices();
  21866. }
  21867. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  21868. CylinderGeometry.prototype.constructor = CylinderGeometry;
  21869. // CylinderBufferGeometry
  21870. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21871. BufferGeometry.call( this );
  21872. this.type = 'CylinderBufferGeometry';
  21873. this.parameters = {
  21874. radiusTop: radiusTop,
  21875. radiusBottom: radiusBottom,
  21876. height: height,
  21877. radialSegments: radialSegments,
  21878. heightSegments: heightSegments,
  21879. openEnded: openEnded,
  21880. thetaStart: thetaStart,
  21881. thetaLength: thetaLength
  21882. };
  21883. var scope = this;
  21884. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  21885. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  21886. height = height || 1;
  21887. radialSegments = Math.floor( radialSegments ) || 8;
  21888. heightSegments = Math.floor( heightSegments ) || 1;
  21889. openEnded = openEnded !== undefined ? openEnded : false;
  21890. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  21891. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21892. // buffers
  21893. var indices = [];
  21894. var vertices = [];
  21895. var normals = [];
  21896. var uvs = [];
  21897. // helper variables
  21898. var index = 0;
  21899. var indexArray = [];
  21900. var halfHeight = height / 2;
  21901. var groupStart = 0;
  21902. // generate geometry
  21903. generateTorso();
  21904. if ( openEnded === false ) {
  21905. if ( radiusTop > 0 ) generateCap( true );
  21906. if ( radiusBottom > 0 ) generateCap( false );
  21907. }
  21908. // build geometry
  21909. this.setIndex( indices );
  21910. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21911. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21912. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21913. function generateTorso() {
  21914. var x, y;
  21915. var normal = new Vector3();
  21916. var vertex = new Vector3();
  21917. var groupCount = 0;
  21918. // this will be used to calculate the normal
  21919. var slope = ( radiusBottom - radiusTop ) / height;
  21920. // generate vertices, normals and uvs
  21921. for ( y = 0; y <= heightSegments; y ++ ) {
  21922. var indexRow = [];
  21923. var v = y / heightSegments;
  21924. // calculate the radius of the current row
  21925. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21926. for ( x = 0; x <= radialSegments; x ++ ) {
  21927. var u = x / radialSegments;
  21928. var theta = u * thetaLength + thetaStart;
  21929. var sinTheta = Math.sin( theta );
  21930. var cosTheta = Math.cos( theta );
  21931. // vertex
  21932. vertex.x = radius * sinTheta;
  21933. vertex.y = - v * height + halfHeight;
  21934. vertex.z = radius * cosTheta;
  21935. vertices.push( vertex.x, vertex.y, vertex.z );
  21936. // normal
  21937. normal.set( sinTheta, slope, cosTheta ).normalize();
  21938. normals.push( normal.x, normal.y, normal.z );
  21939. // uv
  21940. uvs.push( u, 1 - v );
  21941. // save index of vertex in respective row
  21942. indexRow.push( index ++ );
  21943. }
  21944. // now save vertices of the row in our index array
  21945. indexArray.push( indexRow );
  21946. }
  21947. // generate indices
  21948. for ( x = 0; x < radialSegments; x ++ ) {
  21949. for ( y = 0; y < heightSegments; y ++ ) {
  21950. // we use the index array to access the correct indices
  21951. var a = indexArray[ y ][ x ];
  21952. var b = indexArray[ y + 1 ][ x ];
  21953. var c = indexArray[ y + 1 ][ x + 1 ];
  21954. var d = indexArray[ y ][ x + 1 ];
  21955. // faces
  21956. indices.push( a, b, d );
  21957. indices.push( b, c, d );
  21958. // update group counter
  21959. groupCount += 6;
  21960. }
  21961. }
  21962. // add a group to the geometry. this will ensure multi material support
  21963. scope.addGroup( groupStart, groupCount, 0 );
  21964. // calculate new start value for groups
  21965. groupStart += groupCount;
  21966. }
  21967. function generateCap( top ) {
  21968. var x, centerIndexStart, centerIndexEnd;
  21969. var uv = new Vector2();
  21970. var vertex = new Vector3();
  21971. var groupCount = 0;
  21972. var radius = ( top === true ) ? radiusTop : radiusBottom;
  21973. var sign = ( top === true ) ? 1 : - 1;
  21974. // save the index of the first center vertex
  21975. centerIndexStart = index;
  21976. // first we generate the center vertex data of the cap.
  21977. // because the geometry needs one set of uvs per face,
  21978. // we must generate a center vertex per face/segment
  21979. for ( x = 1; x <= radialSegments; x ++ ) {
  21980. // vertex
  21981. vertices.push( 0, halfHeight * sign, 0 );
  21982. // normal
  21983. normals.push( 0, sign, 0 );
  21984. // uv
  21985. uvs.push( 0.5, 0.5 );
  21986. // increase index
  21987. index ++;
  21988. }
  21989. // save the index of the last center vertex
  21990. centerIndexEnd = index;
  21991. // now we generate the surrounding vertices, normals and uvs
  21992. for ( x = 0; x <= radialSegments; x ++ ) {
  21993. var u = x / radialSegments;
  21994. var theta = u * thetaLength + thetaStart;
  21995. var cosTheta = Math.cos( theta );
  21996. var sinTheta = Math.sin( theta );
  21997. // vertex
  21998. vertex.x = radius * sinTheta;
  21999. vertex.y = halfHeight * sign;
  22000. vertex.z = radius * cosTheta;
  22001. vertices.push( vertex.x, vertex.y, vertex.z );
  22002. // normal
  22003. normals.push( 0, sign, 0 );
  22004. // uv
  22005. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22006. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22007. uvs.push( uv.x, uv.y );
  22008. // increase index
  22009. index ++;
  22010. }
  22011. // generate indices
  22012. for ( x = 0; x < radialSegments; x ++ ) {
  22013. var c = centerIndexStart + x;
  22014. var i = centerIndexEnd + x;
  22015. if ( top === true ) {
  22016. // face top
  22017. indices.push( i, i + 1, c );
  22018. } else {
  22019. // face bottom
  22020. indices.push( i + 1, i, c );
  22021. }
  22022. groupCount += 3;
  22023. }
  22024. // add a group to the geometry. this will ensure multi material support
  22025. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22026. // calculate new start value for groups
  22027. groupStart += groupCount;
  22028. }
  22029. }
  22030. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22031. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  22032. /**
  22033. * @author abelnation / http://github.com/abelnation
  22034. */
  22035. // ConeGeometry
  22036. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22037. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22038. this.type = 'ConeGeometry';
  22039. this.parameters = {
  22040. radius: radius,
  22041. height: height,
  22042. radialSegments: radialSegments,
  22043. heightSegments: heightSegments,
  22044. openEnded: openEnded,
  22045. thetaStart: thetaStart,
  22046. thetaLength: thetaLength
  22047. };
  22048. }
  22049. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  22050. ConeGeometry.prototype.constructor = ConeGeometry;
  22051. // ConeBufferGeometry
  22052. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22053. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22054. this.type = 'ConeBufferGeometry';
  22055. this.parameters = {
  22056. radius: radius,
  22057. height: height,
  22058. radialSegments: radialSegments,
  22059. heightSegments: heightSegments,
  22060. openEnded: openEnded,
  22061. thetaStart: thetaStart,
  22062. thetaLength: thetaLength
  22063. };
  22064. }
  22065. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  22066. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  22067. /**
  22068. * @author benaadams / https://twitter.com/ben_a_adams
  22069. * @author Mugen87 / https://github.com/Mugen87
  22070. * @author hughes
  22071. */
  22072. // CircleGeometry
  22073. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  22074. Geometry.call( this );
  22075. this.type = 'CircleGeometry';
  22076. this.parameters = {
  22077. radius: radius,
  22078. segments: segments,
  22079. thetaStart: thetaStart,
  22080. thetaLength: thetaLength
  22081. };
  22082. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  22083. this.mergeVertices();
  22084. }
  22085. CircleGeometry.prototype = Object.create( Geometry.prototype );
  22086. CircleGeometry.prototype.constructor = CircleGeometry;
  22087. // CircleBufferGeometry
  22088. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  22089. BufferGeometry.call( this );
  22090. this.type = 'CircleBufferGeometry';
  22091. this.parameters = {
  22092. radius: radius,
  22093. segments: segments,
  22094. thetaStart: thetaStart,
  22095. thetaLength: thetaLength
  22096. };
  22097. radius = radius || 1;
  22098. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  22099. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22100. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22101. // buffers
  22102. var indices = [];
  22103. var vertices = [];
  22104. var normals = [];
  22105. var uvs = [];
  22106. // helper variables
  22107. var i, s;
  22108. var vertex = new Vector3();
  22109. var uv = new Vector2();
  22110. // center point
  22111. vertices.push( 0, 0, 0 );
  22112. normals.push( 0, 0, 1 );
  22113. uvs.push( 0.5, 0.5 );
  22114. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22115. var segment = thetaStart + s / segments * thetaLength;
  22116. // vertex
  22117. vertex.x = radius * Math.cos( segment );
  22118. vertex.y = radius * Math.sin( segment );
  22119. vertices.push( vertex.x, vertex.y, vertex.z );
  22120. // normal
  22121. normals.push( 0, 0, 1 );
  22122. // uvs
  22123. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22124. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22125. uvs.push( uv.x, uv.y );
  22126. }
  22127. // indices
  22128. for ( i = 1; i <= segments; i ++ ) {
  22129. indices.push( i, i + 1, 0 );
  22130. }
  22131. // build geometry
  22132. this.setIndex( indices );
  22133. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22134. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22135. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22136. }
  22137. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22138. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  22139. var Geometries = /*#__PURE__*/Object.freeze({
  22140. WireframeGeometry: WireframeGeometry,
  22141. ParametricGeometry: ParametricGeometry,
  22142. ParametricBufferGeometry: ParametricBufferGeometry,
  22143. TetrahedronGeometry: TetrahedronGeometry,
  22144. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  22145. OctahedronGeometry: OctahedronGeometry,
  22146. OctahedronBufferGeometry: OctahedronBufferGeometry,
  22147. IcosahedronGeometry: IcosahedronGeometry,
  22148. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  22149. DodecahedronGeometry: DodecahedronGeometry,
  22150. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  22151. PolyhedronGeometry: PolyhedronGeometry,
  22152. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  22153. TubeGeometry: TubeGeometry,
  22154. TubeBufferGeometry: TubeBufferGeometry,
  22155. TorusKnotGeometry: TorusKnotGeometry,
  22156. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  22157. TorusGeometry: TorusGeometry,
  22158. TorusBufferGeometry: TorusBufferGeometry,
  22159. TextGeometry: TextGeometry,
  22160. TextBufferGeometry: TextBufferGeometry,
  22161. SphereGeometry: SphereGeometry,
  22162. SphereBufferGeometry: SphereBufferGeometry,
  22163. RingGeometry: RingGeometry,
  22164. RingBufferGeometry: RingBufferGeometry,
  22165. PlaneGeometry: PlaneGeometry,
  22166. PlaneBufferGeometry: PlaneBufferGeometry,
  22167. LatheGeometry: LatheGeometry,
  22168. LatheBufferGeometry: LatheBufferGeometry,
  22169. ShapeGeometry: ShapeGeometry,
  22170. ShapeBufferGeometry: ShapeBufferGeometry,
  22171. ExtrudeGeometry: ExtrudeGeometry,
  22172. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  22173. EdgesGeometry: EdgesGeometry,
  22174. ConeGeometry: ConeGeometry,
  22175. ConeBufferGeometry: ConeBufferGeometry,
  22176. CylinderGeometry: CylinderGeometry,
  22177. CylinderBufferGeometry: CylinderBufferGeometry,
  22178. CircleGeometry: CircleGeometry,
  22179. CircleBufferGeometry: CircleBufferGeometry,
  22180. BoxGeometry: BoxGeometry,
  22181. BoxBufferGeometry: BoxBufferGeometry
  22182. });
  22183. /**
  22184. * @author mrdoob / http://mrdoob.com/
  22185. *
  22186. * parameters = {
  22187. * color: <THREE.Color>
  22188. * }
  22189. */
  22190. function ShadowMaterial( parameters ) {
  22191. Material.call( this );
  22192. this.type = 'ShadowMaterial';
  22193. this.color = new Color( 0x000000 );
  22194. this.transparent = true;
  22195. this.setValues( parameters );
  22196. }
  22197. ShadowMaterial.prototype = Object.create( Material.prototype );
  22198. ShadowMaterial.prototype.constructor = ShadowMaterial;
  22199. ShadowMaterial.prototype.isShadowMaterial = true;
  22200. ShadowMaterial.prototype.copy = function ( source ) {
  22201. Material.prototype.copy.call( this, source );
  22202. this.color.copy( source.color );
  22203. return this;
  22204. };
  22205. /**
  22206. * @author mrdoob / http://mrdoob.com/
  22207. */
  22208. function RawShaderMaterial( parameters ) {
  22209. ShaderMaterial.call( this, parameters );
  22210. this.type = 'RawShaderMaterial';
  22211. }
  22212. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  22213. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  22214. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  22215. /**
  22216. * @author WestLangley / http://github.com/WestLangley
  22217. *
  22218. * parameters = {
  22219. * color: <hex>,
  22220. * roughness: <float>,
  22221. * metalness: <float>,
  22222. * opacity: <float>,
  22223. *
  22224. * map: new THREE.Texture( <Image> ),
  22225. *
  22226. * lightMap: new THREE.Texture( <Image> ),
  22227. * lightMapIntensity: <float>
  22228. *
  22229. * aoMap: new THREE.Texture( <Image> ),
  22230. * aoMapIntensity: <float>
  22231. *
  22232. * emissive: <hex>,
  22233. * emissiveIntensity: <float>
  22234. * emissiveMap: new THREE.Texture( <Image> ),
  22235. *
  22236. * bumpMap: new THREE.Texture( <Image> ),
  22237. * bumpScale: <float>,
  22238. *
  22239. * normalMap: new THREE.Texture( <Image> ),
  22240. * normalMapType: THREE.TangentSpaceNormalMap,
  22241. * normalScale: <Vector2>,
  22242. *
  22243. * displacementMap: new THREE.Texture( <Image> ),
  22244. * displacementScale: <float>,
  22245. * displacementBias: <float>,
  22246. *
  22247. * roughnessMap: new THREE.Texture( <Image> ),
  22248. *
  22249. * metalnessMap: new THREE.Texture( <Image> ),
  22250. *
  22251. * alphaMap: new THREE.Texture( <Image> ),
  22252. *
  22253. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22254. * envMapIntensity: <float>
  22255. *
  22256. * refractionRatio: <float>,
  22257. *
  22258. * wireframe: <boolean>,
  22259. * wireframeLinewidth: <float>,
  22260. *
  22261. * skinning: <bool>,
  22262. * morphTargets: <bool>,
  22263. * morphNormals: <bool>
  22264. * }
  22265. */
  22266. function MeshStandardMaterial( parameters ) {
  22267. Material.call( this );
  22268. this.defines = { 'STANDARD': '' };
  22269. this.type = 'MeshStandardMaterial';
  22270. this.color = new Color( 0xffffff ); // diffuse
  22271. this.roughness = 0.5;
  22272. this.metalness = 0.5;
  22273. this.map = null;
  22274. this.lightMap = null;
  22275. this.lightMapIntensity = 1.0;
  22276. this.aoMap = null;
  22277. this.aoMapIntensity = 1.0;
  22278. this.emissive = new Color( 0x000000 );
  22279. this.emissiveIntensity = 1.0;
  22280. this.emissiveMap = null;
  22281. this.bumpMap = null;
  22282. this.bumpScale = 1;
  22283. this.normalMap = null;
  22284. this.normalMapType = TangentSpaceNormalMap;
  22285. this.normalScale = new Vector2( 1, 1 );
  22286. this.displacementMap = null;
  22287. this.displacementScale = 1;
  22288. this.displacementBias = 0;
  22289. this.roughnessMap = null;
  22290. this.metalnessMap = null;
  22291. this.alphaMap = null;
  22292. this.envMap = null;
  22293. this.envMapIntensity = 1.0;
  22294. this.refractionRatio = 0.98;
  22295. this.wireframe = false;
  22296. this.wireframeLinewidth = 1;
  22297. this.wireframeLinecap = 'round';
  22298. this.wireframeLinejoin = 'round';
  22299. this.skinning = false;
  22300. this.morphTargets = false;
  22301. this.morphNormals = false;
  22302. this.setValues( parameters );
  22303. }
  22304. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  22305. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  22306. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  22307. MeshStandardMaterial.prototype.copy = function ( source ) {
  22308. Material.prototype.copy.call( this, source );
  22309. this.defines = { 'STANDARD': '' };
  22310. this.color.copy( source.color );
  22311. this.roughness = source.roughness;
  22312. this.metalness = source.metalness;
  22313. this.map = source.map;
  22314. this.lightMap = source.lightMap;
  22315. this.lightMapIntensity = source.lightMapIntensity;
  22316. this.aoMap = source.aoMap;
  22317. this.aoMapIntensity = source.aoMapIntensity;
  22318. this.emissive.copy( source.emissive );
  22319. this.emissiveMap = source.emissiveMap;
  22320. this.emissiveIntensity = source.emissiveIntensity;
  22321. this.bumpMap = source.bumpMap;
  22322. this.bumpScale = source.bumpScale;
  22323. this.normalMap = source.normalMap;
  22324. this.normalMapType = source.normalMapType;
  22325. this.normalScale.copy( source.normalScale );
  22326. this.displacementMap = source.displacementMap;
  22327. this.displacementScale = source.displacementScale;
  22328. this.displacementBias = source.displacementBias;
  22329. this.roughnessMap = source.roughnessMap;
  22330. this.metalnessMap = source.metalnessMap;
  22331. this.alphaMap = source.alphaMap;
  22332. this.envMap = source.envMap;
  22333. this.envMapIntensity = source.envMapIntensity;
  22334. this.refractionRatio = source.refractionRatio;
  22335. this.wireframe = source.wireframe;
  22336. this.wireframeLinewidth = source.wireframeLinewidth;
  22337. this.wireframeLinecap = source.wireframeLinecap;
  22338. this.wireframeLinejoin = source.wireframeLinejoin;
  22339. this.skinning = source.skinning;
  22340. this.morphTargets = source.morphTargets;
  22341. this.morphNormals = source.morphNormals;
  22342. return this;
  22343. };
  22344. /**
  22345. * @author WestLangley / http://github.com/WestLangley
  22346. *
  22347. * parameters = {
  22348. * reflectivity: <float>
  22349. * }
  22350. */
  22351. function MeshPhysicalMaterial( parameters ) {
  22352. MeshStandardMaterial.call( this );
  22353. this.defines = { 'PHYSICAL': '' };
  22354. this.type = 'MeshPhysicalMaterial';
  22355. this.reflectivity = 0.5; // maps to F0 = 0.04
  22356. this.clearCoat = 0.0;
  22357. this.clearCoatRoughness = 0.0;
  22358. this.setValues( parameters );
  22359. }
  22360. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  22361. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  22362. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  22363. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  22364. MeshStandardMaterial.prototype.copy.call( this, source );
  22365. this.defines = { 'PHYSICAL': '' };
  22366. this.reflectivity = source.reflectivity;
  22367. this.clearCoat = source.clearCoat;
  22368. this.clearCoatRoughness = source.clearCoatRoughness;
  22369. return this;
  22370. };
  22371. /**
  22372. * @author mrdoob / http://mrdoob.com/
  22373. * @author alteredq / http://alteredqualia.com/
  22374. *
  22375. * parameters = {
  22376. * color: <hex>,
  22377. * specular: <hex>,
  22378. * shininess: <float>,
  22379. * opacity: <float>,
  22380. *
  22381. * map: new THREE.Texture( <Image> ),
  22382. *
  22383. * lightMap: new THREE.Texture( <Image> ),
  22384. * lightMapIntensity: <float>
  22385. *
  22386. * aoMap: new THREE.Texture( <Image> ),
  22387. * aoMapIntensity: <float>
  22388. *
  22389. * emissive: <hex>,
  22390. * emissiveIntensity: <float>
  22391. * emissiveMap: new THREE.Texture( <Image> ),
  22392. *
  22393. * bumpMap: new THREE.Texture( <Image> ),
  22394. * bumpScale: <float>,
  22395. *
  22396. * normalMap: new THREE.Texture( <Image> ),
  22397. * normalMapType: THREE.TangentSpaceNormalMap,
  22398. * normalScale: <Vector2>,
  22399. *
  22400. * displacementMap: new THREE.Texture( <Image> ),
  22401. * displacementScale: <float>,
  22402. * displacementBias: <float>,
  22403. *
  22404. * specularMap: new THREE.Texture( <Image> ),
  22405. *
  22406. * alphaMap: new THREE.Texture( <Image> ),
  22407. *
  22408. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22409. * combine: THREE.Multiply,
  22410. * reflectivity: <float>,
  22411. * refractionRatio: <float>,
  22412. *
  22413. * wireframe: <boolean>,
  22414. * wireframeLinewidth: <float>,
  22415. *
  22416. * skinning: <bool>,
  22417. * morphTargets: <bool>,
  22418. * morphNormals: <bool>
  22419. * }
  22420. */
  22421. function MeshPhongMaterial( parameters ) {
  22422. Material.call( this );
  22423. this.type = 'MeshPhongMaterial';
  22424. this.color = new Color( 0xffffff ); // diffuse
  22425. this.specular = new Color( 0x111111 );
  22426. this.shininess = 30;
  22427. this.map = null;
  22428. this.lightMap = null;
  22429. this.lightMapIntensity = 1.0;
  22430. this.aoMap = null;
  22431. this.aoMapIntensity = 1.0;
  22432. this.emissive = new Color( 0x000000 );
  22433. this.emissiveIntensity = 1.0;
  22434. this.emissiveMap = null;
  22435. this.bumpMap = null;
  22436. this.bumpScale = 1;
  22437. this.normalMap = null;
  22438. this.normalMapType = TangentSpaceNormalMap;
  22439. this.normalScale = new Vector2( 1, 1 );
  22440. this.displacementMap = null;
  22441. this.displacementScale = 1;
  22442. this.displacementBias = 0;
  22443. this.specularMap = null;
  22444. this.alphaMap = null;
  22445. this.envMap = null;
  22446. this.combine = MultiplyOperation;
  22447. this.reflectivity = 1;
  22448. this.refractionRatio = 0.98;
  22449. this.wireframe = false;
  22450. this.wireframeLinewidth = 1;
  22451. this.wireframeLinecap = 'round';
  22452. this.wireframeLinejoin = 'round';
  22453. this.skinning = false;
  22454. this.morphTargets = false;
  22455. this.morphNormals = false;
  22456. this.setValues( parameters );
  22457. }
  22458. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  22459. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  22460. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  22461. MeshPhongMaterial.prototype.copy = function ( source ) {
  22462. Material.prototype.copy.call( this, source );
  22463. this.color.copy( source.color );
  22464. this.specular.copy( source.specular );
  22465. this.shininess = source.shininess;
  22466. this.map = source.map;
  22467. this.lightMap = source.lightMap;
  22468. this.lightMapIntensity = source.lightMapIntensity;
  22469. this.aoMap = source.aoMap;
  22470. this.aoMapIntensity = source.aoMapIntensity;
  22471. this.emissive.copy( source.emissive );
  22472. this.emissiveMap = source.emissiveMap;
  22473. this.emissiveIntensity = source.emissiveIntensity;
  22474. this.bumpMap = source.bumpMap;
  22475. this.bumpScale = source.bumpScale;
  22476. this.normalMap = source.normalMap;
  22477. this.normalMapType = source.normalMapType;
  22478. this.normalScale.copy( source.normalScale );
  22479. this.displacementMap = source.displacementMap;
  22480. this.displacementScale = source.displacementScale;
  22481. this.displacementBias = source.displacementBias;
  22482. this.specularMap = source.specularMap;
  22483. this.alphaMap = source.alphaMap;
  22484. this.envMap = source.envMap;
  22485. this.combine = source.combine;
  22486. this.reflectivity = source.reflectivity;
  22487. this.refractionRatio = source.refractionRatio;
  22488. this.wireframe = source.wireframe;
  22489. this.wireframeLinewidth = source.wireframeLinewidth;
  22490. this.wireframeLinecap = source.wireframeLinecap;
  22491. this.wireframeLinejoin = source.wireframeLinejoin;
  22492. this.skinning = source.skinning;
  22493. this.morphTargets = source.morphTargets;
  22494. this.morphNormals = source.morphNormals;
  22495. return this;
  22496. };
  22497. /**
  22498. * @author takahirox / http://github.com/takahirox
  22499. *
  22500. * parameters = {
  22501. * gradientMap: new THREE.Texture( <Image> )
  22502. * }
  22503. */
  22504. function MeshToonMaterial( parameters ) {
  22505. MeshPhongMaterial.call( this );
  22506. this.defines = { 'TOON': '' };
  22507. this.type = 'MeshToonMaterial';
  22508. this.gradientMap = null;
  22509. this.setValues( parameters );
  22510. }
  22511. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  22512. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  22513. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  22514. MeshToonMaterial.prototype.copy = function ( source ) {
  22515. MeshPhongMaterial.prototype.copy.call( this, source );
  22516. this.gradientMap = source.gradientMap;
  22517. return this;
  22518. };
  22519. /**
  22520. * @author mrdoob / http://mrdoob.com/
  22521. * @author WestLangley / http://github.com/WestLangley
  22522. *
  22523. * parameters = {
  22524. * opacity: <float>,
  22525. *
  22526. * bumpMap: new THREE.Texture( <Image> ),
  22527. * bumpScale: <float>,
  22528. *
  22529. * normalMap: new THREE.Texture( <Image> ),
  22530. * normalMapType: THREE.TangentSpaceNormalMap,
  22531. * normalScale: <Vector2>,
  22532. *
  22533. * displacementMap: new THREE.Texture( <Image> ),
  22534. * displacementScale: <float>,
  22535. * displacementBias: <float>,
  22536. *
  22537. * wireframe: <boolean>,
  22538. * wireframeLinewidth: <float>
  22539. *
  22540. * skinning: <bool>,
  22541. * morphTargets: <bool>,
  22542. * morphNormals: <bool>
  22543. * }
  22544. */
  22545. function MeshNormalMaterial( parameters ) {
  22546. Material.call( this );
  22547. this.type = 'MeshNormalMaterial';
  22548. this.bumpMap = null;
  22549. this.bumpScale = 1;
  22550. this.normalMap = null;
  22551. this.normalMapType = TangentSpaceNormalMap;
  22552. this.normalScale = new Vector2( 1, 1 );
  22553. this.displacementMap = null;
  22554. this.displacementScale = 1;
  22555. this.displacementBias = 0;
  22556. this.wireframe = false;
  22557. this.wireframeLinewidth = 1;
  22558. this.fog = false;
  22559. this.lights = false;
  22560. this.skinning = false;
  22561. this.morphTargets = false;
  22562. this.morphNormals = false;
  22563. this.setValues( parameters );
  22564. }
  22565. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  22566. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  22567. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  22568. MeshNormalMaterial.prototype.copy = function ( source ) {
  22569. Material.prototype.copy.call( this, source );
  22570. this.bumpMap = source.bumpMap;
  22571. this.bumpScale = source.bumpScale;
  22572. this.normalMap = source.normalMap;
  22573. this.normalMapType = source.normalMapType;
  22574. this.normalScale.copy( source.normalScale );
  22575. this.displacementMap = source.displacementMap;
  22576. this.displacementScale = source.displacementScale;
  22577. this.displacementBias = source.displacementBias;
  22578. this.wireframe = source.wireframe;
  22579. this.wireframeLinewidth = source.wireframeLinewidth;
  22580. this.skinning = source.skinning;
  22581. this.morphTargets = source.morphTargets;
  22582. this.morphNormals = source.morphNormals;
  22583. return this;
  22584. };
  22585. /**
  22586. * @author mrdoob / http://mrdoob.com/
  22587. * @author alteredq / http://alteredqualia.com/
  22588. *
  22589. * parameters = {
  22590. * color: <hex>,
  22591. * opacity: <float>,
  22592. *
  22593. * map: new THREE.Texture( <Image> ),
  22594. *
  22595. * lightMap: new THREE.Texture( <Image> ),
  22596. * lightMapIntensity: <float>
  22597. *
  22598. * aoMap: new THREE.Texture( <Image> ),
  22599. * aoMapIntensity: <float>
  22600. *
  22601. * emissive: <hex>,
  22602. * emissiveIntensity: <float>
  22603. * emissiveMap: new THREE.Texture( <Image> ),
  22604. *
  22605. * specularMap: new THREE.Texture( <Image> ),
  22606. *
  22607. * alphaMap: new THREE.Texture( <Image> ),
  22608. *
  22609. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22610. * combine: THREE.Multiply,
  22611. * reflectivity: <float>,
  22612. * refractionRatio: <float>,
  22613. *
  22614. * wireframe: <boolean>,
  22615. * wireframeLinewidth: <float>,
  22616. *
  22617. * skinning: <bool>,
  22618. * morphTargets: <bool>,
  22619. * morphNormals: <bool>
  22620. * }
  22621. */
  22622. function MeshLambertMaterial( parameters ) {
  22623. Material.call( this );
  22624. this.type = 'MeshLambertMaterial';
  22625. this.color = new Color( 0xffffff ); // diffuse
  22626. this.map = null;
  22627. this.lightMap = null;
  22628. this.lightMapIntensity = 1.0;
  22629. this.aoMap = null;
  22630. this.aoMapIntensity = 1.0;
  22631. this.emissive = new Color( 0x000000 );
  22632. this.emissiveIntensity = 1.0;
  22633. this.emissiveMap = null;
  22634. this.specularMap = null;
  22635. this.alphaMap = null;
  22636. this.envMap = null;
  22637. this.combine = MultiplyOperation;
  22638. this.reflectivity = 1;
  22639. this.refractionRatio = 0.98;
  22640. this.wireframe = false;
  22641. this.wireframeLinewidth = 1;
  22642. this.wireframeLinecap = 'round';
  22643. this.wireframeLinejoin = 'round';
  22644. this.skinning = false;
  22645. this.morphTargets = false;
  22646. this.morphNormals = false;
  22647. this.setValues( parameters );
  22648. }
  22649. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  22650. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  22651. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  22652. MeshLambertMaterial.prototype.copy = function ( source ) {
  22653. Material.prototype.copy.call( this, source );
  22654. this.color.copy( source.color );
  22655. this.map = source.map;
  22656. this.lightMap = source.lightMap;
  22657. this.lightMapIntensity = source.lightMapIntensity;
  22658. this.aoMap = source.aoMap;
  22659. this.aoMapIntensity = source.aoMapIntensity;
  22660. this.emissive.copy( source.emissive );
  22661. this.emissiveMap = source.emissiveMap;
  22662. this.emissiveIntensity = source.emissiveIntensity;
  22663. this.specularMap = source.specularMap;
  22664. this.alphaMap = source.alphaMap;
  22665. this.envMap = source.envMap;
  22666. this.combine = source.combine;
  22667. this.reflectivity = source.reflectivity;
  22668. this.refractionRatio = source.refractionRatio;
  22669. this.wireframe = source.wireframe;
  22670. this.wireframeLinewidth = source.wireframeLinewidth;
  22671. this.wireframeLinecap = source.wireframeLinecap;
  22672. this.wireframeLinejoin = source.wireframeLinejoin;
  22673. this.skinning = source.skinning;
  22674. this.morphTargets = source.morphTargets;
  22675. this.morphNormals = source.morphNormals;
  22676. return this;
  22677. };
  22678. /**
  22679. * @author alteredq / http://alteredqualia.com/
  22680. *
  22681. * parameters = {
  22682. * color: <hex>,
  22683. * opacity: <float>,
  22684. *
  22685. * linewidth: <float>,
  22686. *
  22687. * scale: <float>,
  22688. * dashSize: <float>,
  22689. * gapSize: <float>
  22690. * }
  22691. */
  22692. function LineDashedMaterial( parameters ) {
  22693. LineBasicMaterial.call( this );
  22694. this.type = 'LineDashedMaterial';
  22695. this.scale = 1;
  22696. this.dashSize = 3;
  22697. this.gapSize = 1;
  22698. this.setValues( parameters );
  22699. }
  22700. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  22701. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  22702. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  22703. LineDashedMaterial.prototype.copy = function ( source ) {
  22704. LineBasicMaterial.prototype.copy.call( this, source );
  22705. this.scale = source.scale;
  22706. this.dashSize = source.dashSize;
  22707. this.gapSize = source.gapSize;
  22708. return this;
  22709. };
  22710. var Materials = /*#__PURE__*/Object.freeze({
  22711. ShadowMaterial: ShadowMaterial,
  22712. SpriteMaterial: SpriteMaterial,
  22713. RawShaderMaterial: RawShaderMaterial,
  22714. ShaderMaterial: ShaderMaterial,
  22715. PointsMaterial: PointsMaterial,
  22716. MeshPhysicalMaterial: MeshPhysicalMaterial,
  22717. MeshStandardMaterial: MeshStandardMaterial,
  22718. MeshPhongMaterial: MeshPhongMaterial,
  22719. MeshToonMaterial: MeshToonMaterial,
  22720. MeshNormalMaterial: MeshNormalMaterial,
  22721. MeshLambertMaterial: MeshLambertMaterial,
  22722. MeshDepthMaterial: MeshDepthMaterial,
  22723. MeshDistanceMaterial: MeshDistanceMaterial,
  22724. MeshBasicMaterial: MeshBasicMaterial,
  22725. LineDashedMaterial: LineDashedMaterial,
  22726. LineBasicMaterial: LineBasicMaterial,
  22727. Material: Material
  22728. });
  22729. /**
  22730. * @author mrdoob / http://mrdoob.com/
  22731. */
  22732. var Cache = {
  22733. enabled: false,
  22734. files: {},
  22735. add: function ( key, file ) {
  22736. if ( this.enabled === false ) return;
  22737. // console.log( 'THREE.Cache', 'Adding key:', key );
  22738. this.files[ key ] = file;
  22739. },
  22740. get: function ( key ) {
  22741. if ( this.enabled === false ) return;
  22742. // console.log( 'THREE.Cache', 'Checking key:', key );
  22743. return this.files[ key ];
  22744. },
  22745. remove: function ( key ) {
  22746. delete this.files[ key ];
  22747. },
  22748. clear: function () {
  22749. this.files = {};
  22750. }
  22751. };
  22752. /**
  22753. * @author mrdoob / http://mrdoob.com/
  22754. */
  22755. function LoadingManager( onLoad, onProgress, onError ) {
  22756. var scope = this;
  22757. var isLoading = false;
  22758. var itemsLoaded = 0;
  22759. var itemsTotal = 0;
  22760. var urlModifier = undefined;
  22761. this.onStart = undefined;
  22762. this.onLoad = onLoad;
  22763. this.onProgress = onProgress;
  22764. this.onError = onError;
  22765. this.itemStart = function ( url ) {
  22766. itemsTotal ++;
  22767. if ( isLoading === false ) {
  22768. if ( scope.onStart !== undefined ) {
  22769. scope.onStart( url, itemsLoaded, itemsTotal );
  22770. }
  22771. }
  22772. isLoading = true;
  22773. };
  22774. this.itemEnd = function ( url ) {
  22775. itemsLoaded ++;
  22776. if ( scope.onProgress !== undefined ) {
  22777. scope.onProgress( url, itemsLoaded, itemsTotal );
  22778. }
  22779. if ( itemsLoaded === itemsTotal ) {
  22780. isLoading = false;
  22781. if ( scope.onLoad !== undefined ) {
  22782. scope.onLoad();
  22783. }
  22784. }
  22785. };
  22786. this.itemError = function ( url ) {
  22787. if ( scope.onError !== undefined ) {
  22788. scope.onError( url );
  22789. }
  22790. };
  22791. this.resolveURL = function ( url ) {
  22792. if ( urlModifier ) {
  22793. return urlModifier( url );
  22794. }
  22795. return url;
  22796. };
  22797. this.setURLModifier = function ( transform ) {
  22798. urlModifier = transform;
  22799. return this;
  22800. };
  22801. }
  22802. var DefaultLoadingManager = new LoadingManager();
  22803. /**
  22804. * @author mrdoob / http://mrdoob.com/
  22805. */
  22806. var loading = {};
  22807. function FileLoader( manager ) {
  22808. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22809. }
  22810. Object.assign( FileLoader.prototype, {
  22811. load: function ( url, onLoad, onProgress, onError ) {
  22812. if ( url === undefined ) url = '';
  22813. if ( this.path !== undefined ) url = this.path + url;
  22814. url = this.manager.resolveURL( url );
  22815. var scope = this;
  22816. var cached = Cache.get( url );
  22817. if ( cached !== undefined ) {
  22818. scope.manager.itemStart( url );
  22819. setTimeout( function () {
  22820. if ( onLoad ) onLoad( cached );
  22821. scope.manager.itemEnd( url );
  22822. }, 0 );
  22823. return cached;
  22824. }
  22825. // Check if request is duplicate
  22826. if ( loading[ url ] !== undefined ) {
  22827. loading[ url ].push( {
  22828. onLoad: onLoad,
  22829. onProgress: onProgress,
  22830. onError: onError
  22831. } );
  22832. return;
  22833. }
  22834. // Check for data: URI
  22835. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22836. var dataUriRegexResult = url.match( dataUriRegex );
  22837. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22838. if ( dataUriRegexResult ) {
  22839. var mimeType = dataUriRegexResult[ 1 ];
  22840. var isBase64 = !! dataUriRegexResult[ 2 ];
  22841. var data = dataUriRegexResult[ 3 ];
  22842. data = window.decodeURIComponent( data );
  22843. if ( isBase64 ) data = window.atob( data );
  22844. try {
  22845. var response;
  22846. var responseType = ( this.responseType || '' ).toLowerCase();
  22847. switch ( responseType ) {
  22848. case 'arraybuffer':
  22849. case 'blob':
  22850. var view = new Uint8Array( data.length );
  22851. for ( var i = 0; i < data.length; i ++ ) {
  22852. view[ i ] = data.charCodeAt( i );
  22853. }
  22854. if ( responseType === 'blob' ) {
  22855. response = new Blob( [ view.buffer ], { type: mimeType } );
  22856. } else {
  22857. response = view.buffer;
  22858. }
  22859. break;
  22860. case 'document':
  22861. var parser = new DOMParser();
  22862. response = parser.parseFromString( data, mimeType );
  22863. break;
  22864. case 'json':
  22865. response = JSON.parse( data );
  22866. break;
  22867. default: // 'text' or other
  22868. response = data;
  22869. break;
  22870. }
  22871. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22872. window.setTimeout( function () {
  22873. if ( onLoad ) onLoad( response );
  22874. scope.manager.itemEnd( url );
  22875. }, 0 );
  22876. } catch ( error ) {
  22877. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22878. window.setTimeout( function () {
  22879. if ( onError ) onError( error );
  22880. scope.manager.itemEnd( url );
  22881. scope.manager.itemError( url );
  22882. }, 0 );
  22883. }
  22884. } else {
  22885. // Initialise array for duplicate requests
  22886. loading[ url ] = [];
  22887. loading[ url ].push( {
  22888. onLoad: onLoad,
  22889. onProgress: onProgress,
  22890. onError: onError
  22891. } );
  22892. var request = new XMLHttpRequest();
  22893. request.open( 'GET', url, true );
  22894. request.addEventListener( 'load', function ( event ) {
  22895. var response = this.response;
  22896. Cache.add( url, response );
  22897. var callbacks = loading[ url ];
  22898. delete loading[ url ];
  22899. if ( this.status === 200 || this.status === 0 ) {
  22900. // Some browsers return HTTP Status 0 when using non-http protocol
  22901. // e.g. 'file://' or 'data://'. Handle as success.
  22902. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  22903. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22904. var callback = callbacks[ i ];
  22905. if ( callback.onLoad ) callback.onLoad( response );
  22906. }
  22907. scope.manager.itemEnd( url );
  22908. } else {
  22909. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22910. var callback = callbacks[ i ];
  22911. if ( callback.onError ) callback.onError( event );
  22912. }
  22913. scope.manager.itemEnd( url );
  22914. scope.manager.itemError( url );
  22915. }
  22916. }, false );
  22917. request.addEventListener( 'progress', function ( event ) {
  22918. var callbacks = loading[ url ];
  22919. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22920. var callback = callbacks[ i ];
  22921. if ( callback.onProgress ) callback.onProgress( event );
  22922. }
  22923. }, false );
  22924. request.addEventListener( 'error', function ( event ) {
  22925. var callbacks = loading[ url ];
  22926. delete loading[ url ];
  22927. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22928. var callback = callbacks[ i ];
  22929. if ( callback.onError ) callback.onError( event );
  22930. }
  22931. scope.manager.itemEnd( url );
  22932. scope.manager.itemError( url );
  22933. }, false );
  22934. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  22935. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  22936. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  22937. for ( var header in this.requestHeader ) {
  22938. request.setRequestHeader( header, this.requestHeader[ header ] );
  22939. }
  22940. request.send( null );
  22941. }
  22942. scope.manager.itemStart( url );
  22943. return request;
  22944. },
  22945. setPath: function ( value ) {
  22946. this.path = value;
  22947. return this;
  22948. },
  22949. setResponseType: function ( value ) {
  22950. this.responseType = value;
  22951. return this;
  22952. },
  22953. setWithCredentials: function ( value ) {
  22954. this.withCredentials = value;
  22955. return this;
  22956. },
  22957. setMimeType: function ( value ) {
  22958. this.mimeType = value;
  22959. return this;
  22960. },
  22961. setRequestHeader: function ( value ) {
  22962. this.requestHeader = value;
  22963. return this;
  22964. }
  22965. } );
  22966. /**
  22967. * @author mrdoob / http://mrdoob.com/
  22968. *
  22969. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22970. */
  22971. function CompressedTextureLoader( manager ) {
  22972. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22973. // override in sub classes
  22974. this._parser = null;
  22975. }
  22976. Object.assign( CompressedTextureLoader.prototype, {
  22977. load: function ( url, onLoad, onProgress, onError ) {
  22978. var scope = this;
  22979. var images = [];
  22980. var texture = new CompressedTexture();
  22981. texture.image = images;
  22982. var loader = new FileLoader( this.manager );
  22983. loader.setPath( this.path );
  22984. loader.setResponseType( 'arraybuffer' );
  22985. function loadTexture( i ) {
  22986. loader.load( url[ i ], function ( buffer ) {
  22987. var texDatas = scope._parser( buffer, true );
  22988. images[ i ] = {
  22989. width: texDatas.width,
  22990. height: texDatas.height,
  22991. format: texDatas.format,
  22992. mipmaps: texDatas.mipmaps
  22993. };
  22994. loaded += 1;
  22995. if ( loaded === 6 ) {
  22996. if ( texDatas.mipmapCount === 1 )
  22997. texture.minFilter = LinearFilter;
  22998. texture.format = texDatas.format;
  22999. texture.needsUpdate = true;
  23000. if ( onLoad ) onLoad( texture );
  23001. }
  23002. }, onProgress, onError );
  23003. }
  23004. if ( Array.isArray( url ) ) {
  23005. var loaded = 0;
  23006. for ( var i = 0, il = url.length; i < il; ++ i ) {
  23007. loadTexture( i );
  23008. }
  23009. } else {
  23010. // compressed cubemap texture stored in a single DDS file
  23011. loader.load( url, function ( buffer ) {
  23012. var texDatas = scope._parser( buffer, true );
  23013. if ( texDatas.isCubemap ) {
  23014. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23015. for ( var f = 0; f < faces; f ++ ) {
  23016. images[ f ] = { mipmaps: [] };
  23017. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  23018. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  23019. images[ f ].format = texDatas.format;
  23020. images[ f ].width = texDatas.width;
  23021. images[ f ].height = texDatas.height;
  23022. }
  23023. }
  23024. } else {
  23025. texture.image.width = texDatas.width;
  23026. texture.image.height = texDatas.height;
  23027. texture.mipmaps = texDatas.mipmaps;
  23028. }
  23029. if ( texDatas.mipmapCount === 1 ) {
  23030. texture.minFilter = LinearFilter;
  23031. }
  23032. texture.format = texDatas.format;
  23033. texture.needsUpdate = true;
  23034. if ( onLoad ) onLoad( texture );
  23035. }, onProgress, onError );
  23036. }
  23037. return texture;
  23038. },
  23039. setPath: function ( value ) {
  23040. this.path = value;
  23041. return this;
  23042. }
  23043. } );
  23044. /**
  23045. * @author Nikos M. / https://github.com/foo123/
  23046. *
  23047. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23048. */
  23049. function DataTextureLoader( manager ) {
  23050. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23051. // override in sub classes
  23052. this._parser = null;
  23053. }
  23054. Object.assign( DataTextureLoader.prototype, {
  23055. load: function ( url, onLoad, onProgress, onError ) {
  23056. var scope = this;
  23057. var texture = new DataTexture();
  23058. var loader = new FileLoader( this.manager );
  23059. loader.setResponseType( 'arraybuffer' );
  23060. loader.load( url, function ( buffer ) {
  23061. var texData = scope._parser( buffer );
  23062. if ( ! texData ) return;
  23063. if ( undefined !== texData.image ) {
  23064. texture.image = texData.image;
  23065. } else if ( undefined !== texData.data ) {
  23066. texture.image.width = texData.width;
  23067. texture.image.height = texData.height;
  23068. texture.image.data = texData.data;
  23069. }
  23070. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  23071. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  23072. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  23073. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  23074. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  23075. if ( undefined !== texData.format ) {
  23076. texture.format = texData.format;
  23077. }
  23078. if ( undefined !== texData.type ) {
  23079. texture.type = texData.type;
  23080. }
  23081. if ( undefined !== texData.mipmaps ) {
  23082. texture.mipmaps = texData.mipmaps;
  23083. }
  23084. if ( 1 === texData.mipmapCount ) {
  23085. texture.minFilter = LinearFilter;
  23086. }
  23087. texture.needsUpdate = true;
  23088. if ( onLoad ) onLoad( texture, texData );
  23089. }, onProgress, onError );
  23090. return texture;
  23091. }
  23092. } );
  23093. /**
  23094. * @author mrdoob / http://mrdoob.com/
  23095. */
  23096. function ImageLoader( manager ) {
  23097. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23098. }
  23099. Object.assign( ImageLoader.prototype, {
  23100. crossOrigin: 'anonymous',
  23101. load: function ( url, onLoad, onProgress, onError ) {
  23102. if ( url === undefined ) url = '';
  23103. if ( this.path !== undefined ) url = this.path + url;
  23104. url = this.manager.resolveURL( url );
  23105. var scope = this;
  23106. var cached = Cache.get( url );
  23107. if ( cached !== undefined ) {
  23108. scope.manager.itemStart( url );
  23109. setTimeout( function () {
  23110. if ( onLoad ) onLoad( cached );
  23111. scope.manager.itemEnd( url );
  23112. }, 0 );
  23113. return cached;
  23114. }
  23115. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  23116. function onImageLoad() {
  23117. image.removeEventListener( 'load', onImageLoad, false );
  23118. image.removeEventListener( 'error', onImageError, false );
  23119. Cache.add( url, this );
  23120. if ( onLoad ) onLoad( this );
  23121. scope.manager.itemEnd( url );
  23122. }
  23123. function onImageError( event ) {
  23124. image.removeEventListener( 'load', onImageLoad, false );
  23125. image.removeEventListener( 'error', onImageError, false );
  23126. if ( onError ) onError( event );
  23127. scope.manager.itemEnd( url );
  23128. scope.manager.itemError( url );
  23129. }
  23130. image.addEventListener( 'load', onImageLoad, false );
  23131. image.addEventListener( 'error', onImageError, false );
  23132. if ( url.substr( 0, 5 ) !== 'data:' ) {
  23133. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23134. }
  23135. scope.manager.itemStart( url );
  23136. image.src = url;
  23137. return image;
  23138. },
  23139. setCrossOrigin: function ( value ) {
  23140. this.crossOrigin = value;
  23141. return this;
  23142. },
  23143. setPath: function ( value ) {
  23144. this.path = value;
  23145. return this;
  23146. }
  23147. } );
  23148. /**
  23149. * @author mrdoob / http://mrdoob.com/
  23150. */
  23151. function CubeTextureLoader( manager ) {
  23152. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23153. }
  23154. Object.assign( CubeTextureLoader.prototype, {
  23155. crossOrigin: 'anonymous',
  23156. load: function ( urls, onLoad, onProgress, onError ) {
  23157. var texture = new CubeTexture();
  23158. var loader = new ImageLoader( this.manager );
  23159. loader.setCrossOrigin( this.crossOrigin );
  23160. loader.setPath( this.path );
  23161. var loaded = 0;
  23162. function loadTexture( i ) {
  23163. loader.load( urls[ i ], function ( image ) {
  23164. texture.images[ i ] = image;
  23165. loaded ++;
  23166. if ( loaded === 6 ) {
  23167. texture.needsUpdate = true;
  23168. if ( onLoad ) onLoad( texture );
  23169. }
  23170. }, undefined, onError );
  23171. }
  23172. for ( var i = 0; i < urls.length; ++ i ) {
  23173. loadTexture( i );
  23174. }
  23175. return texture;
  23176. },
  23177. setCrossOrigin: function ( value ) {
  23178. this.crossOrigin = value;
  23179. return this;
  23180. },
  23181. setPath: function ( value ) {
  23182. this.path = value;
  23183. return this;
  23184. }
  23185. } );
  23186. /**
  23187. * @author mrdoob / http://mrdoob.com/
  23188. */
  23189. function TextureLoader( manager ) {
  23190. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23191. }
  23192. Object.assign( TextureLoader.prototype, {
  23193. crossOrigin: 'anonymous',
  23194. load: function ( url, onLoad, onProgress, onError ) {
  23195. var texture = new Texture();
  23196. var loader = new ImageLoader( this.manager );
  23197. loader.setCrossOrigin( this.crossOrigin );
  23198. loader.setPath( this.path );
  23199. loader.load( url, function ( image ) {
  23200. texture.image = image;
  23201. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  23202. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  23203. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  23204. texture.needsUpdate = true;
  23205. if ( onLoad !== undefined ) {
  23206. onLoad( texture );
  23207. }
  23208. }, onProgress, onError );
  23209. return texture;
  23210. },
  23211. setCrossOrigin: function ( value ) {
  23212. this.crossOrigin = value;
  23213. return this;
  23214. },
  23215. setPath: function ( value ) {
  23216. this.path = value;
  23217. return this;
  23218. }
  23219. } );
  23220. /**
  23221. * @author zz85 / http://www.lab4games.net/zz85/blog
  23222. * Extensible curve object
  23223. *
  23224. * Some common of curve methods:
  23225. * .getPoint( t, optionalTarget ), .getTangent( t )
  23226. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  23227. * .getPoints(), .getSpacedPoints()
  23228. * .getLength()
  23229. * .updateArcLengths()
  23230. *
  23231. * This following curves inherit from THREE.Curve:
  23232. *
  23233. * -- 2D curves --
  23234. * THREE.ArcCurve
  23235. * THREE.CubicBezierCurve
  23236. * THREE.EllipseCurve
  23237. * THREE.LineCurve
  23238. * THREE.QuadraticBezierCurve
  23239. * THREE.SplineCurve
  23240. *
  23241. * -- 3D curves --
  23242. * THREE.CatmullRomCurve3
  23243. * THREE.CubicBezierCurve3
  23244. * THREE.LineCurve3
  23245. * THREE.QuadraticBezierCurve3
  23246. *
  23247. * A series of curves can be represented as a THREE.CurvePath.
  23248. *
  23249. **/
  23250. /**************************************************************
  23251. * Abstract Curve base class
  23252. **************************************************************/
  23253. function Curve() {
  23254. this.type = 'Curve';
  23255. this.arcLengthDivisions = 200;
  23256. }
  23257. Object.assign( Curve.prototype, {
  23258. // Virtual base class method to overwrite and implement in subclasses
  23259. // - t [0 .. 1]
  23260. getPoint: function ( /* t, optionalTarget */ ) {
  23261. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  23262. return null;
  23263. },
  23264. // Get point at relative position in curve according to arc length
  23265. // - u [0 .. 1]
  23266. getPointAt: function ( u, optionalTarget ) {
  23267. var t = this.getUtoTmapping( u );
  23268. return this.getPoint( t, optionalTarget );
  23269. },
  23270. // Get sequence of points using getPoint( t )
  23271. getPoints: function ( divisions ) {
  23272. if ( divisions === undefined ) divisions = 5;
  23273. var points = [];
  23274. for ( var d = 0; d <= divisions; d ++ ) {
  23275. points.push( this.getPoint( d / divisions ) );
  23276. }
  23277. return points;
  23278. },
  23279. // Get sequence of points using getPointAt( u )
  23280. getSpacedPoints: function ( divisions ) {
  23281. if ( divisions === undefined ) divisions = 5;
  23282. var points = [];
  23283. for ( var d = 0; d <= divisions; d ++ ) {
  23284. points.push( this.getPointAt( d / divisions ) );
  23285. }
  23286. return points;
  23287. },
  23288. // Get total curve arc length
  23289. getLength: function () {
  23290. var lengths = this.getLengths();
  23291. return lengths[ lengths.length - 1 ];
  23292. },
  23293. // Get list of cumulative segment lengths
  23294. getLengths: function ( divisions ) {
  23295. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  23296. if ( this.cacheArcLengths &&
  23297. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23298. ! this.needsUpdate ) {
  23299. return this.cacheArcLengths;
  23300. }
  23301. this.needsUpdate = false;
  23302. var cache = [];
  23303. var current, last = this.getPoint( 0 );
  23304. var p, sum = 0;
  23305. cache.push( 0 );
  23306. for ( p = 1; p <= divisions; p ++ ) {
  23307. current = this.getPoint( p / divisions );
  23308. sum += current.distanceTo( last );
  23309. cache.push( sum );
  23310. last = current;
  23311. }
  23312. this.cacheArcLengths = cache;
  23313. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23314. },
  23315. updateArcLengths: function () {
  23316. this.needsUpdate = true;
  23317. this.getLengths();
  23318. },
  23319. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  23320. getUtoTmapping: function ( u, distance ) {
  23321. var arcLengths = this.getLengths();
  23322. var i = 0, il = arcLengths.length;
  23323. var targetArcLength; // The targeted u distance value to get
  23324. if ( distance ) {
  23325. targetArcLength = distance;
  23326. } else {
  23327. targetArcLength = u * arcLengths[ il - 1 ];
  23328. }
  23329. // binary search for the index with largest value smaller than target u distance
  23330. var low = 0, high = il - 1, comparison;
  23331. while ( low <= high ) {
  23332. 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
  23333. comparison = arcLengths[ i ] - targetArcLength;
  23334. if ( comparison < 0 ) {
  23335. low = i + 1;
  23336. } else if ( comparison > 0 ) {
  23337. high = i - 1;
  23338. } else {
  23339. high = i;
  23340. break;
  23341. // DONE
  23342. }
  23343. }
  23344. i = high;
  23345. if ( arcLengths[ i ] === targetArcLength ) {
  23346. return i / ( il - 1 );
  23347. }
  23348. // we could get finer grain at lengths, or use simple interpolation between two points
  23349. var lengthBefore = arcLengths[ i ];
  23350. var lengthAfter = arcLengths[ i + 1 ];
  23351. var segmentLength = lengthAfter - lengthBefore;
  23352. // determine where we are between the 'before' and 'after' points
  23353. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23354. // add that fractional amount to t
  23355. var t = ( i + segmentFraction ) / ( il - 1 );
  23356. return t;
  23357. },
  23358. // Returns a unit vector tangent at t
  23359. // In case any sub curve does not implement its tangent derivation,
  23360. // 2 points a small delta apart will be used to find its gradient
  23361. // which seems to give a reasonable approximation
  23362. getTangent: function ( t ) {
  23363. var delta = 0.0001;
  23364. var t1 = t - delta;
  23365. var t2 = t + delta;
  23366. // Capping in case of danger
  23367. if ( t1 < 0 ) t1 = 0;
  23368. if ( t2 > 1 ) t2 = 1;
  23369. var pt1 = this.getPoint( t1 );
  23370. var pt2 = this.getPoint( t2 );
  23371. var vec = pt2.clone().sub( pt1 );
  23372. return vec.normalize();
  23373. },
  23374. getTangentAt: function ( u ) {
  23375. var t = this.getUtoTmapping( u );
  23376. return this.getTangent( t );
  23377. },
  23378. computeFrenetFrames: function ( segments, closed ) {
  23379. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23380. var normal = new Vector3();
  23381. var tangents = [];
  23382. var normals = [];
  23383. var binormals = [];
  23384. var vec = new Vector3();
  23385. var mat = new Matrix4();
  23386. var i, u, theta;
  23387. // compute the tangent vectors for each segment on the curve
  23388. for ( i = 0; i <= segments; i ++ ) {
  23389. u = i / segments;
  23390. tangents[ i ] = this.getTangentAt( u );
  23391. tangents[ i ].normalize();
  23392. }
  23393. // select an initial normal vector perpendicular to the first tangent vector,
  23394. // and in the direction of the minimum tangent xyz component
  23395. normals[ 0 ] = new Vector3();
  23396. binormals[ 0 ] = new Vector3();
  23397. var min = Number.MAX_VALUE;
  23398. var tx = Math.abs( tangents[ 0 ].x );
  23399. var ty = Math.abs( tangents[ 0 ].y );
  23400. var tz = Math.abs( tangents[ 0 ].z );
  23401. if ( tx <= min ) {
  23402. min = tx;
  23403. normal.set( 1, 0, 0 );
  23404. }
  23405. if ( ty <= min ) {
  23406. min = ty;
  23407. normal.set( 0, 1, 0 );
  23408. }
  23409. if ( tz <= min ) {
  23410. normal.set( 0, 0, 1 );
  23411. }
  23412. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23413. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23414. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23415. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23416. for ( i = 1; i <= segments; i ++ ) {
  23417. normals[ i ] = normals[ i - 1 ].clone();
  23418. binormals[ i ] = binormals[ i - 1 ].clone();
  23419. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23420. if ( vec.length() > Number.EPSILON ) {
  23421. vec.normalize();
  23422. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  23423. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23424. }
  23425. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23426. }
  23427. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23428. if ( closed === true ) {
  23429. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  23430. theta /= segments;
  23431. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23432. theta = - theta;
  23433. }
  23434. for ( i = 1; i <= segments; i ++ ) {
  23435. // twist a little...
  23436. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23437. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23438. }
  23439. }
  23440. return {
  23441. tangents: tangents,
  23442. normals: normals,
  23443. binormals: binormals
  23444. };
  23445. },
  23446. clone: function () {
  23447. return new this.constructor().copy( this );
  23448. },
  23449. copy: function ( source ) {
  23450. this.arcLengthDivisions = source.arcLengthDivisions;
  23451. return this;
  23452. },
  23453. toJSON: function () {
  23454. var data = {
  23455. metadata: {
  23456. version: 4.5,
  23457. type: 'Curve',
  23458. generator: 'Curve.toJSON'
  23459. }
  23460. };
  23461. data.arcLengthDivisions = this.arcLengthDivisions;
  23462. data.type = this.type;
  23463. return data;
  23464. },
  23465. fromJSON: function ( json ) {
  23466. this.arcLengthDivisions = json.arcLengthDivisions;
  23467. return this;
  23468. }
  23469. } );
  23470. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23471. Curve.call( this );
  23472. this.type = 'EllipseCurve';
  23473. this.aX = aX || 0;
  23474. this.aY = aY || 0;
  23475. this.xRadius = xRadius || 1;
  23476. this.yRadius = yRadius || 1;
  23477. this.aStartAngle = aStartAngle || 0;
  23478. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23479. this.aClockwise = aClockwise || false;
  23480. this.aRotation = aRotation || 0;
  23481. }
  23482. EllipseCurve.prototype = Object.create( Curve.prototype );
  23483. EllipseCurve.prototype.constructor = EllipseCurve;
  23484. EllipseCurve.prototype.isEllipseCurve = true;
  23485. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23486. var point = optionalTarget || new Vector2();
  23487. var twoPi = Math.PI * 2;
  23488. var deltaAngle = this.aEndAngle - this.aStartAngle;
  23489. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23490. // ensures that deltaAngle is 0 .. 2 PI
  23491. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23492. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23493. if ( deltaAngle < Number.EPSILON ) {
  23494. if ( samePoints ) {
  23495. deltaAngle = 0;
  23496. } else {
  23497. deltaAngle = twoPi;
  23498. }
  23499. }
  23500. if ( this.aClockwise === true && ! samePoints ) {
  23501. if ( deltaAngle === twoPi ) {
  23502. deltaAngle = - twoPi;
  23503. } else {
  23504. deltaAngle = deltaAngle - twoPi;
  23505. }
  23506. }
  23507. var angle = this.aStartAngle + t * deltaAngle;
  23508. var x = this.aX + this.xRadius * Math.cos( angle );
  23509. var y = this.aY + this.yRadius * Math.sin( angle );
  23510. if ( this.aRotation !== 0 ) {
  23511. var cos = Math.cos( this.aRotation );
  23512. var sin = Math.sin( this.aRotation );
  23513. var tx = x - this.aX;
  23514. var ty = y - this.aY;
  23515. // Rotate the point about the center of the ellipse.
  23516. x = tx * cos - ty * sin + this.aX;
  23517. y = tx * sin + ty * cos + this.aY;
  23518. }
  23519. return point.set( x, y );
  23520. };
  23521. EllipseCurve.prototype.copy = function ( source ) {
  23522. Curve.prototype.copy.call( this, source );
  23523. this.aX = source.aX;
  23524. this.aY = source.aY;
  23525. this.xRadius = source.xRadius;
  23526. this.yRadius = source.yRadius;
  23527. this.aStartAngle = source.aStartAngle;
  23528. this.aEndAngle = source.aEndAngle;
  23529. this.aClockwise = source.aClockwise;
  23530. this.aRotation = source.aRotation;
  23531. return this;
  23532. };
  23533. EllipseCurve.prototype.toJSON = function () {
  23534. var data = Curve.prototype.toJSON.call( this );
  23535. data.aX = this.aX;
  23536. data.aY = this.aY;
  23537. data.xRadius = this.xRadius;
  23538. data.yRadius = this.yRadius;
  23539. data.aStartAngle = this.aStartAngle;
  23540. data.aEndAngle = this.aEndAngle;
  23541. data.aClockwise = this.aClockwise;
  23542. data.aRotation = this.aRotation;
  23543. return data;
  23544. };
  23545. EllipseCurve.prototype.fromJSON = function ( json ) {
  23546. Curve.prototype.fromJSON.call( this, json );
  23547. this.aX = json.aX;
  23548. this.aY = json.aY;
  23549. this.xRadius = json.xRadius;
  23550. this.yRadius = json.yRadius;
  23551. this.aStartAngle = json.aStartAngle;
  23552. this.aEndAngle = json.aEndAngle;
  23553. this.aClockwise = json.aClockwise;
  23554. this.aRotation = json.aRotation;
  23555. return this;
  23556. };
  23557. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23558. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23559. this.type = 'ArcCurve';
  23560. }
  23561. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  23562. ArcCurve.prototype.constructor = ArcCurve;
  23563. ArcCurve.prototype.isArcCurve = true;
  23564. /**
  23565. * @author zz85 https://github.com/zz85
  23566. *
  23567. * Centripetal CatmullRom Curve - which is useful for avoiding
  23568. * cusps and self-intersections in non-uniform catmull rom curves.
  23569. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23570. *
  23571. * curve.type accepts centripetal(default), chordal and catmullrom
  23572. * curve.tension is used for catmullrom which defaults to 0.5
  23573. */
  23574. /*
  23575. Based on an optimized c++ solution in
  23576. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23577. - http://ideone.com/NoEbVM
  23578. This CubicPoly class could be used for reusing some variables and calculations,
  23579. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23580. which can be placed in CurveUtils.
  23581. */
  23582. function CubicPoly() {
  23583. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23584. /*
  23585. * Compute coefficients for a cubic polynomial
  23586. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23587. * such that
  23588. * p(0) = x0, p(1) = x1
  23589. * and
  23590. * p'(0) = t0, p'(1) = t1.
  23591. */
  23592. function init( x0, x1, t0, t1 ) {
  23593. c0 = x0;
  23594. c1 = t0;
  23595. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  23596. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23597. }
  23598. return {
  23599. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23600. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23601. },
  23602. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23603. // compute tangents when parameterized in [t1,t2]
  23604. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23605. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23606. // rescale tangents for parametrization in [0,1]
  23607. t1 *= dt1;
  23608. t2 *= dt1;
  23609. init( x1, x2, t1, t2 );
  23610. },
  23611. calc: function ( t ) {
  23612. var t2 = t * t;
  23613. var t3 = t2 * t;
  23614. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23615. }
  23616. };
  23617. }
  23618. //
  23619. var tmp = new Vector3();
  23620. var px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  23621. function CatmullRomCurve3( points, closed, curveType, tension ) {
  23622. Curve.call( this );
  23623. this.type = 'CatmullRomCurve3';
  23624. this.points = points || [];
  23625. this.closed = closed || false;
  23626. this.curveType = curveType || 'centripetal';
  23627. this.tension = tension || 0.5;
  23628. }
  23629. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  23630. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23631. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23632. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23633. var point = optionalTarget || new Vector3();
  23634. var points = this.points;
  23635. var l = points.length;
  23636. var p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23637. var intPoint = Math.floor( p );
  23638. var weight = p - intPoint;
  23639. if ( this.closed ) {
  23640. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23641. } else if ( weight === 0 && intPoint === l - 1 ) {
  23642. intPoint = l - 2;
  23643. weight = 1;
  23644. }
  23645. var p0, p1, p2, p3; // 4 points
  23646. if ( this.closed || intPoint > 0 ) {
  23647. p0 = points[ ( intPoint - 1 ) % l ];
  23648. } else {
  23649. // extrapolate first point
  23650. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23651. p0 = tmp;
  23652. }
  23653. p1 = points[ intPoint % l ];
  23654. p2 = points[ ( intPoint + 1 ) % l ];
  23655. if ( this.closed || intPoint + 2 < l ) {
  23656. p3 = points[ ( intPoint + 2 ) % l ];
  23657. } else {
  23658. // extrapolate last point
  23659. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23660. p3 = tmp;
  23661. }
  23662. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23663. // init Centripetal / Chordal Catmull-Rom
  23664. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23665. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23666. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23667. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23668. // safety check for repeated points
  23669. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23670. if ( dt0 < 1e-4 ) dt0 = dt1;
  23671. if ( dt2 < 1e-4 ) dt2 = dt1;
  23672. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23673. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23674. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23675. } else if ( this.curveType === 'catmullrom' ) {
  23676. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23677. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23678. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23679. }
  23680. point.set(
  23681. px.calc( weight ),
  23682. py.calc( weight ),
  23683. pz.calc( weight )
  23684. );
  23685. return point;
  23686. };
  23687. CatmullRomCurve3.prototype.copy = function ( source ) {
  23688. Curve.prototype.copy.call( this, source );
  23689. this.points = [];
  23690. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  23691. var point = source.points[ i ];
  23692. this.points.push( point.clone() );
  23693. }
  23694. this.closed = source.closed;
  23695. this.curveType = source.curveType;
  23696. this.tension = source.tension;
  23697. return this;
  23698. };
  23699. CatmullRomCurve3.prototype.toJSON = function () {
  23700. var data = Curve.prototype.toJSON.call( this );
  23701. data.points = [];
  23702. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  23703. var point = this.points[ i ];
  23704. data.points.push( point.toArray() );
  23705. }
  23706. data.closed = this.closed;
  23707. data.curveType = this.curveType;
  23708. data.tension = this.tension;
  23709. return data;
  23710. };
  23711. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  23712. Curve.prototype.fromJSON.call( this, json );
  23713. this.points = [];
  23714. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  23715. var point = json.points[ i ];
  23716. this.points.push( new Vector3().fromArray( point ) );
  23717. }
  23718. this.closed = json.closed;
  23719. this.curveType = json.curveType;
  23720. this.tension = json.tension;
  23721. return this;
  23722. };
  23723. /**
  23724. * @author zz85 / http://www.lab4games.net/zz85/blog
  23725. *
  23726. * Bezier Curves formulas obtained from
  23727. * http://en.wikipedia.org/wiki/Bézier_curve
  23728. */
  23729. function CatmullRom( t, p0, p1, p2, p3 ) {
  23730. var v0 = ( p2 - p0 ) * 0.5;
  23731. var v1 = ( p3 - p1 ) * 0.5;
  23732. var t2 = t * t;
  23733. var t3 = t * t2;
  23734. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23735. }
  23736. //
  23737. function QuadraticBezierP0( t, p ) {
  23738. var k = 1 - t;
  23739. return k * k * p;
  23740. }
  23741. function QuadraticBezierP1( t, p ) {
  23742. return 2 * ( 1 - t ) * t * p;
  23743. }
  23744. function QuadraticBezierP2( t, p ) {
  23745. return t * t * p;
  23746. }
  23747. function QuadraticBezier( t, p0, p1, p2 ) {
  23748. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23749. QuadraticBezierP2( t, p2 );
  23750. }
  23751. //
  23752. function CubicBezierP0( t, p ) {
  23753. var k = 1 - t;
  23754. return k * k * k * p;
  23755. }
  23756. function CubicBezierP1( t, p ) {
  23757. var k = 1 - t;
  23758. return 3 * k * k * t * p;
  23759. }
  23760. function CubicBezierP2( t, p ) {
  23761. return 3 * ( 1 - t ) * t * t * p;
  23762. }
  23763. function CubicBezierP3( t, p ) {
  23764. return t * t * t * p;
  23765. }
  23766. function CubicBezier( t, p0, p1, p2, p3 ) {
  23767. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23768. CubicBezierP3( t, p3 );
  23769. }
  23770. function CubicBezierCurve( v0, v1, v2, v3 ) {
  23771. Curve.call( this );
  23772. this.type = 'CubicBezierCurve';
  23773. this.v0 = v0 || new Vector2();
  23774. this.v1 = v1 || new Vector2();
  23775. this.v2 = v2 || new Vector2();
  23776. this.v3 = v3 || new Vector2();
  23777. }
  23778. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  23779. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23780. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23781. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23782. var point = optionalTarget || new Vector2();
  23783. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23784. point.set(
  23785. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23786. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23787. );
  23788. return point;
  23789. };
  23790. CubicBezierCurve.prototype.copy = function ( source ) {
  23791. Curve.prototype.copy.call( this, source );
  23792. this.v0.copy( source.v0 );
  23793. this.v1.copy( source.v1 );
  23794. this.v2.copy( source.v2 );
  23795. this.v3.copy( source.v3 );
  23796. return this;
  23797. };
  23798. CubicBezierCurve.prototype.toJSON = function () {
  23799. var data = Curve.prototype.toJSON.call( this );
  23800. data.v0 = this.v0.toArray();
  23801. data.v1 = this.v1.toArray();
  23802. data.v2 = this.v2.toArray();
  23803. data.v3 = this.v3.toArray();
  23804. return data;
  23805. };
  23806. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  23807. Curve.prototype.fromJSON.call( this, json );
  23808. this.v0.fromArray( json.v0 );
  23809. this.v1.fromArray( json.v1 );
  23810. this.v2.fromArray( json.v2 );
  23811. this.v3.fromArray( json.v3 );
  23812. return this;
  23813. };
  23814. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  23815. Curve.call( this );
  23816. this.type = 'CubicBezierCurve3';
  23817. this.v0 = v0 || new Vector3();
  23818. this.v1 = v1 || new Vector3();
  23819. this.v2 = v2 || new Vector3();
  23820. this.v3 = v3 || new Vector3();
  23821. }
  23822. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  23823. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23824. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23825. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23826. var point = optionalTarget || new Vector3();
  23827. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23828. point.set(
  23829. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23830. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23831. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23832. );
  23833. return point;
  23834. };
  23835. CubicBezierCurve3.prototype.copy = function ( source ) {
  23836. Curve.prototype.copy.call( this, source );
  23837. this.v0.copy( source.v0 );
  23838. this.v1.copy( source.v1 );
  23839. this.v2.copy( source.v2 );
  23840. this.v3.copy( source.v3 );
  23841. return this;
  23842. };
  23843. CubicBezierCurve3.prototype.toJSON = function () {
  23844. var data = Curve.prototype.toJSON.call( this );
  23845. data.v0 = this.v0.toArray();
  23846. data.v1 = this.v1.toArray();
  23847. data.v2 = this.v2.toArray();
  23848. data.v3 = this.v3.toArray();
  23849. return data;
  23850. };
  23851. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  23852. Curve.prototype.fromJSON.call( this, json );
  23853. this.v0.fromArray( json.v0 );
  23854. this.v1.fromArray( json.v1 );
  23855. this.v2.fromArray( json.v2 );
  23856. this.v3.fromArray( json.v3 );
  23857. return this;
  23858. };
  23859. function LineCurve( v1, v2 ) {
  23860. Curve.call( this );
  23861. this.type = 'LineCurve';
  23862. this.v1 = v1 || new Vector2();
  23863. this.v2 = v2 || new Vector2();
  23864. }
  23865. LineCurve.prototype = Object.create( Curve.prototype );
  23866. LineCurve.prototype.constructor = LineCurve;
  23867. LineCurve.prototype.isLineCurve = true;
  23868. LineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23869. var point = optionalTarget || new Vector2();
  23870. if ( t === 1 ) {
  23871. point.copy( this.v2 );
  23872. } else {
  23873. point.copy( this.v2 ).sub( this.v1 );
  23874. point.multiplyScalar( t ).add( this.v1 );
  23875. }
  23876. return point;
  23877. };
  23878. // Line curve is linear, so we can overwrite default getPointAt
  23879. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  23880. return this.getPoint( u, optionalTarget );
  23881. };
  23882. LineCurve.prototype.getTangent = function ( /* t */ ) {
  23883. var tangent = this.v2.clone().sub( this.v1 );
  23884. return tangent.normalize();
  23885. };
  23886. LineCurve.prototype.copy = function ( source ) {
  23887. Curve.prototype.copy.call( this, source );
  23888. this.v1.copy( source.v1 );
  23889. this.v2.copy( source.v2 );
  23890. return this;
  23891. };
  23892. LineCurve.prototype.toJSON = function () {
  23893. var data = Curve.prototype.toJSON.call( this );
  23894. data.v1 = this.v1.toArray();
  23895. data.v2 = this.v2.toArray();
  23896. return data;
  23897. };
  23898. LineCurve.prototype.fromJSON = function ( json ) {
  23899. Curve.prototype.fromJSON.call( this, json );
  23900. this.v1.fromArray( json.v1 );
  23901. this.v2.fromArray( json.v2 );
  23902. return this;
  23903. };
  23904. function LineCurve3( v1, v2 ) {
  23905. Curve.call( this );
  23906. this.type = 'LineCurve3';
  23907. this.v1 = v1 || new Vector3();
  23908. this.v2 = v2 || new Vector3();
  23909. }
  23910. LineCurve3.prototype = Object.create( Curve.prototype );
  23911. LineCurve3.prototype.constructor = LineCurve3;
  23912. LineCurve3.prototype.isLineCurve3 = true;
  23913. LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23914. var point = optionalTarget || new Vector3();
  23915. if ( t === 1 ) {
  23916. point.copy( this.v2 );
  23917. } else {
  23918. point.copy( this.v2 ).sub( this.v1 );
  23919. point.multiplyScalar( t ).add( this.v1 );
  23920. }
  23921. return point;
  23922. };
  23923. // Line curve is linear, so we can overwrite default getPointAt
  23924. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  23925. return this.getPoint( u, optionalTarget );
  23926. };
  23927. LineCurve3.prototype.copy = function ( source ) {
  23928. Curve.prototype.copy.call( this, source );
  23929. this.v1.copy( source.v1 );
  23930. this.v2.copy( source.v2 );
  23931. return this;
  23932. };
  23933. LineCurve3.prototype.toJSON = function () {
  23934. var data = Curve.prototype.toJSON.call( this );
  23935. data.v1 = this.v1.toArray();
  23936. data.v2 = this.v2.toArray();
  23937. return data;
  23938. };
  23939. LineCurve3.prototype.fromJSON = function ( json ) {
  23940. Curve.prototype.fromJSON.call( this, json );
  23941. this.v1.fromArray( json.v1 );
  23942. this.v2.fromArray( json.v2 );
  23943. return this;
  23944. };
  23945. function QuadraticBezierCurve( v0, v1, v2 ) {
  23946. Curve.call( this );
  23947. this.type = 'QuadraticBezierCurve';
  23948. this.v0 = v0 || new Vector2();
  23949. this.v1 = v1 || new Vector2();
  23950. this.v2 = v2 || new Vector2();
  23951. }
  23952. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  23953. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23954. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23955. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23956. var point = optionalTarget || new Vector2();
  23957. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23958. point.set(
  23959. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23960. QuadraticBezier( t, v0.y, v1.y, v2.y )
  23961. );
  23962. return point;
  23963. };
  23964. QuadraticBezierCurve.prototype.copy = function ( source ) {
  23965. Curve.prototype.copy.call( this, source );
  23966. this.v0.copy( source.v0 );
  23967. this.v1.copy( source.v1 );
  23968. this.v2.copy( source.v2 );
  23969. return this;
  23970. };
  23971. QuadraticBezierCurve.prototype.toJSON = function () {
  23972. var data = Curve.prototype.toJSON.call( this );
  23973. data.v0 = this.v0.toArray();
  23974. data.v1 = this.v1.toArray();
  23975. data.v2 = this.v2.toArray();
  23976. return data;
  23977. };
  23978. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  23979. Curve.prototype.fromJSON.call( this, json );
  23980. this.v0.fromArray( json.v0 );
  23981. this.v1.fromArray( json.v1 );
  23982. this.v2.fromArray( json.v2 );
  23983. return this;
  23984. };
  23985. function QuadraticBezierCurve3( v0, v1, v2 ) {
  23986. Curve.call( this );
  23987. this.type = 'QuadraticBezierCurve3';
  23988. this.v0 = v0 || new Vector3();
  23989. this.v1 = v1 || new Vector3();
  23990. this.v2 = v2 || new Vector3();
  23991. }
  23992. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  23993. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23994. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23995. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23996. var point = optionalTarget || new Vector3();
  23997. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23998. point.set(
  23999. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24000. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24001. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24002. );
  24003. return point;
  24004. };
  24005. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  24006. Curve.prototype.copy.call( this, source );
  24007. this.v0.copy( source.v0 );
  24008. this.v1.copy( source.v1 );
  24009. this.v2.copy( source.v2 );
  24010. return this;
  24011. };
  24012. QuadraticBezierCurve3.prototype.toJSON = function () {
  24013. var data = Curve.prototype.toJSON.call( this );
  24014. data.v0 = this.v0.toArray();
  24015. data.v1 = this.v1.toArray();
  24016. data.v2 = this.v2.toArray();
  24017. return data;
  24018. };
  24019. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  24020. Curve.prototype.fromJSON.call( this, json );
  24021. this.v0.fromArray( json.v0 );
  24022. this.v1.fromArray( json.v1 );
  24023. this.v2.fromArray( json.v2 );
  24024. return this;
  24025. };
  24026. function SplineCurve( points /* array of Vector2 */ ) {
  24027. Curve.call( this );
  24028. this.type = 'SplineCurve';
  24029. this.points = points || [];
  24030. }
  24031. SplineCurve.prototype = Object.create( Curve.prototype );
  24032. SplineCurve.prototype.constructor = SplineCurve;
  24033. SplineCurve.prototype.isSplineCurve = true;
  24034. SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  24035. var point = optionalTarget || new Vector2();
  24036. var points = this.points;
  24037. var p = ( points.length - 1 ) * t;
  24038. var intPoint = Math.floor( p );
  24039. var weight = p - intPoint;
  24040. var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24041. var p1 = points[ intPoint ];
  24042. var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24043. var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24044. point.set(
  24045. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24046. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24047. );
  24048. return point;
  24049. };
  24050. SplineCurve.prototype.copy = function ( source ) {
  24051. Curve.prototype.copy.call( this, source );
  24052. this.points = [];
  24053. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  24054. var point = source.points[ i ];
  24055. this.points.push( point.clone() );
  24056. }
  24057. return this;
  24058. };
  24059. SplineCurve.prototype.toJSON = function () {
  24060. var data = Curve.prototype.toJSON.call( this );
  24061. data.points = [];
  24062. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  24063. var point = this.points[ i ];
  24064. data.points.push( point.toArray() );
  24065. }
  24066. return data;
  24067. };
  24068. SplineCurve.prototype.fromJSON = function ( json ) {
  24069. Curve.prototype.fromJSON.call( this, json );
  24070. this.points = [];
  24071. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  24072. var point = json.points[ i ];
  24073. this.points.push( new Vector2().fromArray( point ) );
  24074. }
  24075. return this;
  24076. };
  24077. var Curves = /*#__PURE__*/Object.freeze({
  24078. ArcCurve: ArcCurve,
  24079. CatmullRomCurve3: CatmullRomCurve3,
  24080. CubicBezierCurve: CubicBezierCurve,
  24081. CubicBezierCurve3: CubicBezierCurve3,
  24082. EllipseCurve: EllipseCurve,
  24083. LineCurve: LineCurve,
  24084. LineCurve3: LineCurve3,
  24085. QuadraticBezierCurve: QuadraticBezierCurve,
  24086. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24087. SplineCurve: SplineCurve
  24088. });
  24089. /**
  24090. * @author zz85 / http://www.lab4games.net/zz85/blog
  24091. *
  24092. **/
  24093. /**************************************************************
  24094. * Curved Path - a curve path is simply a array of connected
  24095. * curves, but retains the api of a curve
  24096. **************************************************************/
  24097. function CurvePath() {
  24098. Curve.call( this );
  24099. this.type = 'CurvePath';
  24100. this.curves = [];
  24101. this.autoClose = false; // Automatically closes the path
  24102. }
  24103. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  24104. constructor: CurvePath,
  24105. add: function ( curve ) {
  24106. this.curves.push( curve );
  24107. },
  24108. closePath: function () {
  24109. // Add a line curve if start and end of lines are not connected
  24110. var startPoint = this.curves[ 0 ].getPoint( 0 );
  24111. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24112. if ( ! startPoint.equals( endPoint ) ) {
  24113. this.curves.push( new LineCurve( endPoint, startPoint ) );
  24114. }
  24115. },
  24116. // To get accurate point with reference to
  24117. // entire path distance at time t,
  24118. // following has to be done:
  24119. // 1. Length of each sub path have to be known
  24120. // 2. Locate and identify type of curve
  24121. // 3. Get t for the curve
  24122. // 4. Return curve.getPointAt(t')
  24123. getPoint: function ( t ) {
  24124. var d = t * this.getLength();
  24125. var curveLengths = this.getCurveLengths();
  24126. var i = 0;
  24127. // To think about boundaries points.
  24128. while ( i < curveLengths.length ) {
  24129. if ( curveLengths[ i ] >= d ) {
  24130. var diff = curveLengths[ i ] - d;
  24131. var curve = this.curves[ i ];
  24132. var segmentLength = curve.getLength();
  24133. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24134. return curve.getPointAt( u );
  24135. }
  24136. i ++;
  24137. }
  24138. return null;
  24139. // loop where sum != 0, sum > d , sum+1 <d
  24140. },
  24141. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24142. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24143. // getPoint() depends on getLength
  24144. getLength: function () {
  24145. var lens = this.getCurveLengths();
  24146. return lens[ lens.length - 1 ];
  24147. },
  24148. // cacheLengths must be recalculated.
  24149. updateArcLengths: function () {
  24150. this.needsUpdate = true;
  24151. this.cacheLengths = null;
  24152. this.getCurveLengths();
  24153. },
  24154. // Compute lengths and cache them
  24155. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24156. getCurveLengths: function () {
  24157. // We use cache values if curves and cache array are same length
  24158. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24159. return this.cacheLengths;
  24160. }
  24161. // Get length of sub-curve
  24162. // Push sums into cached array
  24163. var lengths = [], sums = 0;
  24164. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  24165. sums += this.curves[ i ].getLength();
  24166. lengths.push( sums );
  24167. }
  24168. this.cacheLengths = lengths;
  24169. return lengths;
  24170. },
  24171. getSpacedPoints: function ( divisions ) {
  24172. if ( divisions === undefined ) divisions = 40;
  24173. var points = [];
  24174. for ( var i = 0; i <= divisions; i ++ ) {
  24175. points.push( this.getPoint( i / divisions ) );
  24176. }
  24177. if ( this.autoClose ) {
  24178. points.push( points[ 0 ] );
  24179. }
  24180. return points;
  24181. },
  24182. getPoints: function ( divisions ) {
  24183. divisions = divisions || 12;
  24184. var points = [], last;
  24185. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24186. var curve = curves[ i ];
  24187. var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  24188. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  24189. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  24190. : divisions;
  24191. var pts = curve.getPoints( resolution );
  24192. for ( var j = 0; j < pts.length; j ++ ) {
  24193. var point = pts[ j ];
  24194. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24195. points.push( point );
  24196. last = point;
  24197. }
  24198. }
  24199. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24200. points.push( points[ 0 ] );
  24201. }
  24202. return points;
  24203. },
  24204. copy: function ( source ) {
  24205. Curve.prototype.copy.call( this, source );
  24206. this.curves = [];
  24207. for ( var i = 0, l = source.curves.length; i < l; i ++ ) {
  24208. var curve = source.curves[ i ];
  24209. this.curves.push( curve.clone() );
  24210. }
  24211. this.autoClose = source.autoClose;
  24212. return this;
  24213. },
  24214. toJSON: function () {
  24215. var data = Curve.prototype.toJSON.call( this );
  24216. data.autoClose = this.autoClose;
  24217. data.curves = [];
  24218. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  24219. var curve = this.curves[ i ];
  24220. data.curves.push( curve.toJSON() );
  24221. }
  24222. return data;
  24223. },
  24224. fromJSON: function ( json ) {
  24225. Curve.prototype.fromJSON.call( this, json );
  24226. this.autoClose = json.autoClose;
  24227. this.curves = [];
  24228. for ( var i = 0, l = json.curves.length; i < l; i ++ ) {
  24229. var curve = json.curves[ i ];
  24230. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24231. }
  24232. return this;
  24233. }
  24234. } );
  24235. /**
  24236. * @author zz85 / http://www.lab4games.net/zz85/blog
  24237. * Creates free form 2d path using series of points, lines or curves.
  24238. **/
  24239. function Path( points ) {
  24240. CurvePath.call( this );
  24241. this.type = 'Path';
  24242. this.currentPoint = new Vector2();
  24243. if ( points ) {
  24244. this.setFromPoints( points );
  24245. }
  24246. }
  24247. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  24248. constructor: Path,
  24249. setFromPoints: function ( points ) {
  24250. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24251. for ( var i = 1, l = points.length; i < l; i ++ ) {
  24252. this.lineTo( points[ i ].x, points[ i ].y );
  24253. }
  24254. },
  24255. moveTo: function ( x, y ) {
  24256. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24257. },
  24258. lineTo: function ( x, y ) {
  24259. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24260. this.curves.push( curve );
  24261. this.currentPoint.set( x, y );
  24262. },
  24263. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  24264. var curve = new QuadraticBezierCurve(
  24265. this.currentPoint.clone(),
  24266. new Vector2( aCPx, aCPy ),
  24267. new Vector2( aX, aY )
  24268. );
  24269. this.curves.push( curve );
  24270. this.currentPoint.set( aX, aY );
  24271. },
  24272. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24273. var curve = new CubicBezierCurve(
  24274. this.currentPoint.clone(),
  24275. new Vector2( aCP1x, aCP1y ),
  24276. new Vector2( aCP2x, aCP2y ),
  24277. new Vector2( aX, aY )
  24278. );
  24279. this.curves.push( curve );
  24280. this.currentPoint.set( aX, aY );
  24281. },
  24282. splineThru: function ( pts /*Array of Vector*/ ) {
  24283. var npts = [ this.currentPoint.clone() ].concat( pts );
  24284. var curve = new SplineCurve( npts );
  24285. this.curves.push( curve );
  24286. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24287. },
  24288. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24289. var x0 = this.currentPoint.x;
  24290. var y0 = this.currentPoint.y;
  24291. this.absarc( aX + x0, aY + y0, aRadius,
  24292. aStartAngle, aEndAngle, aClockwise );
  24293. },
  24294. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24295. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24296. },
  24297. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24298. var x0 = this.currentPoint.x;
  24299. var y0 = this.currentPoint.y;
  24300. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24301. },
  24302. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24303. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24304. if ( this.curves.length > 0 ) {
  24305. // if a previous curve is present, attempt to join
  24306. var firstPoint = curve.getPoint( 0 );
  24307. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24308. this.lineTo( firstPoint.x, firstPoint.y );
  24309. }
  24310. }
  24311. this.curves.push( curve );
  24312. var lastPoint = curve.getPoint( 1 );
  24313. this.currentPoint.copy( lastPoint );
  24314. },
  24315. copy: function ( source ) {
  24316. CurvePath.prototype.copy.call( this, source );
  24317. this.currentPoint.copy( source.currentPoint );
  24318. return this;
  24319. },
  24320. toJSON: function () {
  24321. var data = CurvePath.prototype.toJSON.call( this );
  24322. data.currentPoint = this.currentPoint.toArray();
  24323. return data;
  24324. },
  24325. fromJSON: function ( json ) {
  24326. CurvePath.prototype.fromJSON.call( this, json );
  24327. this.currentPoint.fromArray( json.currentPoint );
  24328. return this;
  24329. }
  24330. } );
  24331. /**
  24332. * @author zz85 / http://www.lab4games.net/zz85/blog
  24333. * Defines a 2d shape plane using paths.
  24334. **/
  24335. // STEP 1 Create a path.
  24336. // STEP 2 Turn path into shape.
  24337. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  24338. // STEP 3a - Extract points from each shape, turn to vertices
  24339. // STEP 3b - Triangulate each shape, add faces.
  24340. function Shape( points ) {
  24341. Path.call( this, points );
  24342. this.uuid = _Math.generateUUID();
  24343. this.type = 'Shape';
  24344. this.holes = [];
  24345. }
  24346. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  24347. constructor: Shape,
  24348. getPointsHoles: function ( divisions ) {
  24349. var holesPts = [];
  24350. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  24351. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24352. }
  24353. return holesPts;
  24354. },
  24355. // get points of shape and holes (keypoints based on segments parameter)
  24356. extractPoints: function ( divisions ) {
  24357. return {
  24358. shape: this.getPoints( divisions ),
  24359. holes: this.getPointsHoles( divisions )
  24360. };
  24361. },
  24362. copy: function ( source ) {
  24363. Path.prototype.copy.call( this, source );
  24364. this.holes = [];
  24365. for ( var i = 0, l = source.holes.length; i < l; i ++ ) {
  24366. var hole = source.holes[ i ];
  24367. this.holes.push( hole.clone() );
  24368. }
  24369. return this;
  24370. },
  24371. toJSON: function () {
  24372. var data = Path.prototype.toJSON.call( this );
  24373. data.uuid = this.uuid;
  24374. data.holes = [];
  24375. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  24376. var hole = this.holes[ i ];
  24377. data.holes.push( hole.toJSON() );
  24378. }
  24379. return data;
  24380. },
  24381. fromJSON: function ( json ) {
  24382. Path.prototype.fromJSON.call( this, json );
  24383. this.uuid = json.uuid;
  24384. this.holes = [];
  24385. for ( var i = 0, l = json.holes.length; i < l; i ++ ) {
  24386. var hole = json.holes[ i ];
  24387. this.holes.push( new Path().fromJSON( hole ) );
  24388. }
  24389. return this;
  24390. }
  24391. } );
  24392. /**
  24393. * @author mrdoob / http://mrdoob.com/
  24394. * @author alteredq / http://alteredqualia.com/
  24395. */
  24396. function Light( color, intensity ) {
  24397. Object3D.call( this );
  24398. this.type = 'Light';
  24399. this.color = new Color( color );
  24400. this.intensity = intensity !== undefined ? intensity : 1;
  24401. this.receiveShadow = undefined;
  24402. }
  24403. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  24404. constructor: Light,
  24405. isLight: true,
  24406. copy: function ( source ) {
  24407. Object3D.prototype.copy.call( this, source );
  24408. this.color.copy( source.color );
  24409. this.intensity = source.intensity;
  24410. return this;
  24411. },
  24412. toJSON: function ( meta ) {
  24413. var data = Object3D.prototype.toJSON.call( this, meta );
  24414. data.object.color = this.color.getHex();
  24415. data.object.intensity = this.intensity;
  24416. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24417. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24418. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24419. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24420. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24421. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24422. return data;
  24423. }
  24424. } );
  24425. /**
  24426. * @author alteredq / http://alteredqualia.com/
  24427. */
  24428. function HemisphereLight( skyColor, groundColor, intensity ) {
  24429. Light.call( this, skyColor, intensity );
  24430. this.type = 'HemisphereLight';
  24431. this.castShadow = undefined;
  24432. this.position.copy( Object3D.DefaultUp );
  24433. this.updateMatrix();
  24434. this.groundColor = new Color( groundColor );
  24435. }
  24436. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24437. constructor: HemisphereLight,
  24438. isHemisphereLight: true,
  24439. copy: function ( source ) {
  24440. Light.prototype.copy.call( this, source );
  24441. this.groundColor.copy( source.groundColor );
  24442. return this;
  24443. }
  24444. } );
  24445. /**
  24446. * @author mrdoob / http://mrdoob.com/
  24447. */
  24448. function LightShadow( camera ) {
  24449. this.camera = camera;
  24450. this.bias = 0;
  24451. this.radius = 1;
  24452. this.mapSize = new Vector2( 512, 512 );
  24453. this.map = null;
  24454. this.matrix = new Matrix4();
  24455. }
  24456. Object.assign( LightShadow.prototype, {
  24457. copy: function ( source ) {
  24458. this.camera = source.camera.clone();
  24459. this.bias = source.bias;
  24460. this.radius = source.radius;
  24461. this.mapSize.copy( source.mapSize );
  24462. return this;
  24463. },
  24464. clone: function () {
  24465. return new this.constructor().copy( this );
  24466. },
  24467. toJSON: function () {
  24468. var object = {};
  24469. if ( this.bias !== 0 ) object.bias = this.bias;
  24470. if ( this.radius !== 1 ) object.radius = this.radius;
  24471. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24472. object.camera = this.camera.toJSON( false ).object;
  24473. delete object.camera.matrix;
  24474. return object;
  24475. }
  24476. } );
  24477. /**
  24478. * @author mrdoob / http://mrdoob.com/
  24479. */
  24480. function SpotLightShadow() {
  24481. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24482. }
  24483. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24484. constructor: SpotLightShadow,
  24485. isSpotLightShadow: true,
  24486. update: function ( light ) {
  24487. var camera = this.camera;
  24488. var fov = _Math.RAD2DEG * 2 * light.angle;
  24489. var aspect = this.mapSize.width / this.mapSize.height;
  24490. var far = light.distance || camera.far;
  24491. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24492. camera.fov = fov;
  24493. camera.aspect = aspect;
  24494. camera.far = far;
  24495. camera.updateProjectionMatrix();
  24496. }
  24497. }
  24498. } );
  24499. /**
  24500. * @author alteredq / http://alteredqualia.com/
  24501. */
  24502. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  24503. Light.call( this, color, intensity );
  24504. this.type = 'SpotLight';
  24505. this.position.copy( Object3D.DefaultUp );
  24506. this.updateMatrix();
  24507. this.target = new Object3D();
  24508. Object.defineProperty( this, 'power', {
  24509. get: function () {
  24510. // intensity = power per solid angle.
  24511. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24512. return this.intensity * Math.PI;
  24513. },
  24514. set: function ( power ) {
  24515. // intensity = power per solid angle.
  24516. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24517. this.intensity = power / Math.PI;
  24518. }
  24519. } );
  24520. this.distance = ( distance !== undefined ) ? distance : 0;
  24521. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  24522. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  24523. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24524. this.shadow = new SpotLightShadow();
  24525. }
  24526. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24527. constructor: SpotLight,
  24528. isSpotLight: true,
  24529. copy: function ( source ) {
  24530. Light.prototype.copy.call( this, source );
  24531. this.distance = source.distance;
  24532. this.angle = source.angle;
  24533. this.penumbra = source.penumbra;
  24534. this.decay = source.decay;
  24535. this.target = source.target.clone();
  24536. this.shadow = source.shadow.clone();
  24537. return this;
  24538. }
  24539. } );
  24540. /**
  24541. * @author mrdoob / http://mrdoob.com/
  24542. */
  24543. function PointLight( color, intensity, distance, decay ) {
  24544. Light.call( this, color, intensity );
  24545. this.type = 'PointLight';
  24546. Object.defineProperty( this, 'power', {
  24547. get: function () {
  24548. // intensity = power per solid angle.
  24549. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24550. return this.intensity * 4 * Math.PI;
  24551. },
  24552. set: function ( power ) {
  24553. // intensity = power per solid angle.
  24554. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24555. this.intensity = power / ( 4 * Math.PI );
  24556. }
  24557. } );
  24558. this.distance = ( distance !== undefined ) ? distance : 0;
  24559. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24560. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24561. }
  24562. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24563. constructor: PointLight,
  24564. isPointLight: true,
  24565. copy: function ( source ) {
  24566. Light.prototype.copy.call( this, source );
  24567. this.distance = source.distance;
  24568. this.decay = source.decay;
  24569. this.shadow = source.shadow.clone();
  24570. return this;
  24571. }
  24572. } );
  24573. /**
  24574. * @author mrdoob / http://mrdoob.com/
  24575. */
  24576. function DirectionalLightShadow( ) {
  24577. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24578. }
  24579. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24580. constructor: DirectionalLightShadow
  24581. } );
  24582. /**
  24583. * @author mrdoob / http://mrdoob.com/
  24584. * @author alteredq / http://alteredqualia.com/
  24585. */
  24586. function DirectionalLight( color, intensity ) {
  24587. Light.call( this, color, intensity );
  24588. this.type = 'DirectionalLight';
  24589. this.position.copy( Object3D.DefaultUp );
  24590. this.updateMatrix();
  24591. this.target = new Object3D();
  24592. this.shadow = new DirectionalLightShadow();
  24593. }
  24594. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24595. constructor: DirectionalLight,
  24596. isDirectionalLight: true,
  24597. copy: function ( source ) {
  24598. Light.prototype.copy.call( this, source );
  24599. this.target = source.target.clone();
  24600. this.shadow = source.shadow.clone();
  24601. return this;
  24602. }
  24603. } );
  24604. /**
  24605. * @author mrdoob / http://mrdoob.com/
  24606. */
  24607. function AmbientLight( color, intensity ) {
  24608. Light.call( this, color, intensity );
  24609. this.type = 'AmbientLight';
  24610. this.castShadow = undefined;
  24611. }
  24612. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24613. constructor: AmbientLight,
  24614. isAmbientLight: true
  24615. } );
  24616. /**
  24617. * @author abelnation / http://github.com/abelnation
  24618. */
  24619. function RectAreaLight( color, intensity, width, height ) {
  24620. Light.call( this, color, intensity );
  24621. this.type = 'RectAreaLight';
  24622. this.width = ( width !== undefined ) ? width : 10;
  24623. this.height = ( height !== undefined ) ? height : 10;
  24624. }
  24625. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24626. constructor: RectAreaLight,
  24627. isRectAreaLight: true,
  24628. copy: function ( source ) {
  24629. Light.prototype.copy.call( this, source );
  24630. this.width = source.width;
  24631. this.height = source.height;
  24632. return this;
  24633. },
  24634. toJSON: function ( meta ) {
  24635. var data = Light.prototype.toJSON.call( this, meta );
  24636. data.object.width = this.width;
  24637. data.object.height = this.height;
  24638. return data;
  24639. }
  24640. } );
  24641. /**
  24642. * @author tschw
  24643. * @author Ben Houston / http://clara.io/
  24644. * @author David Sarno / http://lighthaus.us/
  24645. */
  24646. var AnimationUtils = {
  24647. // same as Array.prototype.slice, but also works on typed arrays
  24648. arraySlice: function ( array, from, to ) {
  24649. if ( AnimationUtils.isTypedArray( array ) ) {
  24650. // in ios9 array.subarray(from, undefined) will return empty array
  24651. // but array.subarray(from) or array.subarray(from, len) is correct
  24652. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  24653. }
  24654. return array.slice( from, to );
  24655. },
  24656. // converts an array to a specific type
  24657. convertArray: function ( array, type, forceClone ) {
  24658. if ( ! array || // let 'undefined' and 'null' pass
  24659. ! forceClone && array.constructor === type ) return array;
  24660. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  24661. return new type( array ); // create typed array
  24662. }
  24663. return Array.prototype.slice.call( array ); // create Array
  24664. },
  24665. isTypedArray: function ( object ) {
  24666. return ArrayBuffer.isView( object ) &&
  24667. ! ( object instanceof DataView );
  24668. },
  24669. // returns an array by which times and values can be sorted
  24670. getKeyframeOrder: function ( times ) {
  24671. function compareTime( i, j ) {
  24672. return times[ i ] - times[ j ];
  24673. }
  24674. var n = times.length;
  24675. var result = new Array( n );
  24676. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  24677. result.sort( compareTime );
  24678. return result;
  24679. },
  24680. // uses the array previously returned by 'getKeyframeOrder' to sort data
  24681. sortedArray: function ( values, stride, order ) {
  24682. var nValues = values.length;
  24683. var result = new values.constructor( nValues );
  24684. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  24685. var srcOffset = order[ i ] * stride;
  24686. for ( var j = 0; j !== stride; ++ j ) {
  24687. result[ dstOffset ++ ] = values[ srcOffset + j ];
  24688. }
  24689. }
  24690. return result;
  24691. },
  24692. // function for parsing AOS keyframe formats
  24693. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  24694. var i = 1, key = jsonKeys[ 0 ];
  24695. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  24696. key = jsonKeys[ i ++ ];
  24697. }
  24698. if ( key === undefined ) return; // no data
  24699. var value = key[ valuePropertyName ];
  24700. if ( value === undefined ) return; // no data
  24701. if ( Array.isArray( value ) ) {
  24702. do {
  24703. value = key[ valuePropertyName ];
  24704. if ( value !== undefined ) {
  24705. times.push( key.time );
  24706. values.push.apply( values, value ); // push all elements
  24707. }
  24708. key = jsonKeys[ i ++ ];
  24709. } while ( key !== undefined );
  24710. } else if ( value.toArray !== undefined ) {
  24711. // ...assume THREE.Math-ish
  24712. do {
  24713. value = key[ valuePropertyName ];
  24714. if ( value !== undefined ) {
  24715. times.push( key.time );
  24716. value.toArray( values, values.length );
  24717. }
  24718. key = jsonKeys[ i ++ ];
  24719. } while ( key !== undefined );
  24720. } else {
  24721. // otherwise push as-is
  24722. do {
  24723. value = key[ valuePropertyName ];
  24724. if ( value !== undefined ) {
  24725. times.push( key.time );
  24726. values.push( value );
  24727. }
  24728. key = jsonKeys[ i ++ ];
  24729. } while ( key !== undefined );
  24730. }
  24731. }
  24732. };
  24733. /**
  24734. * Abstract base class of interpolants over parametric samples.
  24735. *
  24736. * The parameter domain is one dimensional, typically the time or a path
  24737. * along a curve defined by the data.
  24738. *
  24739. * The sample values can have any dimensionality and derived classes may
  24740. * apply special interpretations to the data.
  24741. *
  24742. * This class provides the interval seek in a Template Method, deferring
  24743. * the actual interpolation to derived classes.
  24744. *
  24745. * Time complexity is O(1) for linear access crossing at most two points
  24746. * and O(log N) for random access, where N is the number of positions.
  24747. *
  24748. * References:
  24749. *
  24750. * http://www.oodesign.com/template-method-pattern.html
  24751. *
  24752. * @author tschw
  24753. */
  24754. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24755. this.parameterPositions = parameterPositions;
  24756. this._cachedIndex = 0;
  24757. this.resultBuffer = resultBuffer !== undefined ?
  24758. resultBuffer : new sampleValues.constructor( sampleSize );
  24759. this.sampleValues = sampleValues;
  24760. this.valueSize = sampleSize;
  24761. }
  24762. Object.assign( Interpolant.prototype, {
  24763. evaluate: function ( t ) {
  24764. var pp = this.parameterPositions,
  24765. i1 = this._cachedIndex,
  24766. t1 = pp[ i1 ],
  24767. t0 = pp[ i1 - 1 ];
  24768. validate_interval: {
  24769. seek: {
  24770. var right;
  24771. linear_scan: {
  24772. //- See http://jsperf.com/comparison-to-undefined/3
  24773. //- slower code:
  24774. //-
  24775. //- if ( t >= t1 || t1 === undefined ) {
  24776. forward_scan: if ( ! ( t < t1 ) ) {
  24777. for ( var giveUpAt = i1 + 2; ; ) {
  24778. if ( t1 === undefined ) {
  24779. if ( t < t0 ) break forward_scan;
  24780. // after end
  24781. i1 = pp.length;
  24782. this._cachedIndex = i1;
  24783. return this.afterEnd_( i1 - 1, t, t0 );
  24784. }
  24785. if ( i1 === giveUpAt ) break; // this loop
  24786. t0 = t1;
  24787. t1 = pp[ ++ i1 ];
  24788. if ( t < t1 ) {
  24789. // we have arrived at the sought interval
  24790. break seek;
  24791. }
  24792. }
  24793. // prepare binary search on the right side of the index
  24794. right = pp.length;
  24795. break linear_scan;
  24796. }
  24797. //- slower code:
  24798. //- if ( t < t0 || t0 === undefined ) {
  24799. if ( ! ( t >= t0 ) ) {
  24800. // looping?
  24801. var t1global = pp[ 1 ];
  24802. if ( t < t1global ) {
  24803. i1 = 2; // + 1, using the scan for the details
  24804. t0 = t1global;
  24805. }
  24806. // linear reverse scan
  24807. for ( var giveUpAt = i1 - 2; ; ) {
  24808. if ( t0 === undefined ) {
  24809. // before start
  24810. this._cachedIndex = 0;
  24811. return this.beforeStart_( 0, t, t1 );
  24812. }
  24813. if ( i1 === giveUpAt ) break; // this loop
  24814. t1 = t0;
  24815. t0 = pp[ -- i1 - 1 ];
  24816. if ( t >= t0 ) {
  24817. // we have arrived at the sought interval
  24818. break seek;
  24819. }
  24820. }
  24821. // prepare binary search on the left side of the index
  24822. right = i1;
  24823. i1 = 0;
  24824. break linear_scan;
  24825. }
  24826. // the interval is valid
  24827. break validate_interval;
  24828. } // linear scan
  24829. // binary search
  24830. while ( i1 < right ) {
  24831. var mid = ( i1 + right ) >>> 1;
  24832. if ( t < pp[ mid ] ) {
  24833. right = mid;
  24834. } else {
  24835. i1 = mid + 1;
  24836. }
  24837. }
  24838. t1 = pp[ i1 ];
  24839. t0 = pp[ i1 - 1 ];
  24840. // check boundary cases, again
  24841. if ( t0 === undefined ) {
  24842. this._cachedIndex = 0;
  24843. return this.beforeStart_( 0, t, t1 );
  24844. }
  24845. if ( t1 === undefined ) {
  24846. i1 = pp.length;
  24847. this._cachedIndex = i1;
  24848. return this.afterEnd_( i1 - 1, t0, t );
  24849. }
  24850. } // seek
  24851. this._cachedIndex = i1;
  24852. this.intervalChanged_( i1, t0, t1 );
  24853. } // validate_interval
  24854. return this.interpolate_( i1, t0, t, t1 );
  24855. },
  24856. settings: null, // optional, subclass-specific settings structure
  24857. // Note: The indirection allows central control of many interpolants.
  24858. // --- Protected interface
  24859. DefaultSettings_: {},
  24860. getSettings_: function () {
  24861. return this.settings || this.DefaultSettings_;
  24862. },
  24863. copySampleValue_: function ( index ) {
  24864. // copies a sample value to the result buffer
  24865. var result = this.resultBuffer,
  24866. values = this.sampleValues,
  24867. stride = this.valueSize,
  24868. offset = index * stride;
  24869. for ( var i = 0; i !== stride; ++ i ) {
  24870. result[ i ] = values[ offset + i ];
  24871. }
  24872. return result;
  24873. },
  24874. // Template methods for derived classes:
  24875. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  24876. throw new Error( 'call to abstract method' );
  24877. // implementations shall return this.resultBuffer
  24878. },
  24879. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  24880. // empty
  24881. }
  24882. } );
  24883. //!\ DECLARE ALIAS AFTER assign prototype !
  24884. Object.assign( Interpolant.prototype, {
  24885. //( 0, t, t0 ), returns this.resultBuffer
  24886. beforeStart_: Interpolant.prototype.copySampleValue_,
  24887. //( N-1, tN-1, t ), returns this.resultBuffer
  24888. afterEnd_: Interpolant.prototype.copySampleValue_,
  24889. } );
  24890. /**
  24891. * Fast and simple cubic spline interpolant.
  24892. *
  24893. * It was derived from a Hermitian construction setting the first derivative
  24894. * at each sample position to the linear slope between neighboring positions
  24895. * over their parameter interval.
  24896. *
  24897. * @author tschw
  24898. */
  24899. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24900. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24901. this._weightPrev = - 0;
  24902. this._offsetPrev = - 0;
  24903. this._weightNext = - 0;
  24904. this._offsetNext = - 0;
  24905. }
  24906. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24907. constructor: CubicInterpolant,
  24908. DefaultSettings_: {
  24909. endingStart: ZeroCurvatureEnding,
  24910. endingEnd: ZeroCurvatureEnding
  24911. },
  24912. intervalChanged_: function ( i1, t0, t1 ) {
  24913. var pp = this.parameterPositions,
  24914. iPrev = i1 - 2,
  24915. iNext = i1 + 1,
  24916. tPrev = pp[ iPrev ],
  24917. tNext = pp[ iNext ];
  24918. if ( tPrev === undefined ) {
  24919. switch ( this.getSettings_().endingStart ) {
  24920. case ZeroSlopeEnding:
  24921. // f'(t0) = 0
  24922. iPrev = i1;
  24923. tPrev = 2 * t0 - t1;
  24924. break;
  24925. case WrapAroundEnding:
  24926. // use the other end of the curve
  24927. iPrev = pp.length - 2;
  24928. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  24929. break;
  24930. default: // ZeroCurvatureEnding
  24931. // f''(t0) = 0 a.k.a. Natural Spline
  24932. iPrev = i1;
  24933. tPrev = t1;
  24934. }
  24935. }
  24936. if ( tNext === undefined ) {
  24937. switch ( this.getSettings_().endingEnd ) {
  24938. case ZeroSlopeEnding:
  24939. // f'(tN) = 0
  24940. iNext = i1;
  24941. tNext = 2 * t1 - t0;
  24942. break;
  24943. case WrapAroundEnding:
  24944. // use the other end of the curve
  24945. iNext = 1;
  24946. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  24947. break;
  24948. default: // ZeroCurvatureEnding
  24949. // f''(tN) = 0, a.k.a. Natural Spline
  24950. iNext = i1 - 1;
  24951. tNext = t0;
  24952. }
  24953. }
  24954. var halfDt = ( t1 - t0 ) * 0.5,
  24955. stride = this.valueSize;
  24956. this._weightPrev = halfDt / ( t0 - tPrev );
  24957. this._weightNext = halfDt / ( tNext - t1 );
  24958. this._offsetPrev = iPrev * stride;
  24959. this._offsetNext = iNext * stride;
  24960. },
  24961. interpolate_: function ( i1, t0, t, t1 ) {
  24962. var result = this.resultBuffer,
  24963. values = this.sampleValues,
  24964. stride = this.valueSize,
  24965. o1 = i1 * stride, o0 = o1 - stride,
  24966. oP = this._offsetPrev, oN = this._offsetNext,
  24967. wP = this._weightPrev, wN = this._weightNext,
  24968. p = ( t - t0 ) / ( t1 - t0 ),
  24969. pp = p * p,
  24970. ppp = pp * p;
  24971. // evaluate polynomials
  24972. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  24973. var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  24974. var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  24975. var sN = wN * ppp - wN * pp;
  24976. // combine data linearly
  24977. for ( var i = 0; i !== stride; ++ i ) {
  24978. result[ i ] =
  24979. sP * values[ oP + i ] +
  24980. s0 * values[ o0 + i ] +
  24981. s1 * values[ o1 + i ] +
  24982. sN * values[ oN + i ];
  24983. }
  24984. return result;
  24985. }
  24986. } );
  24987. /**
  24988. * @author tschw
  24989. */
  24990. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24991. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24992. }
  24993. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24994. constructor: LinearInterpolant,
  24995. interpolate_: function ( i1, t0, t, t1 ) {
  24996. var result = this.resultBuffer,
  24997. values = this.sampleValues,
  24998. stride = this.valueSize,
  24999. offset1 = i1 * stride,
  25000. offset0 = offset1 - stride,
  25001. weight1 = ( t - t0 ) / ( t1 - t0 ),
  25002. weight0 = 1 - weight1;
  25003. for ( var i = 0; i !== stride; ++ i ) {
  25004. result[ i ] =
  25005. values[ offset0 + i ] * weight0 +
  25006. values[ offset1 + i ] * weight1;
  25007. }
  25008. return result;
  25009. }
  25010. } );
  25011. /**
  25012. *
  25013. * Interpolant that evaluates to the sample value at the position preceeding
  25014. * the parameter.
  25015. *
  25016. * @author tschw
  25017. */
  25018. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25019. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  25020. }
  25021. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  25022. constructor: DiscreteInterpolant,
  25023. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  25024. return this.copySampleValue_( i1 - 1 );
  25025. }
  25026. } );
  25027. /**
  25028. *
  25029. * A timed sequence of keyframes for a specific property.
  25030. *
  25031. *
  25032. * @author Ben Houston / http://clara.io/
  25033. * @author David Sarno / http://lighthaus.us/
  25034. * @author tschw
  25035. */
  25036. function KeyframeTrack( name, times, values, interpolation ) {
  25037. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  25038. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  25039. this.name = name;
  25040. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  25041. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  25042. this.setInterpolation( interpolation || this.DefaultInterpolation );
  25043. }
  25044. // Static methods
  25045. Object.assign( KeyframeTrack, {
  25046. // Serialization (in static context, because of constructor invocation
  25047. // and automatic invocation of .toJSON):
  25048. toJSON: function ( track ) {
  25049. var trackType = track.constructor;
  25050. var json;
  25051. // derived classes can define a static toJSON method
  25052. if ( trackType.toJSON !== undefined ) {
  25053. json = trackType.toJSON( track );
  25054. } else {
  25055. // by default, we assume the data can be serialized as-is
  25056. json = {
  25057. 'name': track.name,
  25058. 'times': AnimationUtils.convertArray( track.times, Array ),
  25059. 'values': AnimationUtils.convertArray( track.values, Array )
  25060. };
  25061. var interpolation = track.getInterpolation();
  25062. if ( interpolation !== track.DefaultInterpolation ) {
  25063. json.interpolation = interpolation;
  25064. }
  25065. }
  25066. json.type = track.ValueTypeName; // mandatory
  25067. return json;
  25068. }
  25069. } );
  25070. Object.assign( KeyframeTrack.prototype, {
  25071. constructor: KeyframeTrack,
  25072. TimeBufferType: Float32Array,
  25073. ValueBufferType: Float32Array,
  25074. DefaultInterpolation: InterpolateLinear,
  25075. InterpolantFactoryMethodDiscrete: function ( result ) {
  25076. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  25077. },
  25078. InterpolantFactoryMethodLinear: function ( result ) {
  25079. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25080. },
  25081. InterpolantFactoryMethodSmooth: function ( result ) {
  25082. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  25083. },
  25084. setInterpolation: function ( interpolation ) {
  25085. var factoryMethod;
  25086. switch ( interpolation ) {
  25087. case InterpolateDiscrete:
  25088. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  25089. break;
  25090. case InterpolateLinear:
  25091. factoryMethod = this.InterpolantFactoryMethodLinear;
  25092. break;
  25093. case InterpolateSmooth:
  25094. factoryMethod = this.InterpolantFactoryMethodSmooth;
  25095. break;
  25096. }
  25097. if ( factoryMethod === undefined ) {
  25098. var message = "unsupported interpolation for " +
  25099. this.ValueTypeName + " keyframe track named " + this.name;
  25100. if ( this.createInterpolant === undefined ) {
  25101. // fall back to default, unless the default itself is messed up
  25102. if ( interpolation !== this.DefaultInterpolation ) {
  25103. this.setInterpolation( this.DefaultInterpolation );
  25104. } else {
  25105. throw new Error( message ); // fatal, in this case
  25106. }
  25107. }
  25108. console.warn( 'THREE.KeyframeTrack:', message );
  25109. return this;
  25110. }
  25111. this.createInterpolant = factoryMethod;
  25112. return this;
  25113. },
  25114. getInterpolation: function () {
  25115. switch ( this.createInterpolant ) {
  25116. case this.InterpolantFactoryMethodDiscrete:
  25117. return InterpolateDiscrete;
  25118. case this.InterpolantFactoryMethodLinear:
  25119. return InterpolateLinear;
  25120. case this.InterpolantFactoryMethodSmooth:
  25121. return InterpolateSmooth;
  25122. }
  25123. },
  25124. getValueSize: function () {
  25125. return this.values.length / this.times.length;
  25126. },
  25127. // move all keyframes either forwards or backwards in time
  25128. shift: function ( timeOffset ) {
  25129. if ( timeOffset !== 0.0 ) {
  25130. var times = this.times;
  25131. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  25132. times[ i ] += timeOffset;
  25133. }
  25134. }
  25135. return this;
  25136. },
  25137. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  25138. scale: function ( timeScale ) {
  25139. if ( timeScale !== 1.0 ) {
  25140. var times = this.times;
  25141. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  25142. times[ i ] *= timeScale;
  25143. }
  25144. }
  25145. return this;
  25146. },
  25147. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  25148. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  25149. trim: function ( startTime, endTime ) {
  25150. var times = this.times,
  25151. nKeys = times.length,
  25152. from = 0,
  25153. to = nKeys - 1;
  25154. while ( from !== nKeys && times[ from ] < startTime ) {
  25155. ++ from;
  25156. }
  25157. while ( to !== - 1 && times[ to ] > endTime ) {
  25158. -- to;
  25159. }
  25160. ++ to; // inclusive -> exclusive bound
  25161. if ( from !== 0 || to !== nKeys ) {
  25162. // empty tracks are forbidden, so keep at least one keyframe
  25163. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  25164. var stride = this.getValueSize();
  25165. this.times = AnimationUtils.arraySlice( times, from, to );
  25166. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  25167. }
  25168. return this;
  25169. },
  25170. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  25171. validate: function () {
  25172. var valid = true;
  25173. var valueSize = this.getValueSize();
  25174. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  25175. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  25176. valid = false;
  25177. }
  25178. var times = this.times,
  25179. values = this.values,
  25180. nKeys = times.length;
  25181. if ( nKeys === 0 ) {
  25182. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  25183. valid = false;
  25184. }
  25185. var prevTime = null;
  25186. for ( var i = 0; i !== nKeys; i ++ ) {
  25187. var currTime = times[ i ];
  25188. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  25189. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  25190. valid = false;
  25191. break;
  25192. }
  25193. if ( prevTime !== null && prevTime > currTime ) {
  25194. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  25195. valid = false;
  25196. break;
  25197. }
  25198. prevTime = currTime;
  25199. }
  25200. if ( values !== undefined ) {
  25201. if ( AnimationUtils.isTypedArray( values ) ) {
  25202. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  25203. var value = values[ i ];
  25204. if ( isNaN( value ) ) {
  25205. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  25206. valid = false;
  25207. break;
  25208. }
  25209. }
  25210. }
  25211. }
  25212. return valid;
  25213. },
  25214. // removes equivalent sequential keys as common in morph target sequences
  25215. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  25216. optimize: function () {
  25217. var times = this.times,
  25218. values = this.values,
  25219. stride = this.getValueSize(),
  25220. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  25221. writeIndex = 1,
  25222. lastIndex = times.length - 1;
  25223. for ( var i = 1; i < lastIndex; ++ i ) {
  25224. var keep = false;
  25225. var time = times[ i ];
  25226. var timeNext = times[ i + 1 ];
  25227. // remove adjacent keyframes scheduled at the same time
  25228. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  25229. if ( ! smoothInterpolation ) {
  25230. // remove unnecessary keyframes same as their neighbors
  25231. var offset = i * stride,
  25232. offsetP = offset - stride,
  25233. offsetN = offset + stride;
  25234. for ( var j = 0; j !== stride; ++ j ) {
  25235. var value = values[ offset + j ];
  25236. if ( value !== values[ offsetP + j ] ||
  25237. value !== values[ offsetN + j ] ) {
  25238. keep = true;
  25239. break;
  25240. }
  25241. }
  25242. } else {
  25243. keep = true;
  25244. }
  25245. }
  25246. // in-place compaction
  25247. if ( keep ) {
  25248. if ( i !== writeIndex ) {
  25249. times[ writeIndex ] = times[ i ];
  25250. var readOffset = i * stride,
  25251. writeOffset = writeIndex * stride;
  25252. for ( var j = 0; j !== stride; ++ j ) {
  25253. values[ writeOffset + j ] = values[ readOffset + j ];
  25254. }
  25255. }
  25256. ++ writeIndex;
  25257. }
  25258. }
  25259. // flush last keyframe (compaction looks ahead)
  25260. if ( lastIndex > 0 ) {
  25261. times[ writeIndex ] = times[ lastIndex ];
  25262. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  25263. values[ writeOffset + j ] = values[ readOffset + j ];
  25264. }
  25265. ++ writeIndex;
  25266. }
  25267. if ( writeIndex !== times.length ) {
  25268. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  25269. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  25270. }
  25271. return this;
  25272. }
  25273. } );
  25274. /**
  25275. *
  25276. * A Track of Boolean keyframe values.
  25277. *
  25278. *
  25279. * @author Ben Houston / http://clara.io/
  25280. * @author David Sarno / http://lighthaus.us/
  25281. * @author tschw
  25282. */
  25283. function BooleanKeyframeTrack( name, times, values ) {
  25284. KeyframeTrack.call( this, name, times, values );
  25285. }
  25286. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  25287. constructor: BooleanKeyframeTrack,
  25288. ValueTypeName: 'bool',
  25289. ValueBufferType: Array,
  25290. DefaultInterpolation: InterpolateDiscrete,
  25291. InterpolantFactoryMethodLinear: undefined,
  25292. InterpolantFactoryMethodSmooth: undefined
  25293. // Note: Actually this track could have a optimized / compressed
  25294. // representation of a single value and a custom interpolant that
  25295. // computes "firstValue ^ isOdd( index )".
  25296. } );
  25297. /**
  25298. *
  25299. * A Track of keyframe values that represent color.
  25300. *
  25301. *
  25302. * @author Ben Houston / http://clara.io/
  25303. * @author David Sarno / http://lighthaus.us/
  25304. * @author tschw
  25305. */
  25306. function ColorKeyframeTrack( name, times, values, interpolation ) {
  25307. KeyframeTrack.call( this, name, times, values, interpolation );
  25308. }
  25309. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  25310. constructor: ColorKeyframeTrack,
  25311. ValueTypeName: 'color'
  25312. // ValueBufferType is inherited
  25313. // DefaultInterpolation is inherited
  25314. // Note: Very basic implementation and nothing special yet.
  25315. // However, this is the place for color space parameterization.
  25316. } );
  25317. /**
  25318. *
  25319. * A Track of numeric keyframe values.
  25320. *
  25321. * @author Ben Houston / http://clara.io/
  25322. * @author David Sarno / http://lighthaus.us/
  25323. * @author tschw
  25324. */
  25325. function NumberKeyframeTrack( name, times, values, interpolation ) {
  25326. KeyframeTrack.call( this, name, times, values, interpolation );
  25327. }
  25328. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  25329. constructor: NumberKeyframeTrack,
  25330. ValueTypeName: 'number'
  25331. // ValueBufferType is inherited
  25332. // DefaultInterpolation is inherited
  25333. } );
  25334. /**
  25335. * Spherical linear unit quaternion interpolant.
  25336. *
  25337. * @author tschw
  25338. */
  25339. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25340. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  25341. }
  25342. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  25343. constructor: QuaternionLinearInterpolant,
  25344. interpolate_: function ( i1, t0, t, t1 ) {
  25345. var result = this.resultBuffer,
  25346. values = this.sampleValues,
  25347. stride = this.valueSize,
  25348. offset = i1 * stride,
  25349. alpha = ( t - t0 ) / ( t1 - t0 );
  25350. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  25351. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  25352. }
  25353. return result;
  25354. }
  25355. } );
  25356. /**
  25357. *
  25358. * A Track of quaternion keyframe values.
  25359. *
  25360. * @author Ben Houston / http://clara.io/
  25361. * @author David Sarno / http://lighthaus.us/
  25362. * @author tschw
  25363. */
  25364. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  25365. KeyframeTrack.call( this, name, times, values, interpolation );
  25366. }
  25367. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  25368. constructor: QuaternionKeyframeTrack,
  25369. ValueTypeName: 'quaternion',
  25370. // ValueBufferType is inherited
  25371. DefaultInterpolation: InterpolateLinear,
  25372. InterpolantFactoryMethodLinear: function ( result ) {
  25373. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25374. },
  25375. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  25376. } );
  25377. /**
  25378. *
  25379. * A Track that interpolates Strings
  25380. *
  25381. *
  25382. * @author Ben Houston / http://clara.io/
  25383. * @author David Sarno / http://lighthaus.us/
  25384. * @author tschw
  25385. */
  25386. function StringKeyframeTrack( name, times, values, interpolation ) {
  25387. KeyframeTrack.call( this, name, times, values, interpolation );
  25388. }
  25389. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  25390. constructor: StringKeyframeTrack,
  25391. ValueTypeName: 'string',
  25392. ValueBufferType: Array,
  25393. DefaultInterpolation: InterpolateDiscrete,
  25394. InterpolantFactoryMethodLinear: undefined,
  25395. InterpolantFactoryMethodSmooth: undefined
  25396. } );
  25397. /**
  25398. *
  25399. * A Track of vectored keyframe values.
  25400. *
  25401. *
  25402. * @author Ben Houston / http://clara.io/
  25403. * @author David Sarno / http://lighthaus.us/
  25404. * @author tschw
  25405. */
  25406. function VectorKeyframeTrack( name, times, values, interpolation ) {
  25407. KeyframeTrack.call( this, name, times, values, interpolation );
  25408. }
  25409. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  25410. constructor: VectorKeyframeTrack,
  25411. ValueTypeName: 'vector'
  25412. // ValueBufferType is inherited
  25413. // DefaultInterpolation is inherited
  25414. } );
  25415. /**
  25416. *
  25417. * Reusable set of Tracks that represent an animation.
  25418. *
  25419. * @author Ben Houston / http://clara.io/
  25420. * @author David Sarno / http://lighthaus.us/
  25421. */
  25422. function AnimationClip( name, duration, tracks ) {
  25423. this.name = name;
  25424. this.tracks = tracks;
  25425. this.duration = ( duration !== undefined ) ? duration : - 1;
  25426. this.uuid = _Math.generateUUID();
  25427. // this means it should figure out its duration by scanning the tracks
  25428. if ( this.duration < 0 ) {
  25429. this.resetDuration();
  25430. }
  25431. }
  25432. function getTrackTypeForValueTypeName( typeName ) {
  25433. switch ( typeName.toLowerCase() ) {
  25434. case 'scalar':
  25435. case 'double':
  25436. case 'float':
  25437. case 'number':
  25438. case 'integer':
  25439. return NumberKeyframeTrack;
  25440. case 'vector':
  25441. case 'vector2':
  25442. case 'vector3':
  25443. case 'vector4':
  25444. return VectorKeyframeTrack;
  25445. case 'color':
  25446. return ColorKeyframeTrack;
  25447. case 'quaternion':
  25448. return QuaternionKeyframeTrack;
  25449. case 'bool':
  25450. case 'boolean':
  25451. return BooleanKeyframeTrack;
  25452. case 'string':
  25453. return StringKeyframeTrack;
  25454. }
  25455. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  25456. }
  25457. function parseKeyframeTrack( json ) {
  25458. if ( json.type === undefined ) {
  25459. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  25460. }
  25461. var trackType = getTrackTypeForValueTypeName( json.type );
  25462. if ( json.times === undefined ) {
  25463. var times = [], values = [];
  25464. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  25465. json.times = times;
  25466. json.values = values;
  25467. }
  25468. // derived classes can define a static parse method
  25469. if ( trackType.parse !== undefined ) {
  25470. return trackType.parse( json );
  25471. } else {
  25472. // by default, we assume a constructor compatible with the base
  25473. return new trackType( json.name, json.times, json.values, json.interpolation );
  25474. }
  25475. }
  25476. Object.assign( AnimationClip, {
  25477. parse: function ( json ) {
  25478. var tracks = [],
  25479. jsonTracks = json.tracks,
  25480. frameTime = 1.0 / ( json.fps || 1.0 );
  25481. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  25482. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  25483. }
  25484. return new AnimationClip( json.name, json.duration, tracks );
  25485. },
  25486. toJSON: function ( clip ) {
  25487. var tracks = [],
  25488. clipTracks = clip.tracks;
  25489. var json = {
  25490. 'name': clip.name,
  25491. 'duration': clip.duration,
  25492. 'tracks': tracks,
  25493. 'uuid': clip.uuid
  25494. };
  25495. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25496. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25497. }
  25498. return json;
  25499. },
  25500. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  25501. var numMorphTargets = morphTargetSequence.length;
  25502. var tracks = [];
  25503. for ( var i = 0; i < numMorphTargets; i ++ ) {
  25504. var times = [];
  25505. var values = [];
  25506. times.push(
  25507. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25508. i,
  25509. ( i + 1 ) % numMorphTargets );
  25510. values.push( 0, 1, 0 );
  25511. var order = AnimationUtils.getKeyframeOrder( times );
  25512. times = AnimationUtils.sortedArray( times, 1, order );
  25513. values = AnimationUtils.sortedArray( values, 1, order );
  25514. // if there is a key at the first frame, duplicate it as the
  25515. // last frame as well for perfect loop.
  25516. if ( ! noLoop && times[ 0 ] === 0 ) {
  25517. times.push( numMorphTargets );
  25518. values.push( values[ 0 ] );
  25519. }
  25520. tracks.push(
  25521. new NumberKeyframeTrack(
  25522. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25523. times, values
  25524. ).scale( 1.0 / fps ) );
  25525. }
  25526. return new AnimationClip( name, - 1, tracks );
  25527. },
  25528. findByName: function ( objectOrClipArray, name ) {
  25529. var clipArray = objectOrClipArray;
  25530. if ( ! Array.isArray( objectOrClipArray ) ) {
  25531. var o = objectOrClipArray;
  25532. clipArray = o.geometry && o.geometry.animations || o.animations;
  25533. }
  25534. for ( var i = 0; i < clipArray.length; i ++ ) {
  25535. if ( clipArray[ i ].name === name ) {
  25536. return clipArray[ i ];
  25537. }
  25538. }
  25539. return null;
  25540. },
  25541. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  25542. var animationToMorphTargets = {};
  25543. // tested with https://regex101.com/ on trick sequences
  25544. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25545. var pattern = /^([\w-]*?)([\d]+)$/;
  25546. // sort morph target names into animation groups based
  25547. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25548. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  25549. var morphTarget = morphTargets[ i ];
  25550. var parts = morphTarget.name.match( pattern );
  25551. if ( parts && parts.length > 1 ) {
  25552. var name = parts[ 1 ];
  25553. var animationMorphTargets = animationToMorphTargets[ name ];
  25554. if ( ! animationMorphTargets ) {
  25555. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25556. }
  25557. animationMorphTargets.push( morphTarget );
  25558. }
  25559. }
  25560. var clips = [];
  25561. for ( var name in animationToMorphTargets ) {
  25562. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25563. }
  25564. return clips;
  25565. },
  25566. // parse the animation.hierarchy format
  25567. parseAnimation: function ( animation, bones ) {
  25568. if ( ! animation ) {
  25569. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25570. return null;
  25571. }
  25572. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25573. // only return track if there are actually keys.
  25574. if ( animationKeys.length !== 0 ) {
  25575. var times = [];
  25576. var values = [];
  25577. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  25578. // empty keys are filtered out, so check again
  25579. if ( times.length !== 0 ) {
  25580. destTracks.push( new trackType( trackName, times, values ) );
  25581. }
  25582. }
  25583. };
  25584. var tracks = [];
  25585. var clipName = animation.name || 'default';
  25586. // automatic length determination in AnimationClip.
  25587. var duration = animation.length || - 1;
  25588. var fps = animation.fps || 30;
  25589. var hierarchyTracks = animation.hierarchy || [];
  25590. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  25591. var animationKeys = hierarchyTracks[ h ].keys;
  25592. // skip empty tracks
  25593. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25594. // process morph targets
  25595. if ( animationKeys[ 0 ].morphTargets ) {
  25596. // figure out all morph targets used in this track
  25597. var morphTargetNames = {};
  25598. for ( var k = 0; k < animationKeys.length; k ++ ) {
  25599. if ( animationKeys[ k ].morphTargets ) {
  25600. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25601. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25602. }
  25603. }
  25604. }
  25605. // create a track for each morph target with all zero
  25606. // morphTargetInfluences except for the keys in which
  25607. // the morphTarget is named.
  25608. for ( var morphTargetName in morphTargetNames ) {
  25609. var times = [];
  25610. var values = [];
  25611. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  25612. var animationKey = animationKeys[ k ];
  25613. times.push( animationKey.time );
  25614. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  25615. }
  25616. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  25617. }
  25618. duration = morphTargetNames.length * ( fps || 1.0 );
  25619. } else {
  25620. // ...assume skeletal animation
  25621. var boneName = '.bones[' + bones[ h ].name + ']';
  25622. addNonemptyTrack(
  25623. VectorKeyframeTrack, boneName + '.position',
  25624. animationKeys, 'pos', tracks );
  25625. addNonemptyTrack(
  25626. QuaternionKeyframeTrack, boneName + '.quaternion',
  25627. animationKeys, 'rot', tracks );
  25628. addNonemptyTrack(
  25629. VectorKeyframeTrack, boneName + '.scale',
  25630. animationKeys, 'scl', tracks );
  25631. }
  25632. }
  25633. if ( tracks.length === 0 ) {
  25634. return null;
  25635. }
  25636. var clip = new AnimationClip( clipName, duration, tracks );
  25637. return clip;
  25638. }
  25639. } );
  25640. Object.assign( AnimationClip.prototype, {
  25641. resetDuration: function () {
  25642. var tracks = this.tracks, duration = 0;
  25643. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  25644. var track = this.tracks[ i ];
  25645. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  25646. }
  25647. this.duration = duration;
  25648. return this;
  25649. },
  25650. trim: function () {
  25651. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25652. this.tracks[ i ].trim( 0, this.duration );
  25653. }
  25654. return this;
  25655. },
  25656. validate: function () {
  25657. var valid = true;
  25658. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25659. valid = valid && this.tracks[ i ].validate();
  25660. }
  25661. return valid;
  25662. },
  25663. optimize: function () {
  25664. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25665. this.tracks[ i ].optimize();
  25666. }
  25667. return this;
  25668. }
  25669. } );
  25670. /**
  25671. * @author mrdoob / http://mrdoob.com/
  25672. */
  25673. function MaterialLoader( manager ) {
  25674. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25675. this.textures = {};
  25676. }
  25677. Object.assign( MaterialLoader.prototype, {
  25678. load: function ( url, onLoad, onProgress, onError ) {
  25679. var scope = this;
  25680. var loader = new FileLoader( scope.manager );
  25681. loader.load( url, function ( text ) {
  25682. onLoad( scope.parse( JSON.parse( text ) ) );
  25683. }, onProgress, onError );
  25684. },
  25685. setTextures: function ( value ) {
  25686. this.textures = value;
  25687. },
  25688. parse: function ( json ) {
  25689. var textures = this.textures;
  25690. function getTexture( name ) {
  25691. if ( textures[ name ] === undefined ) {
  25692. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25693. }
  25694. return textures[ name ];
  25695. }
  25696. var material = new Materials[ json.type ]();
  25697. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25698. if ( json.name !== undefined ) material.name = json.name;
  25699. if ( json.color !== undefined ) material.color.setHex( json.color );
  25700. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25701. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25702. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25703. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  25704. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25705. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  25706. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  25707. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  25708. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25709. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25710. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  25711. if ( json.fog !== undefined ) material.fog = json.fog;
  25712. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25713. if ( json.blending !== undefined ) material.blending = json.blending;
  25714. if ( json.side !== undefined ) material.side = json.side;
  25715. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25716. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25717. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25718. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25719. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25720. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25721. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25722. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25723. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25724. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25725. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25726. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25727. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25728. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25729. if ( json.scale !== undefined ) material.scale = json.scale;
  25730. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25731. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25732. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25733. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  25734. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  25735. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25736. if ( json.visible !== undefined ) material.visible = json.visible;
  25737. if ( json.userData !== undefined ) material.userData = json.userData;
  25738. // Deprecated
  25739. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  25740. // for PointsMaterial
  25741. if ( json.size !== undefined ) material.size = json.size;
  25742. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25743. // maps
  25744. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25745. if ( json.alphaMap !== undefined ) {
  25746. material.alphaMap = getTexture( json.alphaMap );
  25747. material.transparent = true;
  25748. }
  25749. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25750. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25751. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25752. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25753. if ( json.normalScale !== undefined ) {
  25754. var normalScale = json.normalScale;
  25755. if ( Array.isArray( normalScale ) === false ) {
  25756. // Blender exporter used to export a scalar. See #7459
  25757. normalScale = [ normalScale, normalScale ];
  25758. }
  25759. material.normalScale = new Vector2().fromArray( normalScale );
  25760. }
  25761. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25762. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25763. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25764. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25765. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25766. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25767. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25768. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25769. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25770. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25771. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25772. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25773. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25774. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25775. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25776. return material;
  25777. }
  25778. } );
  25779. /**
  25780. * @author mrdoob / http://mrdoob.com/
  25781. */
  25782. function BufferGeometryLoader( manager ) {
  25783. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25784. }
  25785. Object.assign( BufferGeometryLoader.prototype, {
  25786. load: function ( url, onLoad, onProgress, onError ) {
  25787. var scope = this;
  25788. var loader = new FileLoader( scope.manager );
  25789. loader.load( url, function ( text ) {
  25790. onLoad( scope.parse( JSON.parse( text ) ) );
  25791. }, onProgress, onError );
  25792. },
  25793. parse: function ( json ) {
  25794. var geometry = new BufferGeometry();
  25795. var index = json.data.index;
  25796. if ( index !== undefined ) {
  25797. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  25798. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25799. }
  25800. var attributes = json.data.attributes;
  25801. for ( var key in attributes ) {
  25802. var attribute = attributes[ key ];
  25803. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  25804. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  25805. }
  25806. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25807. if ( groups !== undefined ) {
  25808. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  25809. var group = groups[ i ];
  25810. geometry.addGroup( group.start, group.count, group.materialIndex );
  25811. }
  25812. }
  25813. var boundingSphere = json.data.boundingSphere;
  25814. if ( boundingSphere !== undefined ) {
  25815. var center = new Vector3();
  25816. if ( boundingSphere.center !== undefined ) {
  25817. center.fromArray( boundingSphere.center );
  25818. }
  25819. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25820. }
  25821. return geometry;
  25822. }
  25823. } );
  25824. var TYPED_ARRAYS = {
  25825. Int8Array: Int8Array,
  25826. Uint8Array: Uint8Array,
  25827. // Workaround for IE11 pre KB2929437. See #11440
  25828. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  25829. Int16Array: Int16Array,
  25830. Uint16Array: Uint16Array,
  25831. Int32Array: Int32Array,
  25832. Uint32Array: Uint32Array,
  25833. Float32Array: Float32Array,
  25834. Float64Array: Float64Array
  25835. };
  25836. /**
  25837. * @author alteredq / http://alteredqualia.com/
  25838. */
  25839. function Loader() {}
  25840. Loader.Handlers = {
  25841. handlers: [],
  25842. add: function ( regex, loader ) {
  25843. this.handlers.push( regex, loader );
  25844. },
  25845. get: function ( file ) {
  25846. var handlers = this.handlers;
  25847. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  25848. var regex = handlers[ i ];
  25849. var loader = handlers[ i + 1 ];
  25850. if ( regex.test( file ) ) {
  25851. return loader;
  25852. }
  25853. }
  25854. return null;
  25855. }
  25856. };
  25857. Object.assign( Loader.prototype, {
  25858. crossOrigin: 'anonymous',
  25859. onLoadStart: function () {},
  25860. onLoadProgress: function () {},
  25861. onLoadComplete: function () {},
  25862. initMaterials: function ( materials, texturePath, crossOrigin ) {
  25863. var array = [];
  25864. for ( var i = 0; i < materials.length; ++ i ) {
  25865. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  25866. }
  25867. return array;
  25868. },
  25869. createMaterial: ( function () {
  25870. var BlendingMode = {
  25871. NoBlending: NoBlending,
  25872. NormalBlending: NormalBlending,
  25873. AdditiveBlending: AdditiveBlending,
  25874. SubtractiveBlending: SubtractiveBlending,
  25875. MultiplyBlending: MultiplyBlending,
  25876. CustomBlending: CustomBlending
  25877. };
  25878. var color = new Color();
  25879. var textureLoader = new TextureLoader();
  25880. var materialLoader = new MaterialLoader();
  25881. return function createMaterial( m, texturePath, crossOrigin ) {
  25882. // convert from old material format
  25883. var textures = {};
  25884. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  25885. var fullPath = texturePath + path;
  25886. var loader = Loader.Handlers.get( fullPath );
  25887. var texture;
  25888. if ( loader !== null ) {
  25889. texture = loader.load( fullPath );
  25890. } else {
  25891. textureLoader.setCrossOrigin( crossOrigin );
  25892. texture = textureLoader.load( fullPath );
  25893. }
  25894. if ( repeat !== undefined ) {
  25895. texture.repeat.fromArray( repeat );
  25896. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  25897. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  25898. }
  25899. if ( offset !== undefined ) {
  25900. texture.offset.fromArray( offset );
  25901. }
  25902. if ( wrap !== undefined ) {
  25903. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  25904. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  25905. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  25906. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  25907. }
  25908. if ( anisotropy !== undefined ) {
  25909. texture.anisotropy = anisotropy;
  25910. }
  25911. var uuid = _Math.generateUUID();
  25912. textures[ uuid ] = texture;
  25913. return uuid;
  25914. }
  25915. //
  25916. var json = {
  25917. uuid: _Math.generateUUID(),
  25918. type: 'MeshLambertMaterial'
  25919. };
  25920. for ( var name in m ) {
  25921. var value = m[ name ];
  25922. switch ( name ) {
  25923. case 'DbgColor':
  25924. case 'DbgIndex':
  25925. case 'opticalDensity':
  25926. case 'illumination':
  25927. break;
  25928. case 'DbgName':
  25929. json.name = value;
  25930. break;
  25931. case 'blending':
  25932. json.blending = BlendingMode[ value ];
  25933. break;
  25934. case 'colorAmbient':
  25935. case 'mapAmbient':
  25936. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  25937. break;
  25938. case 'colorDiffuse':
  25939. json.color = color.fromArray( value ).getHex();
  25940. break;
  25941. case 'colorSpecular':
  25942. json.specular = color.fromArray( value ).getHex();
  25943. break;
  25944. case 'colorEmissive':
  25945. json.emissive = color.fromArray( value ).getHex();
  25946. break;
  25947. case 'specularCoef':
  25948. json.shininess = value;
  25949. break;
  25950. case 'shading':
  25951. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  25952. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  25953. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  25954. break;
  25955. case 'mapDiffuse':
  25956. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  25957. break;
  25958. case 'mapDiffuseRepeat':
  25959. case 'mapDiffuseOffset':
  25960. case 'mapDiffuseWrap':
  25961. case 'mapDiffuseAnisotropy':
  25962. break;
  25963. case 'mapEmissive':
  25964. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  25965. break;
  25966. case 'mapEmissiveRepeat':
  25967. case 'mapEmissiveOffset':
  25968. case 'mapEmissiveWrap':
  25969. case 'mapEmissiveAnisotropy':
  25970. break;
  25971. case 'mapLight':
  25972. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  25973. break;
  25974. case 'mapLightRepeat':
  25975. case 'mapLightOffset':
  25976. case 'mapLightWrap':
  25977. case 'mapLightAnisotropy':
  25978. break;
  25979. case 'mapAO':
  25980. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  25981. break;
  25982. case 'mapAORepeat':
  25983. case 'mapAOOffset':
  25984. case 'mapAOWrap':
  25985. case 'mapAOAnisotropy':
  25986. break;
  25987. case 'mapBump':
  25988. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  25989. break;
  25990. case 'mapBumpScale':
  25991. json.bumpScale = value;
  25992. break;
  25993. case 'mapBumpRepeat':
  25994. case 'mapBumpOffset':
  25995. case 'mapBumpWrap':
  25996. case 'mapBumpAnisotropy':
  25997. break;
  25998. case 'mapNormal':
  25999. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  26000. break;
  26001. case 'mapNormalFactor':
  26002. json.normalScale = value;
  26003. break;
  26004. case 'mapNormalRepeat':
  26005. case 'mapNormalOffset':
  26006. case 'mapNormalWrap':
  26007. case 'mapNormalAnisotropy':
  26008. break;
  26009. case 'mapSpecular':
  26010. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  26011. break;
  26012. case 'mapSpecularRepeat':
  26013. case 'mapSpecularOffset':
  26014. case 'mapSpecularWrap':
  26015. case 'mapSpecularAnisotropy':
  26016. break;
  26017. case 'mapMetalness':
  26018. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  26019. break;
  26020. case 'mapMetalnessRepeat':
  26021. case 'mapMetalnessOffset':
  26022. case 'mapMetalnessWrap':
  26023. case 'mapMetalnessAnisotropy':
  26024. break;
  26025. case 'mapRoughness':
  26026. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  26027. break;
  26028. case 'mapRoughnessRepeat':
  26029. case 'mapRoughnessOffset':
  26030. case 'mapRoughnessWrap':
  26031. case 'mapRoughnessAnisotropy':
  26032. break;
  26033. case 'mapAlpha':
  26034. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  26035. break;
  26036. case 'mapAlphaRepeat':
  26037. case 'mapAlphaOffset':
  26038. case 'mapAlphaWrap':
  26039. case 'mapAlphaAnisotropy':
  26040. break;
  26041. case 'flipSided':
  26042. json.side = BackSide;
  26043. break;
  26044. case 'doubleSided':
  26045. json.side = DoubleSide;
  26046. break;
  26047. case 'transparency':
  26048. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  26049. json.opacity = value;
  26050. break;
  26051. case 'depthTest':
  26052. case 'depthWrite':
  26053. case 'colorWrite':
  26054. case 'opacity':
  26055. case 'reflectivity':
  26056. case 'transparent':
  26057. case 'visible':
  26058. case 'wireframe':
  26059. json[ name ] = value;
  26060. break;
  26061. case 'vertexColors':
  26062. if ( value === true ) json.vertexColors = VertexColors;
  26063. if ( value === 'face' ) json.vertexColors = FaceColors;
  26064. break;
  26065. default:
  26066. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  26067. break;
  26068. }
  26069. }
  26070. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  26071. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  26072. if ( json.opacity < 1 ) json.transparent = true;
  26073. materialLoader.setTextures( textures );
  26074. return materialLoader.parse( json );
  26075. };
  26076. } )()
  26077. } );
  26078. /**
  26079. * @author Don McCurdy / https://www.donmccurdy.com
  26080. */
  26081. var LoaderUtils = {
  26082. decodeText: function ( array ) {
  26083. if ( typeof TextDecoder !== 'undefined' ) {
  26084. return new TextDecoder().decode( array );
  26085. }
  26086. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  26087. // throws a "maximum call stack size exceeded" error for large arrays.
  26088. var s = '';
  26089. for ( var i = 0, il = array.length; i < il; i ++ ) {
  26090. // Implicitly assumes little-endian.
  26091. s += String.fromCharCode( array[ i ] );
  26092. }
  26093. // Merges multi-byte utf-8 characters.
  26094. return decodeURIComponent( escape( s ) );
  26095. },
  26096. extractUrlBase: function ( url ) {
  26097. var index = url.lastIndexOf( '/' );
  26098. if ( index === - 1 ) return './';
  26099. return url.substr( 0, index + 1 );
  26100. }
  26101. };
  26102. /**
  26103. * @author mrdoob / http://mrdoob.com/
  26104. * @author alteredq / http://alteredqualia.com/
  26105. */
  26106. function JSONLoader( manager ) {
  26107. if ( typeof manager === 'boolean' ) {
  26108. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  26109. manager = undefined;
  26110. }
  26111. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26112. this.withCredentials = false;
  26113. }
  26114. Object.assign( JSONLoader.prototype, {
  26115. crossOrigin: 'anonymous',
  26116. load: function ( url, onLoad, onProgress, onError ) {
  26117. var scope = this;
  26118. var texturePath = this.texturePath && ( typeof this.texturePath === 'string' ) ? this.texturePath : LoaderUtils.extractUrlBase( url );
  26119. var loader = new FileLoader( this.manager );
  26120. loader.setWithCredentials( this.withCredentials );
  26121. loader.load( url, function ( text ) {
  26122. var json = JSON.parse( text );
  26123. var metadata = json.metadata;
  26124. if ( metadata !== undefined ) {
  26125. var type = metadata.type;
  26126. if ( type !== undefined ) {
  26127. if ( type.toLowerCase() === 'object' ) {
  26128. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  26129. return;
  26130. }
  26131. }
  26132. }
  26133. var object = scope.parse( json, texturePath );
  26134. onLoad( object.geometry, object.materials );
  26135. }, onProgress, onError );
  26136. },
  26137. setCrossOrigin: function ( value ) {
  26138. this.crossOrigin = value;
  26139. return this;
  26140. },
  26141. setTexturePath: function ( value ) {
  26142. this.texturePath = value;
  26143. return this;
  26144. },
  26145. parse: ( function () {
  26146. function parseModel( json, geometry ) {
  26147. function isBitSet( value, position ) {
  26148. return value & ( 1 << position );
  26149. }
  26150. var i, j, fi,
  26151. offset, zLength,
  26152. colorIndex, normalIndex, uvIndex, materialIndex,
  26153. type,
  26154. isQuad,
  26155. hasMaterial,
  26156. hasFaceVertexUv,
  26157. hasFaceNormal, hasFaceVertexNormal,
  26158. hasFaceColor, hasFaceVertexColor,
  26159. vertex, face, faceA, faceB, hex, normal,
  26160. uvLayer, uv, u, v,
  26161. faces = json.faces,
  26162. vertices = json.vertices,
  26163. normals = json.normals,
  26164. colors = json.colors,
  26165. scale = json.scale,
  26166. nUvLayers = 0;
  26167. if ( json.uvs !== undefined ) {
  26168. // disregard empty arrays
  26169. for ( i = 0; i < json.uvs.length; i ++ ) {
  26170. if ( json.uvs[ i ].length ) nUvLayers ++;
  26171. }
  26172. for ( i = 0; i < nUvLayers; i ++ ) {
  26173. geometry.faceVertexUvs[ i ] = [];
  26174. }
  26175. }
  26176. offset = 0;
  26177. zLength = vertices.length;
  26178. while ( offset < zLength ) {
  26179. vertex = new Vector3();
  26180. vertex.x = vertices[ offset ++ ] * scale;
  26181. vertex.y = vertices[ offset ++ ] * scale;
  26182. vertex.z = vertices[ offset ++ ] * scale;
  26183. geometry.vertices.push( vertex );
  26184. }
  26185. offset = 0;
  26186. zLength = faces.length;
  26187. while ( offset < zLength ) {
  26188. type = faces[ offset ++ ];
  26189. isQuad = isBitSet( type, 0 );
  26190. hasMaterial = isBitSet( type, 1 );
  26191. hasFaceVertexUv = isBitSet( type, 3 );
  26192. hasFaceNormal = isBitSet( type, 4 );
  26193. hasFaceVertexNormal = isBitSet( type, 5 );
  26194. hasFaceColor = isBitSet( type, 6 );
  26195. hasFaceVertexColor = isBitSet( type, 7 );
  26196. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  26197. if ( isQuad ) {
  26198. faceA = new Face3();
  26199. faceA.a = faces[ offset ];
  26200. faceA.b = faces[ offset + 1 ];
  26201. faceA.c = faces[ offset + 3 ];
  26202. faceB = new Face3();
  26203. faceB.a = faces[ offset + 1 ];
  26204. faceB.b = faces[ offset + 2 ];
  26205. faceB.c = faces[ offset + 3 ];
  26206. offset += 4;
  26207. if ( hasMaterial ) {
  26208. materialIndex = faces[ offset ++ ];
  26209. faceA.materialIndex = materialIndex;
  26210. faceB.materialIndex = materialIndex;
  26211. }
  26212. // to get face <=> uv index correspondence
  26213. fi = geometry.faces.length;
  26214. if ( hasFaceVertexUv ) {
  26215. for ( i = 0; i < nUvLayers; i ++ ) {
  26216. uvLayer = json.uvs[ i ];
  26217. geometry.faceVertexUvs[ i ][ fi ] = [];
  26218. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  26219. for ( j = 0; j < 4; j ++ ) {
  26220. uvIndex = faces[ offset ++ ];
  26221. u = uvLayer[ uvIndex * 2 ];
  26222. v = uvLayer[ uvIndex * 2 + 1 ];
  26223. uv = new Vector2( u, v );
  26224. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  26225. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  26226. }
  26227. }
  26228. }
  26229. if ( hasFaceNormal ) {
  26230. normalIndex = faces[ offset ++ ] * 3;
  26231. faceA.normal.set(
  26232. normals[ normalIndex ++ ],
  26233. normals[ normalIndex ++ ],
  26234. normals[ normalIndex ]
  26235. );
  26236. faceB.normal.copy( faceA.normal );
  26237. }
  26238. if ( hasFaceVertexNormal ) {
  26239. for ( i = 0; i < 4; i ++ ) {
  26240. normalIndex = faces[ offset ++ ] * 3;
  26241. normal = new Vector3(
  26242. normals[ normalIndex ++ ],
  26243. normals[ normalIndex ++ ],
  26244. normals[ normalIndex ]
  26245. );
  26246. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  26247. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  26248. }
  26249. }
  26250. if ( hasFaceColor ) {
  26251. colorIndex = faces[ offset ++ ];
  26252. hex = colors[ colorIndex ];
  26253. faceA.color.setHex( hex );
  26254. faceB.color.setHex( hex );
  26255. }
  26256. if ( hasFaceVertexColor ) {
  26257. for ( i = 0; i < 4; i ++ ) {
  26258. colorIndex = faces[ offset ++ ];
  26259. hex = colors[ colorIndex ];
  26260. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  26261. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  26262. }
  26263. }
  26264. geometry.faces.push( faceA );
  26265. geometry.faces.push( faceB );
  26266. } else {
  26267. face = new Face3();
  26268. face.a = faces[ offset ++ ];
  26269. face.b = faces[ offset ++ ];
  26270. face.c = faces[ offset ++ ];
  26271. if ( hasMaterial ) {
  26272. materialIndex = faces[ offset ++ ];
  26273. face.materialIndex = materialIndex;
  26274. }
  26275. // to get face <=> uv index correspondence
  26276. fi = geometry.faces.length;
  26277. if ( hasFaceVertexUv ) {
  26278. for ( i = 0; i < nUvLayers; i ++ ) {
  26279. uvLayer = json.uvs[ i ];
  26280. geometry.faceVertexUvs[ i ][ fi ] = [];
  26281. for ( j = 0; j < 3; j ++ ) {
  26282. uvIndex = faces[ offset ++ ];
  26283. u = uvLayer[ uvIndex * 2 ];
  26284. v = uvLayer[ uvIndex * 2 + 1 ];
  26285. uv = new Vector2( u, v );
  26286. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  26287. }
  26288. }
  26289. }
  26290. if ( hasFaceNormal ) {
  26291. normalIndex = faces[ offset ++ ] * 3;
  26292. face.normal.set(
  26293. normals[ normalIndex ++ ],
  26294. normals[ normalIndex ++ ],
  26295. normals[ normalIndex ]
  26296. );
  26297. }
  26298. if ( hasFaceVertexNormal ) {
  26299. for ( i = 0; i < 3; i ++ ) {
  26300. normalIndex = faces[ offset ++ ] * 3;
  26301. normal = new Vector3(
  26302. normals[ normalIndex ++ ],
  26303. normals[ normalIndex ++ ],
  26304. normals[ normalIndex ]
  26305. );
  26306. face.vertexNormals.push( normal );
  26307. }
  26308. }
  26309. if ( hasFaceColor ) {
  26310. colorIndex = faces[ offset ++ ];
  26311. face.color.setHex( colors[ colorIndex ] );
  26312. }
  26313. if ( hasFaceVertexColor ) {
  26314. for ( i = 0; i < 3; i ++ ) {
  26315. colorIndex = faces[ offset ++ ];
  26316. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  26317. }
  26318. }
  26319. geometry.faces.push( face );
  26320. }
  26321. }
  26322. }
  26323. function parseSkin( json, geometry ) {
  26324. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  26325. if ( json.skinWeights ) {
  26326. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  26327. var x = json.skinWeights[ i ];
  26328. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  26329. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  26330. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  26331. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  26332. }
  26333. }
  26334. if ( json.skinIndices ) {
  26335. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  26336. var a = json.skinIndices[ i ];
  26337. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  26338. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  26339. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  26340. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  26341. }
  26342. }
  26343. geometry.bones = json.bones;
  26344. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  26345. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  26346. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  26347. }
  26348. }
  26349. function parseMorphing( json, geometry ) {
  26350. var scale = json.scale;
  26351. if ( json.morphTargets !== undefined ) {
  26352. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  26353. geometry.morphTargets[ i ] = {};
  26354. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  26355. geometry.morphTargets[ i ].vertices = [];
  26356. var dstVertices = geometry.morphTargets[ i ].vertices;
  26357. var srcVertices = json.morphTargets[ i ].vertices;
  26358. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  26359. var vertex = new Vector3();
  26360. vertex.x = srcVertices[ v ] * scale;
  26361. vertex.y = srcVertices[ v + 1 ] * scale;
  26362. vertex.z = srcVertices[ v + 2 ] * scale;
  26363. dstVertices.push( vertex );
  26364. }
  26365. }
  26366. }
  26367. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  26368. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  26369. var faces = geometry.faces;
  26370. var morphColors = json.morphColors[ 0 ].colors;
  26371. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  26372. faces[ i ].color.fromArray( morphColors, i * 3 );
  26373. }
  26374. }
  26375. }
  26376. function parseAnimations( json, geometry ) {
  26377. var outputAnimations = [];
  26378. // parse old style Bone/Hierarchy animations
  26379. var animations = [];
  26380. if ( json.animation !== undefined ) {
  26381. animations.push( json.animation );
  26382. }
  26383. if ( json.animations !== undefined ) {
  26384. if ( json.animations.length ) {
  26385. animations = animations.concat( json.animations );
  26386. } else {
  26387. animations.push( json.animations );
  26388. }
  26389. }
  26390. for ( var i = 0; i < animations.length; i ++ ) {
  26391. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  26392. if ( clip ) outputAnimations.push( clip );
  26393. }
  26394. // parse implicit morph animations
  26395. if ( geometry.morphTargets ) {
  26396. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  26397. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  26398. outputAnimations = outputAnimations.concat( morphAnimationClips );
  26399. }
  26400. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  26401. }
  26402. return function parse( json, texturePath ) {
  26403. if ( json.data !== undefined ) {
  26404. // Geometry 4.0 spec
  26405. json = json.data;
  26406. }
  26407. if ( json.scale !== undefined ) {
  26408. json.scale = 1.0 / json.scale;
  26409. } else {
  26410. json.scale = 1.0;
  26411. }
  26412. var geometry = new Geometry();
  26413. parseModel( json, geometry );
  26414. parseSkin( json, geometry );
  26415. parseMorphing( json, geometry );
  26416. parseAnimations( json, geometry );
  26417. geometry.computeFaceNormals();
  26418. geometry.computeBoundingSphere();
  26419. if ( json.materials === undefined || json.materials.length === 0 ) {
  26420. return { geometry: geometry };
  26421. } else {
  26422. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  26423. return { geometry: geometry, materials: materials };
  26424. }
  26425. };
  26426. } )()
  26427. } );
  26428. /**
  26429. * @author mrdoob / http://mrdoob.com/
  26430. */
  26431. function ObjectLoader( manager ) {
  26432. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26433. this.texturePath = '';
  26434. }
  26435. Object.assign( ObjectLoader.prototype, {
  26436. crossOrigin: 'anonymous',
  26437. load: function ( url, onLoad, onProgress, onError ) {
  26438. if ( this.texturePath === '' ) {
  26439. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  26440. }
  26441. var scope = this;
  26442. var loader = new FileLoader( scope.manager );
  26443. loader.load( url, function ( text ) {
  26444. var json = null;
  26445. try {
  26446. json = JSON.parse( text );
  26447. } catch ( error ) {
  26448. if ( onError !== undefined ) onError( error );
  26449. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  26450. return;
  26451. }
  26452. var metadata = json.metadata;
  26453. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26454. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  26455. return;
  26456. }
  26457. scope.parse( json, onLoad );
  26458. }, onProgress, onError );
  26459. },
  26460. setTexturePath: function ( value ) {
  26461. this.texturePath = value;
  26462. return this;
  26463. },
  26464. setCrossOrigin: function ( value ) {
  26465. this.crossOrigin = value;
  26466. return this;
  26467. },
  26468. parse: function ( json, onLoad ) {
  26469. var shapes = this.parseShape( json.shapes );
  26470. var geometries = this.parseGeometries( json.geometries, shapes );
  26471. var images = this.parseImages( json.images, function () {
  26472. if ( onLoad !== undefined ) onLoad( object );
  26473. } );
  26474. var textures = this.parseTextures( json.textures, images );
  26475. var materials = this.parseMaterials( json.materials, textures );
  26476. var object = this.parseObject( json.object, geometries, materials );
  26477. if ( json.animations ) {
  26478. object.animations = this.parseAnimations( json.animations );
  26479. }
  26480. if ( json.images === undefined || json.images.length === 0 ) {
  26481. if ( onLoad !== undefined ) onLoad( object );
  26482. }
  26483. return object;
  26484. },
  26485. parseShape: function ( json ) {
  26486. var shapes = {};
  26487. if ( json !== undefined ) {
  26488. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26489. var shape = new Shape().fromJSON( json[ i ] );
  26490. shapes[ shape.uuid ] = shape;
  26491. }
  26492. }
  26493. return shapes;
  26494. },
  26495. parseGeometries: function ( json, shapes ) {
  26496. var geometries = {};
  26497. if ( json !== undefined ) {
  26498. var geometryLoader = new JSONLoader();
  26499. var bufferGeometryLoader = new BufferGeometryLoader();
  26500. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26501. var geometry;
  26502. var data = json[ i ];
  26503. switch ( data.type ) {
  26504. case 'PlaneGeometry':
  26505. case 'PlaneBufferGeometry':
  26506. geometry = new Geometries[ data.type ](
  26507. data.width,
  26508. data.height,
  26509. data.widthSegments,
  26510. data.heightSegments
  26511. );
  26512. break;
  26513. case 'BoxGeometry':
  26514. case 'BoxBufferGeometry':
  26515. case 'CubeGeometry': // backwards compatible
  26516. geometry = new Geometries[ data.type ](
  26517. data.width,
  26518. data.height,
  26519. data.depth,
  26520. data.widthSegments,
  26521. data.heightSegments,
  26522. data.depthSegments
  26523. );
  26524. break;
  26525. case 'CircleGeometry':
  26526. case 'CircleBufferGeometry':
  26527. geometry = new Geometries[ data.type ](
  26528. data.radius,
  26529. data.segments,
  26530. data.thetaStart,
  26531. data.thetaLength
  26532. );
  26533. break;
  26534. case 'CylinderGeometry':
  26535. case 'CylinderBufferGeometry':
  26536. geometry = new Geometries[ data.type ](
  26537. data.radiusTop,
  26538. data.radiusBottom,
  26539. data.height,
  26540. data.radialSegments,
  26541. data.heightSegments,
  26542. data.openEnded,
  26543. data.thetaStart,
  26544. data.thetaLength
  26545. );
  26546. break;
  26547. case 'ConeGeometry':
  26548. case 'ConeBufferGeometry':
  26549. geometry = new Geometries[ data.type ](
  26550. data.radius,
  26551. data.height,
  26552. data.radialSegments,
  26553. data.heightSegments,
  26554. data.openEnded,
  26555. data.thetaStart,
  26556. data.thetaLength
  26557. );
  26558. break;
  26559. case 'SphereGeometry':
  26560. case 'SphereBufferGeometry':
  26561. geometry = new Geometries[ data.type ](
  26562. data.radius,
  26563. data.widthSegments,
  26564. data.heightSegments,
  26565. data.phiStart,
  26566. data.phiLength,
  26567. data.thetaStart,
  26568. data.thetaLength
  26569. );
  26570. break;
  26571. case 'DodecahedronGeometry':
  26572. case 'DodecahedronBufferGeometry':
  26573. case 'IcosahedronGeometry':
  26574. case 'IcosahedronBufferGeometry':
  26575. case 'OctahedronGeometry':
  26576. case 'OctahedronBufferGeometry':
  26577. case 'TetrahedronGeometry':
  26578. case 'TetrahedronBufferGeometry':
  26579. geometry = new Geometries[ data.type ](
  26580. data.radius,
  26581. data.detail
  26582. );
  26583. break;
  26584. case 'RingGeometry':
  26585. case 'RingBufferGeometry':
  26586. geometry = new Geometries[ data.type ](
  26587. data.innerRadius,
  26588. data.outerRadius,
  26589. data.thetaSegments,
  26590. data.phiSegments,
  26591. data.thetaStart,
  26592. data.thetaLength
  26593. );
  26594. break;
  26595. case 'TorusGeometry':
  26596. case 'TorusBufferGeometry':
  26597. geometry = new Geometries[ data.type ](
  26598. data.radius,
  26599. data.tube,
  26600. data.radialSegments,
  26601. data.tubularSegments,
  26602. data.arc
  26603. );
  26604. break;
  26605. case 'TorusKnotGeometry':
  26606. case 'TorusKnotBufferGeometry':
  26607. geometry = new Geometries[ data.type ](
  26608. data.radius,
  26609. data.tube,
  26610. data.tubularSegments,
  26611. data.radialSegments,
  26612. data.p,
  26613. data.q
  26614. );
  26615. break;
  26616. case 'LatheGeometry':
  26617. case 'LatheBufferGeometry':
  26618. geometry = new Geometries[ data.type ](
  26619. data.points,
  26620. data.segments,
  26621. data.phiStart,
  26622. data.phiLength
  26623. );
  26624. break;
  26625. case 'PolyhedronGeometry':
  26626. case 'PolyhedronBufferGeometry':
  26627. geometry = new Geometries[ data.type ](
  26628. data.vertices,
  26629. data.indices,
  26630. data.radius,
  26631. data.details
  26632. );
  26633. break;
  26634. case 'ShapeGeometry':
  26635. case 'ShapeBufferGeometry':
  26636. var geometryShapes = [];
  26637. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26638. var shape = shapes[ data.shapes[ j ] ];
  26639. geometryShapes.push( shape );
  26640. }
  26641. geometry = new Geometries[ data.type ](
  26642. geometryShapes,
  26643. data.curveSegments
  26644. );
  26645. break;
  26646. case 'ExtrudeGeometry':
  26647. case 'ExtrudeBufferGeometry':
  26648. var geometryShapes = [];
  26649. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26650. var shape = shapes[ data.shapes[ j ] ];
  26651. geometryShapes.push( shape );
  26652. }
  26653. var extrudePath = data.options.extrudePath;
  26654. if ( extrudePath !== undefined ) {
  26655. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26656. }
  26657. geometry = new Geometries[ data.type ](
  26658. geometryShapes,
  26659. data.options
  26660. );
  26661. break;
  26662. case 'BufferGeometry':
  26663. geometry = bufferGeometryLoader.parse( data );
  26664. break;
  26665. case 'Geometry':
  26666. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  26667. break;
  26668. default:
  26669. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  26670. continue;
  26671. }
  26672. geometry.uuid = data.uuid;
  26673. if ( data.name !== undefined ) geometry.name = data.name;
  26674. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  26675. geometries[ data.uuid ] = geometry;
  26676. }
  26677. }
  26678. return geometries;
  26679. },
  26680. parseMaterials: function ( json, textures ) {
  26681. var materials = {};
  26682. if ( json !== undefined ) {
  26683. var loader = new MaterialLoader();
  26684. loader.setTextures( textures );
  26685. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26686. var data = json[ i ];
  26687. if ( data.type === 'MultiMaterial' ) {
  26688. // Deprecated
  26689. var array = [];
  26690. for ( var j = 0; j < data.materials.length; j ++ ) {
  26691. array.push( loader.parse( data.materials[ j ] ) );
  26692. }
  26693. materials[ data.uuid ] = array;
  26694. } else {
  26695. materials[ data.uuid ] = loader.parse( data );
  26696. }
  26697. }
  26698. }
  26699. return materials;
  26700. },
  26701. parseAnimations: function ( json ) {
  26702. var animations = [];
  26703. for ( var i = 0; i < json.length; i ++ ) {
  26704. var data = json[ i ];
  26705. var clip = AnimationClip.parse( data );
  26706. if ( data.uuid !== undefined ) clip.uuid = data.uuid;
  26707. animations.push( clip );
  26708. }
  26709. return animations;
  26710. },
  26711. parseImages: function ( json, onLoad ) {
  26712. var scope = this;
  26713. var images = {};
  26714. function loadImage( url ) {
  26715. scope.manager.itemStart( url );
  26716. return loader.load( url, function () {
  26717. scope.manager.itemEnd( url );
  26718. }, undefined, function () {
  26719. scope.manager.itemEnd( url );
  26720. scope.manager.itemError( url );
  26721. } );
  26722. }
  26723. if ( json !== undefined && json.length > 0 ) {
  26724. var manager = new LoadingManager( onLoad );
  26725. var loader = new ImageLoader( manager );
  26726. loader.setCrossOrigin( this.crossOrigin );
  26727. for ( var i = 0, il = json.length; i < il; i ++ ) {
  26728. var image = json[ i ];
  26729. var url = image.url;
  26730. if ( Array.isArray( url ) ) {
  26731. // load array of images e.g CubeTexture
  26732. images[ image.uuid ] = [];
  26733. for ( var j = 0, jl = url.length; j < jl; j ++ ) {
  26734. var currentUrl = url[ j ];
  26735. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.texturePath + currentUrl;
  26736. images[ image.uuid ].push( loadImage( path ) );
  26737. }
  26738. } else {
  26739. // load single image
  26740. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  26741. images[ image.uuid ] = loadImage( path );
  26742. }
  26743. }
  26744. }
  26745. return images;
  26746. },
  26747. parseTextures: function ( json, images ) {
  26748. function parseConstant( value, type ) {
  26749. if ( typeof value === 'number' ) return value;
  26750. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  26751. return type[ value ];
  26752. }
  26753. var textures = {};
  26754. if ( json !== undefined ) {
  26755. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26756. var data = json[ i ];
  26757. if ( data.image === undefined ) {
  26758. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  26759. }
  26760. if ( images[ data.image ] === undefined ) {
  26761. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  26762. }
  26763. var texture;
  26764. if ( Array.isArray( images[ data.image ] ) ) {
  26765. texture = new CubeTexture( images[ data.image ] );
  26766. } else {
  26767. texture = new Texture( images[ data.image ] );
  26768. }
  26769. texture.needsUpdate = true;
  26770. texture.uuid = data.uuid;
  26771. if ( data.name !== undefined ) texture.name = data.name;
  26772. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  26773. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  26774. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  26775. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  26776. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  26777. if ( data.wrap !== undefined ) {
  26778. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  26779. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  26780. }
  26781. if ( data.format !== undefined ) texture.format = data.format;
  26782. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  26783. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  26784. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  26785. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  26786. textures[ data.uuid ] = texture;
  26787. }
  26788. }
  26789. return textures;
  26790. },
  26791. parseObject: function ( data, geometries, materials ) {
  26792. var object;
  26793. function getGeometry( name ) {
  26794. if ( geometries[ name ] === undefined ) {
  26795. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  26796. }
  26797. return geometries[ name ];
  26798. }
  26799. function getMaterial( name ) {
  26800. if ( name === undefined ) return undefined;
  26801. if ( Array.isArray( name ) ) {
  26802. var array = [];
  26803. for ( var i = 0, l = name.length; i < l; i ++ ) {
  26804. var uuid = name[ i ];
  26805. if ( materials[ uuid ] === undefined ) {
  26806. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  26807. }
  26808. array.push( materials[ uuid ] );
  26809. }
  26810. return array;
  26811. }
  26812. if ( materials[ name ] === undefined ) {
  26813. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  26814. }
  26815. return materials[ name ];
  26816. }
  26817. switch ( data.type ) {
  26818. case 'Scene':
  26819. object = new Scene();
  26820. if ( data.background !== undefined ) {
  26821. if ( Number.isInteger( data.background ) ) {
  26822. object.background = new Color( data.background );
  26823. }
  26824. }
  26825. if ( data.fog !== undefined ) {
  26826. if ( data.fog.type === 'Fog' ) {
  26827. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  26828. } else if ( data.fog.type === 'FogExp2' ) {
  26829. object.fog = new FogExp2( data.fog.color, data.fog.density );
  26830. }
  26831. }
  26832. break;
  26833. case 'PerspectiveCamera':
  26834. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  26835. if ( data.focus !== undefined ) object.focus = data.focus;
  26836. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26837. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  26838. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  26839. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26840. break;
  26841. case 'OrthographicCamera':
  26842. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  26843. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26844. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26845. break;
  26846. case 'AmbientLight':
  26847. object = new AmbientLight( data.color, data.intensity );
  26848. break;
  26849. case 'DirectionalLight':
  26850. object = new DirectionalLight( data.color, data.intensity );
  26851. break;
  26852. case 'PointLight':
  26853. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  26854. break;
  26855. case 'RectAreaLight':
  26856. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  26857. break;
  26858. case 'SpotLight':
  26859. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  26860. break;
  26861. case 'HemisphereLight':
  26862. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  26863. break;
  26864. case 'SkinnedMesh':
  26865. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  26866. case 'Mesh':
  26867. var geometry = getGeometry( data.geometry );
  26868. var material = getMaterial( data.material );
  26869. if ( geometry.bones && geometry.bones.length > 0 ) {
  26870. object = new SkinnedMesh( geometry, material );
  26871. } else {
  26872. object = new Mesh( geometry, material );
  26873. }
  26874. break;
  26875. case 'LOD':
  26876. object = new LOD();
  26877. break;
  26878. case 'Line':
  26879. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  26880. break;
  26881. case 'LineLoop':
  26882. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  26883. break;
  26884. case 'LineSegments':
  26885. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  26886. break;
  26887. case 'PointCloud':
  26888. case 'Points':
  26889. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  26890. break;
  26891. case 'Sprite':
  26892. object = new Sprite( getMaterial( data.material ) );
  26893. break;
  26894. case 'Group':
  26895. object = new Group();
  26896. break;
  26897. default:
  26898. object = new Object3D();
  26899. }
  26900. object.uuid = data.uuid;
  26901. if ( data.name !== undefined ) object.name = data.name;
  26902. if ( data.matrix !== undefined ) {
  26903. object.matrix.fromArray( data.matrix );
  26904. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  26905. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  26906. } else {
  26907. if ( data.position !== undefined ) object.position.fromArray( data.position );
  26908. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  26909. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  26910. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  26911. }
  26912. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  26913. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  26914. if ( data.shadow ) {
  26915. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  26916. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  26917. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26918. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26919. }
  26920. if ( data.visible !== undefined ) object.visible = data.visible;
  26921. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  26922. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  26923. if ( data.userData !== undefined ) object.userData = data.userData;
  26924. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  26925. if ( data.children !== undefined ) {
  26926. var children = data.children;
  26927. for ( var i = 0; i < children.length; i ++ ) {
  26928. object.add( this.parseObject( children[ i ], geometries, materials ) );
  26929. }
  26930. }
  26931. if ( data.type === 'LOD' ) {
  26932. var levels = data.levels;
  26933. for ( var l = 0; l < levels.length; l ++ ) {
  26934. var level = levels[ l ];
  26935. var child = object.getObjectByProperty( 'uuid', level.object );
  26936. if ( child !== undefined ) {
  26937. object.addLevel( child, level.distance );
  26938. }
  26939. }
  26940. }
  26941. return object;
  26942. }
  26943. } );
  26944. var TEXTURE_MAPPING = {
  26945. UVMapping: UVMapping,
  26946. CubeReflectionMapping: CubeReflectionMapping,
  26947. CubeRefractionMapping: CubeRefractionMapping,
  26948. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26949. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26950. SphericalReflectionMapping: SphericalReflectionMapping,
  26951. CubeUVReflectionMapping: CubeUVReflectionMapping,
  26952. CubeUVRefractionMapping: CubeUVRefractionMapping
  26953. };
  26954. var TEXTURE_WRAPPING = {
  26955. RepeatWrapping: RepeatWrapping,
  26956. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26957. MirroredRepeatWrapping: MirroredRepeatWrapping
  26958. };
  26959. var TEXTURE_FILTER = {
  26960. NearestFilter: NearestFilter,
  26961. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  26962. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  26963. LinearFilter: LinearFilter,
  26964. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  26965. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  26966. };
  26967. /**
  26968. * @author thespite / http://clicktorelease.com/
  26969. */
  26970. function ImageBitmapLoader( manager ) {
  26971. if ( typeof createImageBitmap === 'undefined' ) {
  26972. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26973. }
  26974. if ( typeof fetch === 'undefined' ) {
  26975. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26976. }
  26977. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  26978. this.options = undefined;
  26979. }
  26980. ImageBitmapLoader.prototype = {
  26981. constructor: ImageBitmapLoader,
  26982. setOptions: function setOptions( options ) {
  26983. this.options = options;
  26984. return this;
  26985. },
  26986. load: function ( url, onLoad, onProgress, onError ) {
  26987. if ( url === undefined ) url = '';
  26988. if ( this.path !== undefined ) url = this.path + url;
  26989. url = this.manager.resolveURL( url );
  26990. var scope = this;
  26991. var cached = Cache.get( url );
  26992. if ( cached !== undefined ) {
  26993. scope.manager.itemStart( url );
  26994. setTimeout( function () {
  26995. if ( onLoad ) onLoad( cached );
  26996. scope.manager.itemEnd( url );
  26997. }, 0 );
  26998. return cached;
  26999. }
  27000. fetch( url ).then( function ( res ) {
  27001. return res.blob();
  27002. } ).then( function ( blob ) {
  27003. return createImageBitmap( blob, scope.options );
  27004. } ).then( function ( imageBitmap ) {
  27005. Cache.add( url, imageBitmap );
  27006. if ( onLoad ) onLoad( imageBitmap );
  27007. scope.manager.itemEnd( url );
  27008. } ).catch( function ( e ) {
  27009. if ( onError ) onError( e );
  27010. scope.manager.itemEnd( url );
  27011. scope.manager.itemError( url );
  27012. } );
  27013. },
  27014. setCrossOrigin: function ( /* value */ ) {
  27015. return this;
  27016. },
  27017. setPath: function ( value ) {
  27018. this.path = value;
  27019. return this;
  27020. }
  27021. };
  27022. /**
  27023. * @author zz85 / http://www.lab4games.net/zz85/blog
  27024. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  27025. **/
  27026. function ShapePath() {
  27027. this.type = 'ShapePath';
  27028. this.color = new Color();
  27029. this.subPaths = [];
  27030. this.currentPath = null;
  27031. }
  27032. Object.assign( ShapePath.prototype, {
  27033. moveTo: function ( x, y ) {
  27034. this.currentPath = new Path();
  27035. this.subPaths.push( this.currentPath );
  27036. this.currentPath.moveTo( x, y );
  27037. },
  27038. lineTo: function ( x, y ) {
  27039. this.currentPath.lineTo( x, y );
  27040. },
  27041. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  27042. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  27043. },
  27044. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  27045. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  27046. },
  27047. splineThru: function ( pts ) {
  27048. this.currentPath.splineThru( pts );
  27049. },
  27050. toShapes: function ( isCCW, noHoles ) {
  27051. function toShapesNoHoles( inSubpaths ) {
  27052. var shapes = [];
  27053. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  27054. var tmpPath = inSubpaths[ i ];
  27055. var tmpShape = new Shape();
  27056. tmpShape.curves = tmpPath.curves;
  27057. shapes.push( tmpShape );
  27058. }
  27059. return shapes;
  27060. }
  27061. function isPointInsidePolygon( inPt, inPolygon ) {
  27062. var polyLen = inPolygon.length;
  27063. // inPt on polygon contour => immediate success or
  27064. // toggling of inside/outside at every single! intersection point of an edge
  27065. // with the horizontal line through inPt, left of inPt
  27066. // not counting lowerY endpoints of edges and whole edges on that line
  27067. var inside = false;
  27068. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  27069. var edgeLowPt = inPolygon[ p ];
  27070. var edgeHighPt = inPolygon[ q ];
  27071. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  27072. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  27073. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  27074. // not parallel
  27075. if ( edgeDy < 0 ) {
  27076. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  27077. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  27078. }
  27079. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  27080. if ( inPt.y === edgeLowPt.y ) {
  27081. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  27082. // continue; // no intersection or edgeLowPt => doesn't count !!!
  27083. } else {
  27084. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  27085. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  27086. if ( perpEdge < 0 ) continue;
  27087. inside = ! inside; // true intersection left of inPt
  27088. }
  27089. } else {
  27090. // parallel or collinear
  27091. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  27092. // edge lies on the same horizontal line as inPt
  27093. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  27094. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  27095. // continue;
  27096. }
  27097. }
  27098. return inside;
  27099. }
  27100. var isClockWise = ShapeUtils.isClockWise;
  27101. var subPaths = this.subPaths;
  27102. if ( subPaths.length === 0 ) return [];
  27103. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  27104. var solid, tmpPath, tmpShape, shapes = [];
  27105. if ( subPaths.length === 1 ) {
  27106. tmpPath = subPaths[ 0 ];
  27107. tmpShape = new Shape();
  27108. tmpShape.curves = tmpPath.curves;
  27109. shapes.push( tmpShape );
  27110. return shapes;
  27111. }
  27112. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  27113. holesFirst = isCCW ? ! holesFirst : holesFirst;
  27114. // console.log("Holes first", holesFirst);
  27115. var betterShapeHoles = [];
  27116. var newShapes = [];
  27117. var newShapeHoles = [];
  27118. var mainIdx = 0;
  27119. var tmpPoints;
  27120. newShapes[ mainIdx ] = undefined;
  27121. newShapeHoles[ mainIdx ] = [];
  27122. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  27123. tmpPath = subPaths[ i ];
  27124. tmpPoints = tmpPath.getPoints();
  27125. solid = isClockWise( tmpPoints );
  27126. solid = isCCW ? ! solid : solid;
  27127. if ( solid ) {
  27128. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  27129. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  27130. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  27131. if ( holesFirst ) mainIdx ++;
  27132. newShapeHoles[ mainIdx ] = [];
  27133. //console.log('cw', i);
  27134. } else {
  27135. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  27136. //console.log('ccw', i);
  27137. }
  27138. }
  27139. // only Holes? -> probably all Shapes with wrong orientation
  27140. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  27141. if ( newShapes.length > 1 ) {
  27142. var ambiguous = false;
  27143. var toChange = [];
  27144. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  27145. betterShapeHoles[ sIdx ] = [];
  27146. }
  27147. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  27148. var sho = newShapeHoles[ sIdx ];
  27149. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  27150. var ho = sho[ hIdx ];
  27151. var hole_unassigned = true;
  27152. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  27153. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  27154. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  27155. if ( hole_unassigned ) {
  27156. hole_unassigned = false;
  27157. betterShapeHoles[ s2Idx ].push( ho );
  27158. } else {
  27159. ambiguous = true;
  27160. }
  27161. }
  27162. }
  27163. if ( hole_unassigned ) {
  27164. betterShapeHoles[ sIdx ].push( ho );
  27165. }
  27166. }
  27167. }
  27168. // console.log("ambiguous: ", ambiguous);
  27169. if ( toChange.length > 0 ) {
  27170. // console.log("to change: ", toChange);
  27171. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  27172. }
  27173. }
  27174. var tmpHoles;
  27175. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  27176. tmpShape = newShapes[ i ].s;
  27177. shapes.push( tmpShape );
  27178. tmpHoles = newShapeHoles[ i ];
  27179. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  27180. tmpShape.holes.push( tmpHoles[ j ].h );
  27181. }
  27182. }
  27183. //console.log("shape", shapes);
  27184. return shapes;
  27185. }
  27186. } );
  27187. /**
  27188. * @author zz85 / http://www.lab4games.net/zz85/blog
  27189. * @author mrdoob / http://mrdoob.com/
  27190. */
  27191. function Font( data ) {
  27192. this.type = 'Font';
  27193. this.data = data;
  27194. }
  27195. Object.assign( Font.prototype, {
  27196. isFont: true,
  27197. generateShapes: function ( text, size ) {
  27198. if ( size === undefined ) size = 100;
  27199. var shapes = [];
  27200. var paths = createPaths( text, size, this.data );
  27201. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  27202. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  27203. }
  27204. return shapes;
  27205. }
  27206. } );
  27207. function createPaths( text, size, data ) {
  27208. var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // see #13988
  27209. var scale = size / data.resolution;
  27210. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  27211. var paths = [];
  27212. var offsetX = 0, offsetY = 0;
  27213. for ( var i = 0; i < chars.length; i ++ ) {
  27214. var char = chars[ i ];
  27215. if ( char === '\n' ) {
  27216. offsetX = 0;
  27217. offsetY -= line_height;
  27218. } else {
  27219. var ret = createPath( char, scale, offsetX, offsetY, data );
  27220. offsetX += ret.offsetX;
  27221. paths.push( ret.path );
  27222. }
  27223. }
  27224. return paths;
  27225. }
  27226. function createPath( char, scale, offsetX, offsetY, data ) {
  27227. var glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  27228. if ( ! glyph ) return;
  27229. var path = new ShapePath();
  27230. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  27231. if ( glyph.o ) {
  27232. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  27233. for ( var i = 0, l = outline.length; i < l; ) {
  27234. var action = outline[ i ++ ];
  27235. switch ( action ) {
  27236. case 'm': // moveTo
  27237. x = outline[ i ++ ] * scale + offsetX;
  27238. y = outline[ i ++ ] * scale + offsetY;
  27239. path.moveTo( x, y );
  27240. break;
  27241. case 'l': // lineTo
  27242. x = outline[ i ++ ] * scale + offsetX;
  27243. y = outline[ i ++ ] * scale + offsetY;
  27244. path.lineTo( x, y );
  27245. break;
  27246. case 'q': // quadraticCurveTo
  27247. cpx = outline[ i ++ ] * scale + offsetX;
  27248. cpy = outline[ i ++ ] * scale + offsetY;
  27249. cpx1 = outline[ i ++ ] * scale + offsetX;
  27250. cpy1 = outline[ i ++ ] * scale + offsetY;
  27251. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  27252. break;
  27253. case 'b': // bezierCurveTo
  27254. cpx = outline[ i ++ ] * scale + offsetX;
  27255. cpy = outline[ i ++ ] * scale + offsetY;
  27256. cpx1 = outline[ i ++ ] * scale + offsetX;
  27257. cpy1 = outline[ i ++ ] * scale + offsetY;
  27258. cpx2 = outline[ i ++ ] * scale + offsetX;
  27259. cpy2 = outline[ i ++ ] * scale + offsetY;
  27260. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  27261. break;
  27262. }
  27263. }
  27264. }
  27265. return { offsetX: glyph.ha * scale, path: path };
  27266. }
  27267. /**
  27268. * @author mrdoob / http://mrdoob.com/
  27269. */
  27270. function FontLoader( manager ) {
  27271. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27272. }
  27273. Object.assign( FontLoader.prototype, {
  27274. load: function ( url, onLoad, onProgress, onError ) {
  27275. var scope = this;
  27276. var loader = new FileLoader( this.manager );
  27277. loader.setPath( this.path );
  27278. loader.load( url, function ( text ) {
  27279. var json;
  27280. try {
  27281. json = JSON.parse( text );
  27282. } catch ( e ) {
  27283. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  27284. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  27285. }
  27286. var font = scope.parse( json );
  27287. if ( onLoad ) onLoad( font );
  27288. }, onProgress, onError );
  27289. },
  27290. parse: function ( json ) {
  27291. return new Font( json );
  27292. },
  27293. setPath: function ( value ) {
  27294. this.path = value;
  27295. return this;
  27296. }
  27297. } );
  27298. /**
  27299. * @author mrdoob / http://mrdoob.com/
  27300. */
  27301. var context;
  27302. var AudioContext = {
  27303. getContext: function () {
  27304. if ( context === undefined ) {
  27305. context = new ( window.AudioContext || window.webkitAudioContext )();
  27306. }
  27307. return context;
  27308. },
  27309. setContext: function ( value ) {
  27310. context = value;
  27311. }
  27312. };
  27313. /**
  27314. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  27315. */
  27316. function AudioLoader( manager ) {
  27317. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27318. }
  27319. Object.assign( AudioLoader.prototype, {
  27320. load: function ( url, onLoad, onProgress, onError ) {
  27321. var loader = new FileLoader( this.manager );
  27322. loader.setResponseType( 'arraybuffer' );
  27323. loader.load( url, function ( buffer ) {
  27324. // Create a copy of the buffer. The `decodeAudioData` method
  27325. // detaches the buffer when complete, preventing reuse.
  27326. var bufferCopy = buffer.slice( 0 );
  27327. var context = AudioContext.getContext();
  27328. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  27329. onLoad( audioBuffer );
  27330. } );
  27331. }, onProgress, onError );
  27332. }
  27333. } );
  27334. /**
  27335. * @author mrdoob / http://mrdoob.com/
  27336. */
  27337. function StereoCamera() {
  27338. this.type = 'StereoCamera';
  27339. this.aspect = 1;
  27340. this.eyeSep = 0.064;
  27341. this.cameraL = new PerspectiveCamera();
  27342. this.cameraL.layers.enable( 1 );
  27343. this.cameraL.matrixAutoUpdate = false;
  27344. this.cameraR = new PerspectiveCamera();
  27345. this.cameraR.layers.enable( 2 );
  27346. this.cameraR.matrixAutoUpdate = false;
  27347. }
  27348. Object.assign( StereoCamera.prototype, {
  27349. update: ( function () {
  27350. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  27351. var eyeRight = new Matrix4();
  27352. var eyeLeft = new Matrix4();
  27353. return function update( camera ) {
  27354. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  27355. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  27356. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  27357. if ( needsUpdate ) {
  27358. instance = this;
  27359. focus = camera.focus;
  27360. fov = camera.fov;
  27361. aspect = camera.aspect * this.aspect;
  27362. near = camera.near;
  27363. far = camera.far;
  27364. zoom = camera.zoom;
  27365. // Off-axis stereoscopic effect based on
  27366. // http://paulbourke.net/stereographics/stereorender/
  27367. var projectionMatrix = camera.projectionMatrix.clone();
  27368. eyeSep = this.eyeSep / 2;
  27369. var eyeSepOnProjection = eyeSep * near / focus;
  27370. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  27371. var xmin, xmax;
  27372. // translate xOffset
  27373. eyeLeft.elements[ 12 ] = - eyeSep;
  27374. eyeRight.elements[ 12 ] = eyeSep;
  27375. // for left eye
  27376. xmin = - ymax * aspect + eyeSepOnProjection;
  27377. xmax = ymax * aspect + eyeSepOnProjection;
  27378. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  27379. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27380. this.cameraL.projectionMatrix.copy( projectionMatrix );
  27381. // for right eye
  27382. xmin = - ymax * aspect - eyeSepOnProjection;
  27383. xmax = ymax * aspect - eyeSepOnProjection;
  27384. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  27385. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27386. this.cameraR.projectionMatrix.copy( projectionMatrix );
  27387. }
  27388. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  27389. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  27390. };
  27391. } )()
  27392. } );
  27393. /**
  27394. * Camera for rendering cube maps
  27395. * - renders scene into axis-aligned cube
  27396. *
  27397. * @author alteredq / http://alteredqualia.com/
  27398. */
  27399. function CubeCamera( near, far, cubeResolution ) {
  27400. Object3D.call( this );
  27401. this.type = 'CubeCamera';
  27402. var fov = 90, aspect = 1;
  27403. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  27404. cameraPX.up.set( 0, - 1, 0 );
  27405. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  27406. this.add( cameraPX );
  27407. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  27408. cameraNX.up.set( 0, - 1, 0 );
  27409. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  27410. this.add( cameraNX );
  27411. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  27412. cameraPY.up.set( 0, 0, 1 );
  27413. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  27414. this.add( cameraPY );
  27415. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  27416. cameraNY.up.set( 0, 0, - 1 );
  27417. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  27418. this.add( cameraNY );
  27419. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  27420. cameraPZ.up.set( 0, - 1, 0 );
  27421. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  27422. this.add( cameraPZ );
  27423. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  27424. cameraNZ.up.set( 0, - 1, 0 );
  27425. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  27426. this.add( cameraNZ );
  27427. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  27428. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  27429. this.renderTarget.texture.name = "CubeCamera";
  27430. this.update = function ( renderer, scene ) {
  27431. if ( this.parent === null ) this.updateMatrixWorld();
  27432. var renderTarget = this.renderTarget;
  27433. var generateMipmaps = renderTarget.texture.generateMipmaps;
  27434. renderTarget.texture.generateMipmaps = false;
  27435. renderTarget.activeCubeFace = 0;
  27436. renderer.render( scene, cameraPX, renderTarget );
  27437. renderTarget.activeCubeFace = 1;
  27438. renderer.render( scene, cameraNX, renderTarget );
  27439. renderTarget.activeCubeFace = 2;
  27440. renderer.render( scene, cameraPY, renderTarget );
  27441. renderTarget.activeCubeFace = 3;
  27442. renderer.render( scene, cameraNY, renderTarget );
  27443. renderTarget.activeCubeFace = 4;
  27444. renderer.render( scene, cameraPZ, renderTarget );
  27445. renderTarget.texture.generateMipmaps = generateMipmaps;
  27446. renderTarget.activeCubeFace = 5;
  27447. renderer.render( scene, cameraNZ, renderTarget );
  27448. renderer.setRenderTarget( null );
  27449. };
  27450. this.clear = function ( renderer, color, depth, stencil ) {
  27451. var renderTarget = this.renderTarget;
  27452. for ( var i = 0; i < 6; i ++ ) {
  27453. renderTarget.activeCubeFace = i;
  27454. renderer.setRenderTarget( renderTarget );
  27455. renderer.clear( color, depth, stencil );
  27456. }
  27457. renderer.setRenderTarget( null );
  27458. };
  27459. }
  27460. CubeCamera.prototype = Object.create( Object3D.prototype );
  27461. CubeCamera.prototype.constructor = CubeCamera;
  27462. /**
  27463. * @author mrdoob / http://mrdoob.com/
  27464. */
  27465. function AudioListener() {
  27466. Object3D.call( this );
  27467. this.type = 'AudioListener';
  27468. this.context = AudioContext.getContext();
  27469. this.gain = this.context.createGain();
  27470. this.gain.connect( this.context.destination );
  27471. this.filter = null;
  27472. }
  27473. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  27474. constructor: AudioListener,
  27475. getInput: function () {
  27476. return this.gain;
  27477. },
  27478. removeFilter: function ( ) {
  27479. if ( this.filter !== null ) {
  27480. this.gain.disconnect( this.filter );
  27481. this.filter.disconnect( this.context.destination );
  27482. this.gain.connect( this.context.destination );
  27483. this.filter = null;
  27484. }
  27485. return this;
  27486. },
  27487. getFilter: function () {
  27488. return this.filter;
  27489. },
  27490. setFilter: function ( value ) {
  27491. if ( this.filter !== null ) {
  27492. this.gain.disconnect( this.filter );
  27493. this.filter.disconnect( this.context.destination );
  27494. } else {
  27495. this.gain.disconnect( this.context.destination );
  27496. }
  27497. this.filter = value;
  27498. this.gain.connect( this.filter );
  27499. this.filter.connect( this.context.destination );
  27500. return this;
  27501. },
  27502. getMasterVolume: function () {
  27503. return this.gain.gain.value;
  27504. },
  27505. setMasterVolume: function ( value ) {
  27506. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  27507. return this;
  27508. },
  27509. updateMatrixWorld: ( function () {
  27510. var position = new Vector3();
  27511. var quaternion = new Quaternion();
  27512. var scale = new Vector3();
  27513. var orientation = new Vector3();
  27514. return function updateMatrixWorld( force ) {
  27515. Object3D.prototype.updateMatrixWorld.call( this, force );
  27516. var listener = this.context.listener;
  27517. var up = this.up;
  27518. this.matrixWorld.decompose( position, quaternion, scale );
  27519. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  27520. if ( listener.positionX ) {
  27521. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  27522. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  27523. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  27524. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  27525. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  27526. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  27527. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  27528. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  27529. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  27530. } else {
  27531. listener.setPosition( position.x, position.y, position.z );
  27532. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  27533. }
  27534. };
  27535. } )()
  27536. } );
  27537. /**
  27538. * @author mrdoob / http://mrdoob.com/
  27539. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  27540. */
  27541. function Audio( listener ) {
  27542. Object3D.call( this );
  27543. this.type = 'Audio';
  27544. this.context = listener.context;
  27545. this.gain = this.context.createGain();
  27546. this.gain.connect( listener.getInput() );
  27547. this.autoplay = false;
  27548. this.buffer = null;
  27549. this.loop = false;
  27550. this.startTime = 0;
  27551. this.offset = 0;
  27552. this.playbackRate = 1;
  27553. this.isPlaying = false;
  27554. this.hasPlaybackControl = true;
  27555. this.sourceType = 'empty';
  27556. this.filters = [];
  27557. }
  27558. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  27559. constructor: Audio,
  27560. getOutput: function () {
  27561. return this.gain;
  27562. },
  27563. setNodeSource: function ( audioNode ) {
  27564. this.hasPlaybackControl = false;
  27565. this.sourceType = 'audioNode';
  27566. this.source = audioNode;
  27567. this.connect();
  27568. return this;
  27569. },
  27570. setMediaElementSource: function ( mediaElement ) {
  27571. this.hasPlaybackControl = false;
  27572. this.sourceType = 'mediaNode';
  27573. this.source = this.context.createMediaElementSource( mediaElement );
  27574. this.connect();
  27575. return this;
  27576. },
  27577. setBuffer: function ( audioBuffer ) {
  27578. this.buffer = audioBuffer;
  27579. this.sourceType = 'buffer';
  27580. if ( this.autoplay ) this.play();
  27581. return this;
  27582. },
  27583. play: function () {
  27584. if ( this.isPlaying === true ) {
  27585. console.warn( 'THREE.Audio: Audio is already playing.' );
  27586. return;
  27587. }
  27588. if ( this.hasPlaybackControl === false ) {
  27589. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27590. return;
  27591. }
  27592. var source = this.context.createBufferSource();
  27593. source.buffer = this.buffer;
  27594. source.loop = this.loop;
  27595. source.onended = this.onEnded.bind( this );
  27596. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  27597. this.startTime = this.context.currentTime;
  27598. source.start( this.startTime, this.offset );
  27599. this.isPlaying = true;
  27600. this.source = source;
  27601. return this.connect();
  27602. },
  27603. pause: function () {
  27604. if ( this.hasPlaybackControl === false ) {
  27605. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27606. return;
  27607. }
  27608. if ( this.isPlaying === true ) {
  27609. this.source.stop();
  27610. this.source.onended = null;
  27611. this.offset += ( this.context.currentTime - this.startTime ) * this.playbackRate;
  27612. this.isPlaying = false;
  27613. }
  27614. return this;
  27615. },
  27616. stop: function () {
  27617. if ( this.hasPlaybackControl === false ) {
  27618. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27619. return;
  27620. }
  27621. this.source.stop();
  27622. this.source.onended = null;
  27623. this.offset = 0;
  27624. this.isPlaying = false;
  27625. return this;
  27626. },
  27627. connect: function () {
  27628. if ( this.filters.length > 0 ) {
  27629. this.source.connect( this.filters[ 0 ] );
  27630. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  27631. this.filters[ i - 1 ].connect( this.filters[ i ] );
  27632. }
  27633. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  27634. } else {
  27635. this.source.connect( this.getOutput() );
  27636. }
  27637. return this;
  27638. },
  27639. disconnect: function () {
  27640. if ( this.filters.length > 0 ) {
  27641. this.source.disconnect( this.filters[ 0 ] );
  27642. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  27643. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  27644. }
  27645. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  27646. } else {
  27647. this.source.disconnect( this.getOutput() );
  27648. }
  27649. return this;
  27650. },
  27651. getFilters: function () {
  27652. return this.filters;
  27653. },
  27654. setFilters: function ( value ) {
  27655. if ( ! value ) value = [];
  27656. if ( this.isPlaying === true ) {
  27657. this.disconnect();
  27658. this.filters = value;
  27659. this.connect();
  27660. } else {
  27661. this.filters = value;
  27662. }
  27663. return this;
  27664. },
  27665. getFilter: function () {
  27666. return this.getFilters()[ 0 ];
  27667. },
  27668. setFilter: function ( filter ) {
  27669. return this.setFilters( filter ? [ filter ] : [] );
  27670. },
  27671. setPlaybackRate: function ( value ) {
  27672. if ( this.hasPlaybackControl === false ) {
  27673. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27674. return;
  27675. }
  27676. this.playbackRate = value;
  27677. if ( this.isPlaying === true ) {
  27678. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  27679. }
  27680. return this;
  27681. },
  27682. getPlaybackRate: function () {
  27683. return this.playbackRate;
  27684. },
  27685. onEnded: function () {
  27686. this.isPlaying = false;
  27687. },
  27688. getLoop: function () {
  27689. if ( this.hasPlaybackControl === false ) {
  27690. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27691. return false;
  27692. }
  27693. return this.loop;
  27694. },
  27695. setLoop: function ( value ) {
  27696. if ( this.hasPlaybackControl === false ) {
  27697. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27698. return;
  27699. }
  27700. this.loop = value;
  27701. if ( this.isPlaying === true ) {
  27702. this.source.loop = this.loop;
  27703. }
  27704. return this;
  27705. },
  27706. getVolume: function () {
  27707. return this.gain.gain.value;
  27708. },
  27709. setVolume: function ( value ) {
  27710. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  27711. return this;
  27712. }
  27713. } );
  27714. /**
  27715. * @author mrdoob / http://mrdoob.com/
  27716. */
  27717. function PositionalAudio( listener ) {
  27718. Audio.call( this, listener );
  27719. this.panner = this.context.createPanner();
  27720. this.panner.connect( this.gain );
  27721. }
  27722. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  27723. constructor: PositionalAudio,
  27724. getOutput: function () {
  27725. return this.panner;
  27726. },
  27727. getRefDistance: function () {
  27728. return this.panner.refDistance;
  27729. },
  27730. setRefDistance: function ( value ) {
  27731. this.panner.refDistance = value;
  27732. return this;
  27733. },
  27734. getRolloffFactor: function () {
  27735. return this.panner.rolloffFactor;
  27736. },
  27737. setRolloffFactor: function ( value ) {
  27738. this.panner.rolloffFactor = value;
  27739. return this;
  27740. },
  27741. getDistanceModel: function () {
  27742. return this.panner.distanceModel;
  27743. },
  27744. setDistanceModel: function ( value ) {
  27745. this.panner.distanceModel = value;
  27746. return this;
  27747. },
  27748. getMaxDistance: function () {
  27749. return this.panner.maxDistance;
  27750. },
  27751. setMaxDistance: function ( value ) {
  27752. this.panner.maxDistance = value;
  27753. return this;
  27754. },
  27755. setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  27756. this.panner.coneInnerAngle = coneInnerAngle;
  27757. this.panner.coneOuterAngle = coneOuterAngle;
  27758. this.panner.coneOuterGain = coneOuterGain;
  27759. return this;
  27760. },
  27761. updateMatrixWorld: ( function () {
  27762. var position = new Vector3();
  27763. var quaternion = new Quaternion();
  27764. var scale = new Vector3();
  27765. var orientation = new Vector3();
  27766. return function updateMatrixWorld( force ) {
  27767. Object3D.prototype.updateMatrixWorld.call( this, force );
  27768. var panner = this.panner;
  27769. this.matrixWorld.decompose( position, quaternion, scale );
  27770. orientation.set( 0, 0, 1 ).applyQuaternion( quaternion );
  27771. panner.setPosition( position.x, position.y, position.z );
  27772. panner.setOrientation( orientation.x, orientation.y, orientation.z );
  27773. };
  27774. } )()
  27775. } );
  27776. /**
  27777. * @author mrdoob / http://mrdoob.com/
  27778. */
  27779. function AudioAnalyser( audio, fftSize ) {
  27780. this.analyser = audio.context.createAnalyser();
  27781. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  27782. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  27783. audio.getOutput().connect( this.analyser );
  27784. }
  27785. Object.assign( AudioAnalyser.prototype, {
  27786. getFrequencyData: function () {
  27787. this.analyser.getByteFrequencyData( this.data );
  27788. return this.data;
  27789. },
  27790. getAverageFrequency: function () {
  27791. var value = 0, data = this.getFrequencyData();
  27792. for ( var i = 0; i < data.length; i ++ ) {
  27793. value += data[ i ];
  27794. }
  27795. return value / data.length;
  27796. }
  27797. } );
  27798. /**
  27799. *
  27800. * Buffered scene graph property that allows weighted accumulation.
  27801. *
  27802. *
  27803. * @author Ben Houston / http://clara.io/
  27804. * @author David Sarno / http://lighthaus.us/
  27805. * @author tschw
  27806. */
  27807. function PropertyMixer( binding, typeName, valueSize ) {
  27808. this.binding = binding;
  27809. this.valueSize = valueSize;
  27810. var bufferType = Float64Array,
  27811. mixFunction;
  27812. switch ( typeName ) {
  27813. case 'quaternion':
  27814. mixFunction = this._slerp;
  27815. break;
  27816. case 'string':
  27817. case 'bool':
  27818. bufferType = Array;
  27819. mixFunction = this._select;
  27820. break;
  27821. default:
  27822. mixFunction = this._lerp;
  27823. }
  27824. this.buffer = new bufferType( valueSize * 4 );
  27825. // layout: [ incoming | accu0 | accu1 | orig ]
  27826. //
  27827. // interpolators can use .buffer as their .result
  27828. // the data then goes to 'incoming'
  27829. //
  27830. // 'accu0' and 'accu1' are used frame-interleaved for
  27831. // the cumulative result and are compared to detect
  27832. // changes
  27833. //
  27834. // 'orig' stores the original state of the property
  27835. this._mixBufferRegion = mixFunction;
  27836. this.cumulativeWeight = 0;
  27837. this.useCount = 0;
  27838. this.referenceCount = 0;
  27839. }
  27840. Object.assign( PropertyMixer.prototype, {
  27841. // accumulate data in the 'incoming' region into 'accu<i>'
  27842. accumulate: function ( accuIndex, weight ) {
  27843. // note: happily accumulating nothing when weight = 0, the caller knows
  27844. // the weight and shouldn't have made the call in the first place
  27845. var buffer = this.buffer,
  27846. stride = this.valueSize,
  27847. offset = accuIndex * stride + stride,
  27848. currentWeight = this.cumulativeWeight;
  27849. if ( currentWeight === 0 ) {
  27850. // accuN := incoming * weight
  27851. for ( var i = 0; i !== stride; ++ i ) {
  27852. buffer[ offset + i ] = buffer[ i ];
  27853. }
  27854. currentWeight = weight;
  27855. } else {
  27856. // accuN := accuN + incoming * weight
  27857. currentWeight += weight;
  27858. var mix = weight / currentWeight;
  27859. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  27860. }
  27861. this.cumulativeWeight = currentWeight;
  27862. },
  27863. // apply the state of 'accu<i>' to the binding when accus differ
  27864. apply: function ( accuIndex ) {
  27865. var stride = this.valueSize,
  27866. buffer = this.buffer,
  27867. offset = accuIndex * stride + stride,
  27868. weight = this.cumulativeWeight,
  27869. binding = this.binding;
  27870. this.cumulativeWeight = 0;
  27871. if ( weight < 1 ) {
  27872. // accuN := accuN + original * ( 1 - cumulativeWeight )
  27873. var originalValueOffset = stride * 3;
  27874. this._mixBufferRegion(
  27875. buffer, offset, originalValueOffset, 1 - weight, stride );
  27876. }
  27877. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  27878. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  27879. // value has changed -> update scene graph
  27880. binding.setValue( buffer, offset );
  27881. break;
  27882. }
  27883. }
  27884. },
  27885. // remember the state of the bound property and copy it to both accus
  27886. saveOriginalState: function () {
  27887. var binding = this.binding;
  27888. var buffer = this.buffer,
  27889. stride = this.valueSize,
  27890. originalValueOffset = stride * 3;
  27891. binding.getValue( buffer, originalValueOffset );
  27892. // accu[0..1] := orig -- initially detect changes against the original
  27893. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  27894. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  27895. }
  27896. this.cumulativeWeight = 0;
  27897. },
  27898. // apply the state previously taken via 'saveOriginalState' to the binding
  27899. restoreOriginalState: function () {
  27900. var originalValueOffset = this.valueSize * 3;
  27901. this.binding.setValue( this.buffer, originalValueOffset );
  27902. },
  27903. // mix functions
  27904. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  27905. if ( t >= 0.5 ) {
  27906. for ( var i = 0; i !== stride; ++ i ) {
  27907. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  27908. }
  27909. }
  27910. },
  27911. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  27912. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  27913. },
  27914. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  27915. var s = 1 - t;
  27916. for ( var i = 0; i !== stride; ++ i ) {
  27917. var j = dstOffset + i;
  27918. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  27919. }
  27920. }
  27921. } );
  27922. /**
  27923. *
  27924. * A reference to a real property in the scene graph.
  27925. *
  27926. *
  27927. * @author Ben Houston / http://clara.io/
  27928. * @author David Sarno / http://lighthaus.us/
  27929. * @author tschw
  27930. */
  27931. // Characters [].:/ are reserved for track binding syntax.
  27932. var RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  27933. function Composite( targetGroup, path, optionalParsedPath ) {
  27934. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  27935. this._targetGroup = targetGroup;
  27936. this._bindings = targetGroup.subscribe_( path, parsedPath );
  27937. }
  27938. Object.assign( Composite.prototype, {
  27939. getValue: function ( array, offset ) {
  27940. this.bind(); // bind all binding
  27941. var firstValidIndex = this._targetGroup.nCachedObjects_,
  27942. binding = this._bindings[ firstValidIndex ];
  27943. // and only call .getValue on the first
  27944. if ( binding !== undefined ) binding.getValue( array, offset );
  27945. },
  27946. setValue: function ( array, offset ) {
  27947. var bindings = this._bindings;
  27948. for ( var i = this._targetGroup.nCachedObjects_,
  27949. n = bindings.length; i !== n; ++ i ) {
  27950. bindings[ i ].setValue( array, offset );
  27951. }
  27952. },
  27953. bind: function () {
  27954. var bindings = this._bindings;
  27955. for ( var i = this._targetGroup.nCachedObjects_,
  27956. n = bindings.length; i !== n; ++ i ) {
  27957. bindings[ i ].bind();
  27958. }
  27959. },
  27960. unbind: function () {
  27961. var bindings = this._bindings;
  27962. for ( var i = this._targetGroup.nCachedObjects_,
  27963. n = bindings.length; i !== n; ++ i ) {
  27964. bindings[ i ].unbind();
  27965. }
  27966. }
  27967. } );
  27968. function PropertyBinding( rootNode, path, parsedPath ) {
  27969. this.path = path;
  27970. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  27971. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  27972. this.rootNode = rootNode;
  27973. }
  27974. Object.assign( PropertyBinding, {
  27975. Composite: Composite,
  27976. create: function ( root, path, parsedPath ) {
  27977. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  27978. return new PropertyBinding( root, path, parsedPath );
  27979. } else {
  27980. return new PropertyBinding.Composite( root, path, parsedPath );
  27981. }
  27982. },
  27983. /**
  27984. * Replaces spaces with underscores and removes unsupported characters from
  27985. * node names, to ensure compatibility with parseTrackName().
  27986. *
  27987. * @param {string} name Node name to be sanitized.
  27988. * @return {string}
  27989. */
  27990. sanitizeNodeName: ( function () {
  27991. var reservedRe = new RegExp( '[' + RESERVED_CHARS_RE + ']', 'g' );
  27992. return function sanitizeNodeName( name ) {
  27993. return name.replace( /\s/g, '_' ).replace( reservedRe, '' );
  27994. };
  27995. }() ),
  27996. parseTrackName: function () {
  27997. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  27998. // only latin characters, and the unicode \p{L} is not yet supported. So
  27999. // instead, we exclude reserved characters and match everything else.
  28000. var wordChar = '[^' + RESERVED_CHARS_RE + ']';
  28001. var wordCharOrDot = '[^' + RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  28002. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  28003. // be matched to parse the rest of the track name.
  28004. var directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', wordChar );
  28005. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  28006. var nodeRe = /(WCOD+)?/.source.replace( 'WCOD', wordCharOrDot );
  28007. // Object on target node, and accessor. May not contain reserved
  28008. // characters. Accessor may contain any character except closing bracket.
  28009. var objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', wordChar );
  28010. // Property and accessor. May not contain reserved characters. Accessor may
  28011. // contain any non-bracket characters.
  28012. var propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', wordChar );
  28013. var trackRe = new RegExp( ''
  28014. + '^'
  28015. + directoryRe
  28016. + nodeRe
  28017. + objectRe
  28018. + propertyRe
  28019. + '$'
  28020. );
  28021. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  28022. return function parseTrackName( trackName ) {
  28023. var matches = trackRe.exec( trackName );
  28024. if ( ! matches ) {
  28025. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  28026. }
  28027. var results = {
  28028. // directoryName: matches[ 1 ], // (tschw) currently unused
  28029. nodeName: matches[ 2 ],
  28030. objectName: matches[ 3 ],
  28031. objectIndex: matches[ 4 ],
  28032. propertyName: matches[ 5 ], // required
  28033. propertyIndex: matches[ 6 ]
  28034. };
  28035. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  28036. if ( lastDot !== undefined && lastDot !== - 1 ) {
  28037. var objectName = results.nodeName.substring( lastDot + 1 );
  28038. // Object names must be checked against a whitelist. Otherwise, there
  28039. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  28040. // 'bar' could be the objectName, or part of a nodeName (which can
  28041. // include '.' characters).
  28042. if ( supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  28043. results.nodeName = results.nodeName.substring( 0, lastDot );
  28044. results.objectName = objectName;
  28045. }
  28046. }
  28047. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  28048. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  28049. }
  28050. return results;
  28051. };
  28052. }(),
  28053. findNode: function ( root, nodeName ) {
  28054. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  28055. return root;
  28056. }
  28057. // search into skeleton bones.
  28058. if ( root.skeleton ) {
  28059. var bone = root.skeleton.getBoneByName( nodeName );
  28060. if ( bone !== undefined ) {
  28061. return bone;
  28062. }
  28063. }
  28064. // search into node subtree.
  28065. if ( root.children ) {
  28066. var searchNodeSubtree = function ( children ) {
  28067. for ( var i = 0; i < children.length; i ++ ) {
  28068. var childNode = children[ i ];
  28069. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  28070. return childNode;
  28071. }
  28072. var result = searchNodeSubtree( childNode.children );
  28073. if ( result ) return result;
  28074. }
  28075. return null;
  28076. };
  28077. var subTreeNode = searchNodeSubtree( root.children );
  28078. if ( subTreeNode ) {
  28079. return subTreeNode;
  28080. }
  28081. }
  28082. return null;
  28083. }
  28084. } );
  28085. Object.assign( PropertyBinding.prototype, { // prototype, continued
  28086. // these are used to "bind" a nonexistent property
  28087. _getValue_unavailable: function () {},
  28088. _setValue_unavailable: function () {},
  28089. BindingType: {
  28090. Direct: 0,
  28091. EntireArray: 1,
  28092. ArrayElement: 2,
  28093. HasFromToArray: 3
  28094. },
  28095. Versioning: {
  28096. None: 0,
  28097. NeedsUpdate: 1,
  28098. MatrixWorldNeedsUpdate: 2
  28099. },
  28100. GetterByBindingType: [
  28101. function getValue_direct( buffer, offset ) {
  28102. buffer[ offset ] = this.node[ this.propertyName ];
  28103. },
  28104. function getValue_array( buffer, offset ) {
  28105. var source = this.resolvedProperty;
  28106. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  28107. buffer[ offset ++ ] = source[ i ];
  28108. }
  28109. },
  28110. function getValue_arrayElement( buffer, offset ) {
  28111. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  28112. },
  28113. function getValue_toArray( buffer, offset ) {
  28114. this.resolvedProperty.toArray( buffer, offset );
  28115. }
  28116. ],
  28117. SetterByBindingTypeAndVersioning: [
  28118. [
  28119. // Direct
  28120. function setValue_direct( buffer, offset ) {
  28121. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28122. },
  28123. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  28124. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28125. this.targetObject.needsUpdate = true;
  28126. },
  28127. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28128. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28129. this.targetObject.matrixWorldNeedsUpdate = true;
  28130. }
  28131. ], [
  28132. // EntireArray
  28133. function setValue_array( buffer, offset ) {
  28134. var dest = this.resolvedProperty;
  28135. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  28136. dest[ i ] = buffer[ offset ++ ];
  28137. }
  28138. },
  28139. function setValue_array_setNeedsUpdate( buffer, offset ) {
  28140. var dest = this.resolvedProperty;
  28141. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  28142. dest[ i ] = buffer[ offset ++ ];
  28143. }
  28144. this.targetObject.needsUpdate = true;
  28145. },
  28146. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28147. var dest = this.resolvedProperty;
  28148. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  28149. dest[ i ] = buffer[ offset ++ ];
  28150. }
  28151. this.targetObject.matrixWorldNeedsUpdate = true;
  28152. }
  28153. ], [
  28154. // ArrayElement
  28155. function setValue_arrayElement( buffer, offset ) {
  28156. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28157. },
  28158. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  28159. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28160. this.targetObject.needsUpdate = true;
  28161. },
  28162. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28163. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28164. this.targetObject.matrixWorldNeedsUpdate = true;
  28165. }
  28166. ], [
  28167. // HasToFromArray
  28168. function setValue_fromArray( buffer, offset ) {
  28169. this.resolvedProperty.fromArray( buffer, offset );
  28170. },
  28171. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  28172. this.resolvedProperty.fromArray( buffer, offset );
  28173. this.targetObject.needsUpdate = true;
  28174. },
  28175. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28176. this.resolvedProperty.fromArray( buffer, offset );
  28177. this.targetObject.matrixWorldNeedsUpdate = true;
  28178. }
  28179. ]
  28180. ],
  28181. getValue: function getValue_unbound( targetArray, offset ) {
  28182. this.bind();
  28183. this.getValue( targetArray, offset );
  28184. // Note: This class uses a State pattern on a per-method basis:
  28185. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  28186. // prototype version of these methods with one that represents
  28187. // the bound state. When the property is not found, the methods
  28188. // become no-ops.
  28189. },
  28190. setValue: function getValue_unbound( sourceArray, offset ) {
  28191. this.bind();
  28192. this.setValue( sourceArray, offset );
  28193. },
  28194. // create getter / setter pair for a property in the scene graph
  28195. bind: function () {
  28196. var targetObject = this.node,
  28197. parsedPath = this.parsedPath,
  28198. objectName = parsedPath.objectName,
  28199. propertyName = parsedPath.propertyName,
  28200. propertyIndex = parsedPath.propertyIndex;
  28201. if ( ! targetObject ) {
  28202. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  28203. this.node = targetObject;
  28204. }
  28205. // set fail state so we can just 'return' on error
  28206. this.getValue = this._getValue_unavailable;
  28207. this.setValue = this._setValue_unavailable;
  28208. // ensure there is a value node
  28209. if ( ! targetObject ) {
  28210. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  28211. return;
  28212. }
  28213. if ( objectName ) {
  28214. var objectIndex = parsedPath.objectIndex;
  28215. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  28216. switch ( objectName ) {
  28217. case 'materials':
  28218. if ( ! targetObject.material ) {
  28219. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28220. return;
  28221. }
  28222. if ( ! targetObject.material.materials ) {
  28223. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  28224. return;
  28225. }
  28226. targetObject = targetObject.material.materials;
  28227. break;
  28228. case 'bones':
  28229. if ( ! targetObject.skeleton ) {
  28230. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  28231. return;
  28232. }
  28233. // potential future optimization: skip this if propertyIndex is already an integer
  28234. // and convert the integer string to a true integer.
  28235. targetObject = targetObject.skeleton.bones;
  28236. // support resolving morphTarget names into indices.
  28237. for ( var i = 0; i < targetObject.length; i ++ ) {
  28238. if ( targetObject[ i ].name === objectIndex ) {
  28239. objectIndex = i;
  28240. break;
  28241. }
  28242. }
  28243. break;
  28244. default:
  28245. if ( targetObject[ objectName ] === undefined ) {
  28246. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  28247. return;
  28248. }
  28249. targetObject = targetObject[ objectName ];
  28250. }
  28251. if ( objectIndex !== undefined ) {
  28252. if ( targetObject[ objectIndex ] === undefined ) {
  28253. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  28254. return;
  28255. }
  28256. targetObject = targetObject[ objectIndex ];
  28257. }
  28258. }
  28259. // resolve property
  28260. var nodeProperty = targetObject[ propertyName ];
  28261. if ( nodeProperty === undefined ) {
  28262. var nodeName = parsedPath.nodeName;
  28263. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  28264. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  28265. return;
  28266. }
  28267. // determine versioning scheme
  28268. var versioning = this.Versioning.None;
  28269. if ( targetObject.needsUpdate !== undefined ) { // material
  28270. versioning = this.Versioning.NeedsUpdate;
  28271. this.targetObject = targetObject;
  28272. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  28273. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  28274. this.targetObject = targetObject;
  28275. }
  28276. // determine how the property gets bound
  28277. var bindingType = this.BindingType.Direct;
  28278. if ( propertyIndex !== undefined ) {
  28279. // access a sub element of the property array (only primitives are supported right now)
  28280. if ( propertyName === "morphTargetInfluences" ) {
  28281. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  28282. // support resolving morphTarget names into indices.
  28283. if ( ! targetObject.geometry ) {
  28284. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  28285. return;
  28286. }
  28287. if ( targetObject.geometry.isBufferGeometry ) {
  28288. if ( ! targetObject.geometry.morphAttributes ) {
  28289. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  28290. return;
  28291. }
  28292. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  28293. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  28294. propertyIndex = i;
  28295. break;
  28296. }
  28297. }
  28298. } else {
  28299. if ( ! targetObject.geometry.morphTargets ) {
  28300. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  28301. return;
  28302. }
  28303. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  28304. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  28305. propertyIndex = i;
  28306. break;
  28307. }
  28308. }
  28309. }
  28310. }
  28311. bindingType = this.BindingType.ArrayElement;
  28312. this.resolvedProperty = nodeProperty;
  28313. this.propertyIndex = propertyIndex;
  28314. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  28315. // must use copy for Object3D.Euler/Quaternion
  28316. bindingType = this.BindingType.HasFromToArray;
  28317. this.resolvedProperty = nodeProperty;
  28318. } else if ( Array.isArray( nodeProperty ) ) {
  28319. bindingType = this.BindingType.EntireArray;
  28320. this.resolvedProperty = nodeProperty;
  28321. } else {
  28322. this.propertyName = propertyName;
  28323. }
  28324. // select getter / setter
  28325. this.getValue = this.GetterByBindingType[ bindingType ];
  28326. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  28327. },
  28328. unbind: function () {
  28329. this.node = null;
  28330. // back to the prototype version of getValue / setValue
  28331. // note: avoiding to mutate the shape of 'this' via 'delete'
  28332. this.getValue = this._getValue_unbound;
  28333. this.setValue = this._setValue_unbound;
  28334. }
  28335. } );
  28336. //!\ DECLARE ALIAS AFTER assign prototype !
  28337. Object.assign( PropertyBinding.prototype, {
  28338. // initial state of these methods that calls 'bind'
  28339. _getValue_unbound: PropertyBinding.prototype.getValue,
  28340. _setValue_unbound: PropertyBinding.prototype.setValue,
  28341. } );
  28342. /**
  28343. *
  28344. * A group of objects that receives a shared animation state.
  28345. *
  28346. * Usage:
  28347. *
  28348. * - Add objects you would otherwise pass as 'root' to the
  28349. * constructor or the .clipAction method of AnimationMixer.
  28350. *
  28351. * - Instead pass this object as 'root'.
  28352. *
  28353. * - You can also add and remove objects later when the mixer
  28354. * is running.
  28355. *
  28356. * Note:
  28357. *
  28358. * Objects of this class appear as one object to the mixer,
  28359. * so cache control of the individual objects must be done
  28360. * on the group.
  28361. *
  28362. * Limitation:
  28363. *
  28364. * - The animated properties must be compatible among the
  28365. * all objects in the group.
  28366. *
  28367. * - A single property can either be controlled through a
  28368. * target group or directly, but not both.
  28369. *
  28370. * @author tschw
  28371. */
  28372. function AnimationObjectGroup() {
  28373. this.uuid = _Math.generateUUID();
  28374. // cached objects followed by the active ones
  28375. this._objects = Array.prototype.slice.call( arguments );
  28376. this.nCachedObjects_ = 0; // threshold
  28377. // note: read by PropertyBinding.Composite
  28378. var indices = {};
  28379. this._indicesByUUID = indices; // for bookkeeping
  28380. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28381. indices[ arguments[ i ].uuid ] = i;
  28382. }
  28383. this._paths = []; // inside: string
  28384. this._parsedPaths = []; // inside: { we don't care, here }
  28385. this._bindings = []; // inside: Array< PropertyBinding >
  28386. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  28387. var scope = this;
  28388. this.stats = {
  28389. objects: {
  28390. get total() {
  28391. return scope._objects.length;
  28392. },
  28393. get inUse() {
  28394. return this.total - scope.nCachedObjects_;
  28395. }
  28396. },
  28397. get bindingsPerObject() {
  28398. return scope._bindings.length;
  28399. }
  28400. };
  28401. }
  28402. Object.assign( AnimationObjectGroup.prototype, {
  28403. isAnimationObjectGroup: true,
  28404. add: function () {
  28405. var objects = this._objects,
  28406. nObjects = objects.length,
  28407. nCachedObjects = this.nCachedObjects_,
  28408. indicesByUUID = this._indicesByUUID,
  28409. paths = this._paths,
  28410. parsedPaths = this._parsedPaths,
  28411. bindings = this._bindings,
  28412. nBindings = bindings.length,
  28413. knownObject = undefined;
  28414. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28415. var object = arguments[ i ],
  28416. uuid = object.uuid,
  28417. index = indicesByUUID[ uuid ];
  28418. if ( index === undefined ) {
  28419. // unknown object -> add it to the ACTIVE region
  28420. index = nObjects ++;
  28421. indicesByUUID[ uuid ] = index;
  28422. objects.push( object );
  28423. // accounting is done, now do the same for all bindings
  28424. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28425. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  28426. }
  28427. } else if ( index < nCachedObjects ) {
  28428. knownObject = objects[ index ];
  28429. // move existing object to the ACTIVE region
  28430. var firstActiveIndex = -- nCachedObjects,
  28431. lastCachedObject = objects[ firstActiveIndex ];
  28432. indicesByUUID[ lastCachedObject.uuid ] = index;
  28433. objects[ index ] = lastCachedObject;
  28434. indicesByUUID[ uuid ] = firstActiveIndex;
  28435. objects[ firstActiveIndex ] = object;
  28436. // accounting is done, now do the same for all bindings
  28437. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28438. var bindingsForPath = bindings[ j ],
  28439. lastCached = bindingsForPath[ firstActiveIndex ],
  28440. binding = bindingsForPath[ index ];
  28441. bindingsForPath[ index ] = lastCached;
  28442. if ( binding === undefined ) {
  28443. // since we do not bother to create new bindings
  28444. // for objects that are cached, the binding may
  28445. // or may not exist
  28446. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  28447. }
  28448. bindingsForPath[ firstActiveIndex ] = binding;
  28449. }
  28450. } else if ( objects[ index ] !== knownObject ) {
  28451. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  28452. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  28453. } // else the object is already where we want it to be
  28454. } // for arguments
  28455. this.nCachedObjects_ = nCachedObjects;
  28456. },
  28457. remove: function () {
  28458. var objects = this._objects,
  28459. nCachedObjects = this.nCachedObjects_,
  28460. indicesByUUID = this._indicesByUUID,
  28461. bindings = this._bindings,
  28462. nBindings = bindings.length;
  28463. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28464. var object = arguments[ i ],
  28465. uuid = object.uuid,
  28466. index = indicesByUUID[ uuid ];
  28467. if ( index !== undefined && index >= nCachedObjects ) {
  28468. // move existing object into the CACHED region
  28469. var lastCachedIndex = nCachedObjects ++,
  28470. firstActiveObject = objects[ lastCachedIndex ];
  28471. indicesByUUID[ firstActiveObject.uuid ] = index;
  28472. objects[ index ] = firstActiveObject;
  28473. indicesByUUID[ uuid ] = lastCachedIndex;
  28474. objects[ lastCachedIndex ] = object;
  28475. // accounting is done, now do the same for all bindings
  28476. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28477. var bindingsForPath = bindings[ j ],
  28478. firstActive = bindingsForPath[ lastCachedIndex ],
  28479. binding = bindingsForPath[ index ];
  28480. bindingsForPath[ index ] = firstActive;
  28481. bindingsForPath[ lastCachedIndex ] = binding;
  28482. }
  28483. }
  28484. } // for arguments
  28485. this.nCachedObjects_ = nCachedObjects;
  28486. },
  28487. // remove & forget
  28488. uncache: function () {
  28489. var objects = this._objects,
  28490. nObjects = objects.length,
  28491. nCachedObjects = this.nCachedObjects_,
  28492. indicesByUUID = this._indicesByUUID,
  28493. bindings = this._bindings,
  28494. nBindings = bindings.length;
  28495. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28496. var object = arguments[ i ],
  28497. uuid = object.uuid,
  28498. index = indicesByUUID[ uuid ];
  28499. if ( index !== undefined ) {
  28500. delete indicesByUUID[ uuid ];
  28501. if ( index < nCachedObjects ) {
  28502. // object is cached, shrink the CACHED region
  28503. var firstActiveIndex = -- nCachedObjects,
  28504. lastCachedObject = objects[ firstActiveIndex ],
  28505. lastIndex = -- nObjects,
  28506. lastObject = objects[ lastIndex ];
  28507. // last cached object takes this object's place
  28508. indicesByUUID[ lastCachedObject.uuid ] = index;
  28509. objects[ index ] = lastCachedObject;
  28510. // last object goes to the activated slot and pop
  28511. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  28512. objects[ firstActiveIndex ] = lastObject;
  28513. objects.pop();
  28514. // accounting is done, now do the same for all bindings
  28515. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28516. var bindingsForPath = bindings[ j ],
  28517. lastCached = bindingsForPath[ firstActiveIndex ],
  28518. last = bindingsForPath[ lastIndex ];
  28519. bindingsForPath[ index ] = lastCached;
  28520. bindingsForPath[ firstActiveIndex ] = last;
  28521. bindingsForPath.pop();
  28522. }
  28523. } else {
  28524. // object is active, just swap with the last and pop
  28525. var lastIndex = -- nObjects,
  28526. lastObject = objects[ lastIndex ];
  28527. indicesByUUID[ lastObject.uuid ] = index;
  28528. objects[ index ] = lastObject;
  28529. objects.pop();
  28530. // accounting is done, now do the same for all bindings
  28531. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28532. var bindingsForPath = bindings[ j ];
  28533. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  28534. bindingsForPath.pop();
  28535. }
  28536. } // cached or active
  28537. } // if object is known
  28538. } // for arguments
  28539. this.nCachedObjects_ = nCachedObjects;
  28540. },
  28541. // Internal interface used by befriended PropertyBinding.Composite:
  28542. subscribe_: function ( path, parsedPath ) {
  28543. // returns an array of bindings for the given path that is changed
  28544. // according to the contained objects in the group
  28545. var indicesByPath = this._bindingsIndicesByPath,
  28546. index = indicesByPath[ path ],
  28547. bindings = this._bindings;
  28548. if ( index !== undefined ) return bindings[ index ];
  28549. var paths = this._paths,
  28550. parsedPaths = this._parsedPaths,
  28551. objects = this._objects,
  28552. nObjects = objects.length,
  28553. nCachedObjects = this.nCachedObjects_,
  28554. bindingsForPath = new Array( nObjects );
  28555. index = bindings.length;
  28556. indicesByPath[ path ] = index;
  28557. paths.push( path );
  28558. parsedPaths.push( parsedPath );
  28559. bindings.push( bindingsForPath );
  28560. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  28561. var object = objects[ i ];
  28562. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  28563. }
  28564. return bindingsForPath;
  28565. },
  28566. unsubscribe_: function ( path ) {
  28567. // tells the group to forget about a property path and no longer
  28568. // update the array previously obtained with 'subscribe_'
  28569. var indicesByPath = this._bindingsIndicesByPath,
  28570. index = indicesByPath[ path ];
  28571. if ( index !== undefined ) {
  28572. var paths = this._paths,
  28573. parsedPaths = this._parsedPaths,
  28574. bindings = this._bindings,
  28575. lastBindingsIndex = bindings.length - 1,
  28576. lastBindings = bindings[ lastBindingsIndex ],
  28577. lastBindingsPath = path[ lastBindingsIndex ];
  28578. indicesByPath[ lastBindingsPath ] = index;
  28579. bindings[ index ] = lastBindings;
  28580. bindings.pop();
  28581. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  28582. parsedPaths.pop();
  28583. paths[ index ] = paths[ lastBindingsIndex ];
  28584. paths.pop();
  28585. }
  28586. }
  28587. } );
  28588. /**
  28589. *
  28590. * Action provided by AnimationMixer for scheduling clip playback on specific
  28591. * objects.
  28592. *
  28593. * @author Ben Houston / http://clara.io/
  28594. * @author David Sarno / http://lighthaus.us/
  28595. * @author tschw
  28596. *
  28597. */
  28598. function AnimationAction( mixer, clip, localRoot ) {
  28599. this._mixer = mixer;
  28600. this._clip = clip;
  28601. this._localRoot = localRoot || null;
  28602. var tracks = clip.tracks,
  28603. nTracks = tracks.length,
  28604. interpolants = new Array( nTracks );
  28605. var interpolantSettings = {
  28606. endingStart: ZeroCurvatureEnding,
  28607. endingEnd: ZeroCurvatureEnding
  28608. };
  28609. for ( var i = 0; i !== nTracks; ++ i ) {
  28610. var interpolant = tracks[ i ].createInterpolant( null );
  28611. interpolants[ i ] = interpolant;
  28612. interpolant.settings = interpolantSettings;
  28613. }
  28614. this._interpolantSettings = interpolantSettings;
  28615. this._interpolants = interpolants; // bound by the mixer
  28616. // inside: PropertyMixer (managed by the mixer)
  28617. this._propertyBindings = new Array( nTracks );
  28618. this._cacheIndex = null; // for the memory manager
  28619. this._byClipCacheIndex = null; // for the memory manager
  28620. this._timeScaleInterpolant = null;
  28621. this._weightInterpolant = null;
  28622. this.loop = LoopRepeat;
  28623. this._loopCount = - 1;
  28624. // global mixer time when the action is to be started
  28625. // it's set back to 'null' upon start of the action
  28626. this._startTime = null;
  28627. // scaled local time of the action
  28628. // gets clamped or wrapped to 0..clip.duration according to loop
  28629. this.time = 0;
  28630. this.timeScale = 1;
  28631. this._effectiveTimeScale = 1;
  28632. this.weight = 1;
  28633. this._effectiveWeight = 1;
  28634. this.repetitions = Infinity; // no. of repetitions when looping
  28635. this.paused = false; // true -> zero effective time scale
  28636. this.enabled = true; // false -> zero effective weight
  28637. this.clampWhenFinished = false; // keep feeding the last frame?
  28638. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  28639. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  28640. }
  28641. Object.assign( AnimationAction.prototype, {
  28642. // State & Scheduling
  28643. play: function () {
  28644. this._mixer._activateAction( this );
  28645. return this;
  28646. },
  28647. stop: function () {
  28648. this._mixer._deactivateAction( this );
  28649. return this.reset();
  28650. },
  28651. reset: function () {
  28652. this.paused = false;
  28653. this.enabled = true;
  28654. this.time = 0; // restart clip
  28655. this._loopCount = - 1; // forget previous loops
  28656. this._startTime = null; // forget scheduling
  28657. return this.stopFading().stopWarping();
  28658. },
  28659. isRunning: function () {
  28660. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  28661. this._startTime === null && this._mixer._isActiveAction( this );
  28662. },
  28663. // return true when play has been called
  28664. isScheduled: function () {
  28665. return this._mixer._isActiveAction( this );
  28666. },
  28667. startAt: function ( time ) {
  28668. this._startTime = time;
  28669. return this;
  28670. },
  28671. setLoop: function ( mode, repetitions ) {
  28672. this.loop = mode;
  28673. this.repetitions = repetitions;
  28674. return this;
  28675. },
  28676. // Weight
  28677. // set the weight stopping any scheduled fading
  28678. // although .enabled = false yields an effective weight of zero, this
  28679. // method does *not* change .enabled, because it would be confusing
  28680. setEffectiveWeight: function ( weight ) {
  28681. this.weight = weight;
  28682. // note: same logic as when updated at runtime
  28683. this._effectiveWeight = this.enabled ? weight : 0;
  28684. return this.stopFading();
  28685. },
  28686. // return the weight considering fading and .enabled
  28687. getEffectiveWeight: function () {
  28688. return this._effectiveWeight;
  28689. },
  28690. fadeIn: function ( duration ) {
  28691. return this._scheduleFading( duration, 0, 1 );
  28692. },
  28693. fadeOut: function ( duration ) {
  28694. return this._scheduleFading( duration, 1, 0 );
  28695. },
  28696. crossFadeFrom: function ( fadeOutAction, duration, warp ) {
  28697. fadeOutAction.fadeOut( duration );
  28698. this.fadeIn( duration );
  28699. if ( warp ) {
  28700. var fadeInDuration = this._clip.duration,
  28701. fadeOutDuration = fadeOutAction._clip.duration,
  28702. startEndRatio = fadeOutDuration / fadeInDuration,
  28703. endStartRatio = fadeInDuration / fadeOutDuration;
  28704. fadeOutAction.warp( 1.0, startEndRatio, duration );
  28705. this.warp( endStartRatio, 1.0, duration );
  28706. }
  28707. return this;
  28708. },
  28709. crossFadeTo: function ( fadeInAction, duration, warp ) {
  28710. return fadeInAction.crossFadeFrom( this, duration, warp );
  28711. },
  28712. stopFading: function () {
  28713. var weightInterpolant = this._weightInterpolant;
  28714. if ( weightInterpolant !== null ) {
  28715. this._weightInterpolant = null;
  28716. this._mixer._takeBackControlInterpolant( weightInterpolant );
  28717. }
  28718. return this;
  28719. },
  28720. // Time Scale Control
  28721. // set the time scale stopping any scheduled warping
  28722. // although .paused = true yields an effective time scale of zero, this
  28723. // method does *not* change .paused, because it would be confusing
  28724. setEffectiveTimeScale: function ( timeScale ) {
  28725. this.timeScale = timeScale;
  28726. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  28727. return this.stopWarping();
  28728. },
  28729. // return the time scale considering warping and .paused
  28730. getEffectiveTimeScale: function () {
  28731. return this._effectiveTimeScale;
  28732. },
  28733. setDuration: function ( duration ) {
  28734. this.timeScale = this._clip.duration / duration;
  28735. return this.stopWarping();
  28736. },
  28737. syncWith: function ( action ) {
  28738. this.time = action.time;
  28739. this.timeScale = action.timeScale;
  28740. return this.stopWarping();
  28741. },
  28742. halt: function ( duration ) {
  28743. return this.warp( this._effectiveTimeScale, 0, duration );
  28744. },
  28745. warp: function ( startTimeScale, endTimeScale, duration ) {
  28746. var mixer = this._mixer, now = mixer.time,
  28747. interpolant = this._timeScaleInterpolant,
  28748. timeScale = this.timeScale;
  28749. if ( interpolant === null ) {
  28750. interpolant = mixer._lendControlInterpolant();
  28751. this._timeScaleInterpolant = interpolant;
  28752. }
  28753. var times = interpolant.parameterPositions,
  28754. values = interpolant.sampleValues;
  28755. times[ 0 ] = now;
  28756. times[ 1 ] = now + duration;
  28757. values[ 0 ] = startTimeScale / timeScale;
  28758. values[ 1 ] = endTimeScale / timeScale;
  28759. return this;
  28760. },
  28761. stopWarping: function () {
  28762. var timeScaleInterpolant = this._timeScaleInterpolant;
  28763. if ( timeScaleInterpolant !== null ) {
  28764. this._timeScaleInterpolant = null;
  28765. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  28766. }
  28767. return this;
  28768. },
  28769. // Object Accessors
  28770. getMixer: function () {
  28771. return this._mixer;
  28772. },
  28773. getClip: function () {
  28774. return this._clip;
  28775. },
  28776. getRoot: function () {
  28777. return this._localRoot || this._mixer._root;
  28778. },
  28779. // Interna
  28780. _update: function ( time, deltaTime, timeDirection, accuIndex ) {
  28781. // called by the mixer
  28782. if ( ! this.enabled ) {
  28783. // call ._updateWeight() to update ._effectiveWeight
  28784. this._updateWeight( time );
  28785. return;
  28786. }
  28787. var startTime = this._startTime;
  28788. if ( startTime !== null ) {
  28789. // check for scheduled start of action
  28790. var timeRunning = ( time - startTime ) * timeDirection;
  28791. if ( timeRunning < 0 || timeDirection === 0 ) {
  28792. return; // yet to come / don't decide when delta = 0
  28793. }
  28794. // start
  28795. this._startTime = null; // unschedule
  28796. deltaTime = timeDirection * timeRunning;
  28797. }
  28798. // apply time scale and advance time
  28799. deltaTime *= this._updateTimeScale( time );
  28800. var clipTime = this._updateTime( deltaTime );
  28801. // note: _updateTime may disable the action resulting in
  28802. // an effective weight of 0
  28803. var weight = this._updateWeight( time );
  28804. if ( weight > 0 ) {
  28805. var interpolants = this._interpolants;
  28806. var propertyMixers = this._propertyBindings;
  28807. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  28808. interpolants[ j ].evaluate( clipTime );
  28809. propertyMixers[ j ].accumulate( accuIndex, weight );
  28810. }
  28811. }
  28812. },
  28813. _updateWeight: function ( time ) {
  28814. var weight = 0;
  28815. if ( this.enabled ) {
  28816. weight = this.weight;
  28817. var interpolant = this._weightInterpolant;
  28818. if ( interpolant !== null ) {
  28819. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  28820. weight *= interpolantValue;
  28821. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28822. this.stopFading();
  28823. if ( interpolantValue === 0 ) {
  28824. // faded out, disable
  28825. this.enabled = false;
  28826. }
  28827. }
  28828. }
  28829. }
  28830. this._effectiveWeight = weight;
  28831. return weight;
  28832. },
  28833. _updateTimeScale: function ( time ) {
  28834. var timeScale = 0;
  28835. if ( ! this.paused ) {
  28836. timeScale = this.timeScale;
  28837. var interpolant = this._timeScaleInterpolant;
  28838. if ( interpolant !== null ) {
  28839. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  28840. timeScale *= interpolantValue;
  28841. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28842. this.stopWarping();
  28843. if ( timeScale === 0 ) {
  28844. // motion has halted, pause
  28845. this.paused = true;
  28846. } else {
  28847. // warp done - apply final time scale
  28848. this.timeScale = timeScale;
  28849. }
  28850. }
  28851. }
  28852. }
  28853. this._effectiveTimeScale = timeScale;
  28854. return timeScale;
  28855. },
  28856. _updateTime: function ( deltaTime ) {
  28857. var time = this.time + deltaTime;
  28858. var duration = this._clip.duration;
  28859. var loop = this.loop;
  28860. var loopCount = this._loopCount;
  28861. var pingPong = ( loop === LoopPingPong );
  28862. if ( deltaTime === 0 ) {
  28863. if ( loopCount === - 1 ) return time;
  28864. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  28865. }
  28866. if ( loop === LoopOnce ) {
  28867. if ( loopCount === - 1 ) {
  28868. // just started
  28869. this._loopCount = 0;
  28870. this._setEndings( true, true, false );
  28871. }
  28872. handle_stop: {
  28873. if ( time >= duration ) {
  28874. time = duration;
  28875. } else if ( time < 0 ) {
  28876. time = 0;
  28877. } else break handle_stop;
  28878. if ( this.clampWhenFinished ) this.paused = true;
  28879. else this.enabled = false;
  28880. this._mixer.dispatchEvent( {
  28881. type: 'finished', action: this,
  28882. direction: deltaTime < 0 ? - 1 : 1
  28883. } );
  28884. }
  28885. } else { // repetitive Repeat or PingPong
  28886. if ( loopCount === - 1 ) {
  28887. // just started
  28888. if ( deltaTime >= 0 ) {
  28889. loopCount = 0;
  28890. this._setEndings( true, this.repetitions === 0, pingPong );
  28891. } else {
  28892. // when looping in reverse direction, the initial
  28893. // transition through zero counts as a repetition,
  28894. // so leave loopCount at -1
  28895. this._setEndings( this.repetitions === 0, true, pingPong );
  28896. }
  28897. }
  28898. if ( time >= duration || time < 0 ) {
  28899. // wrap around
  28900. var loopDelta = Math.floor( time / duration ); // signed
  28901. time -= duration * loopDelta;
  28902. loopCount += Math.abs( loopDelta );
  28903. var pending = this.repetitions - loopCount;
  28904. if ( pending <= 0 ) {
  28905. // have to stop (switch state, clamp time, fire event)
  28906. if ( this.clampWhenFinished ) this.paused = true;
  28907. else this.enabled = false;
  28908. time = deltaTime > 0 ? duration : 0;
  28909. this._mixer.dispatchEvent( {
  28910. type: 'finished', action: this,
  28911. direction: deltaTime > 0 ? 1 : - 1
  28912. } );
  28913. } else {
  28914. // keep running
  28915. if ( pending === 1 ) {
  28916. // entering the last round
  28917. var atStart = deltaTime < 0;
  28918. this._setEndings( atStart, ! atStart, pingPong );
  28919. } else {
  28920. this._setEndings( false, false, pingPong );
  28921. }
  28922. this._loopCount = loopCount;
  28923. this._mixer.dispatchEvent( {
  28924. type: 'loop', action: this, loopDelta: loopDelta
  28925. } );
  28926. }
  28927. }
  28928. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  28929. // invert time for the "pong round"
  28930. this.time = time;
  28931. return duration - time;
  28932. }
  28933. }
  28934. this.time = time;
  28935. return time;
  28936. },
  28937. _setEndings: function ( atStart, atEnd, pingPong ) {
  28938. var settings = this._interpolantSettings;
  28939. if ( pingPong ) {
  28940. settings.endingStart = ZeroSlopeEnding;
  28941. settings.endingEnd = ZeroSlopeEnding;
  28942. } else {
  28943. // assuming for LoopOnce atStart == atEnd == true
  28944. if ( atStart ) {
  28945. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28946. } else {
  28947. settings.endingStart = WrapAroundEnding;
  28948. }
  28949. if ( atEnd ) {
  28950. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28951. } else {
  28952. settings.endingEnd = WrapAroundEnding;
  28953. }
  28954. }
  28955. },
  28956. _scheduleFading: function ( duration, weightNow, weightThen ) {
  28957. var mixer = this._mixer, now = mixer.time,
  28958. interpolant = this._weightInterpolant;
  28959. if ( interpolant === null ) {
  28960. interpolant = mixer._lendControlInterpolant();
  28961. this._weightInterpolant = interpolant;
  28962. }
  28963. var times = interpolant.parameterPositions,
  28964. values = interpolant.sampleValues;
  28965. times[ 0 ] = now; values[ 0 ] = weightNow;
  28966. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  28967. return this;
  28968. }
  28969. } );
  28970. /**
  28971. *
  28972. * Player for AnimationClips.
  28973. *
  28974. *
  28975. * @author Ben Houston / http://clara.io/
  28976. * @author David Sarno / http://lighthaus.us/
  28977. * @author tschw
  28978. */
  28979. function AnimationMixer( root ) {
  28980. this._root = root;
  28981. this._initMemoryManager();
  28982. this._accuIndex = 0;
  28983. this.time = 0;
  28984. this.timeScale = 1.0;
  28985. }
  28986. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  28987. constructor: AnimationMixer,
  28988. _bindAction: function ( action, prototypeAction ) {
  28989. var root = action._localRoot || this._root,
  28990. tracks = action._clip.tracks,
  28991. nTracks = tracks.length,
  28992. bindings = action._propertyBindings,
  28993. interpolants = action._interpolants,
  28994. rootUuid = root.uuid,
  28995. bindingsByRoot = this._bindingsByRootAndName,
  28996. bindingsByName = bindingsByRoot[ rootUuid ];
  28997. if ( bindingsByName === undefined ) {
  28998. bindingsByName = {};
  28999. bindingsByRoot[ rootUuid ] = bindingsByName;
  29000. }
  29001. for ( var i = 0; i !== nTracks; ++ i ) {
  29002. var track = tracks[ i ],
  29003. trackName = track.name,
  29004. binding = bindingsByName[ trackName ];
  29005. if ( binding !== undefined ) {
  29006. bindings[ i ] = binding;
  29007. } else {
  29008. binding = bindings[ i ];
  29009. if ( binding !== undefined ) {
  29010. // existing binding, make sure the cache knows
  29011. if ( binding._cacheIndex === null ) {
  29012. ++ binding.referenceCount;
  29013. this._addInactiveBinding( binding, rootUuid, trackName );
  29014. }
  29015. continue;
  29016. }
  29017. var path = prototypeAction && prototypeAction.
  29018. _propertyBindings[ i ].binding.parsedPath;
  29019. binding = new PropertyMixer(
  29020. PropertyBinding.create( root, trackName, path ),
  29021. track.ValueTypeName, track.getValueSize() );
  29022. ++ binding.referenceCount;
  29023. this._addInactiveBinding( binding, rootUuid, trackName );
  29024. bindings[ i ] = binding;
  29025. }
  29026. interpolants[ i ].resultBuffer = binding.buffer;
  29027. }
  29028. },
  29029. _activateAction: function ( action ) {
  29030. if ( ! this._isActiveAction( action ) ) {
  29031. if ( action._cacheIndex === null ) {
  29032. // this action has been forgotten by the cache, but the user
  29033. // appears to be still using it -> rebind
  29034. var rootUuid = ( action._localRoot || this._root ).uuid,
  29035. clipUuid = action._clip.uuid,
  29036. actionsForClip = this._actionsByClip[ clipUuid ];
  29037. this._bindAction( action,
  29038. actionsForClip && actionsForClip.knownActions[ 0 ] );
  29039. this._addInactiveAction( action, clipUuid, rootUuid );
  29040. }
  29041. var bindings = action._propertyBindings;
  29042. // increment reference counts / sort out state
  29043. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  29044. var binding = bindings[ i ];
  29045. if ( binding.useCount ++ === 0 ) {
  29046. this._lendBinding( binding );
  29047. binding.saveOriginalState();
  29048. }
  29049. }
  29050. this._lendAction( action );
  29051. }
  29052. },
  29053. _deactivateAction: function ( action ) {
  29054. if ( this._isActiveAction( action ) ) {
  29055. var bindings = action._propertyBindings;
  29056. // decrement reference counts / sort out state
  29057. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  29058. var binding = bindings[ i ];
  29059. if ( -- binding.useCount === 0 ) {
  29060. binding.restoreOriginalState();
  29061. this._takeBackBinding( binding );
  29062. }
  29063. }
  29064. this._takeBackAction( action );
  29065. }
  29066. },
  29067. // Memory manager
  29068. _initMemoryManager: function () {
  29069. this._actions = []; // 'nActiveActions' followed by inactive ones
  29070. this._nActiveActions = 0;
  29071. this._actionsByClip = {};
  29072. // inside:
  29073. // {
  29074. // knownActions: Array< AnimationAction > - used as prototypes
  29075. // actionByRoot: AnimationAction - lookup
  29076. // }
  29077. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  29078. this._nActiveBindings = 0;
  29079. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  29080. this._controlInterpolants = []; // same game as above
  29081. this._nActiveControlInterpolants = 0;
  29082. var scope = this;
  29083. this.stats = {
  29084. actions: {
  29085. get total() {
  29086. return scope._actions.length;
  29087. },
  29088. get inUse() {
  29089. return scope._nActiveActions;
  29090. }
  29091. },
  29092. bindings: {
  29093. get total() {
  29094. return scope._bindings.length;
  29095. },
  29096. get inUse() {
  29097. return scope._nActiveBindings;
  29098. }
  29099. },
  29100. controlInterpolants: {
  29101. get total() {
  29102. return scope._controlInterpolants.length;
  29103. },
  29104. get inUse() {
  29105. return scope._nActiveControlInterpolants;
  29106. }
  29107. }
  29108. };
  29109. },
  29110. // Memory management for AnimationAction objects
  29111. _isActiveAction: function ( action ) {
  29112. var index = action._cacheIndex;
  29113. return index !== null && index < this._nActiveActions;
  29114. },
  29115. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  29116. var actions = this._actions,
  29117. actionsByClip = this._actionsByClip,
  29118. actionsForClip = actionsByClip[ clipUuid ];
  29119. if ( actionsForClip === undefined ) {
  29120. actionsForClip = {
  29121. knownActions: [ action ],
  29122. actionByRoot: {}
  29123. };
  29124. action._byClipCacheIndex = 0;
  29125. actionsByClip[ clipUuid ] = actionsForClip;
  29126. } else {
  29127. var knownActions = actionsForClip.knownActions;
  29128. action._byClipCacheIndex = knownActions.length;
  29129. knownActions.push( action );
  29130. }
  29131. action._cacheIndex = actions.length;
  29132. actions.push( action );
  29133. actionsForClip.actionByRoot[ rootUuid ] = action;
  29134. },
  29135. _removeInactiveAction: function ( action ) {
  29136. var actions = this._actions,
  29137. lastInactiveAction = actions[ actions.length - 1 ],
  29138. cacheIndex = action._cacheIndex;
  29139. lastInactiveAction._cacheIndex = cacheIndex;
  29140. actions[ cacheIndex ] = lastInactiveAction;
  29141. actions.pop();
  29142. action._cacheIndex = null;
  29143. var clipUuid = action._clip.uuid,
  29144. actionsByClip = this._actionsByClip,
  29145. actionsForClip = actionsByClip[ clipUuid ],
  29146. knownActionsForClip = actionsForClip.knownActions,
  29147. lastKnownAction =
  29148. knownActionsForClip[ knownActionsForClip.length - 1 ],
  29149. byClipCacheIndex = action._byClipCacheIndex;
  29150. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  29151. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  29152. knownActionsForClip.pop();
  29153. action._byClipCacheIndex = null;
  29154. var actionByRoot = actionsForClip.actionByRoot,
  29155. rootUuid = ( action._localRoot || this._root ).uuid;
  29156. delete actionByRoot[ rootUuid ];
  29157. if ( knownActionsForClip.length === 0 ) {
  29158. delete actionsByClip[ clipUuid ];
  29159. }
  29160. this._removeInactiveBindingsForAction( action );
  29161. },
  29162. _removeInactiveBindingsForAction: function ( action ) {
  29163. var bindings = action._propertyBindings;
  29164. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  29165. var binding = bindings[ i ];
  29166. if ( -- binding.referenceCount === 0 ) {
  29167. this._removeInactiveBinding( binding );
  29168. }
  29169. }
  29170. },
  29171. _lendAction: function ( action ) {
  29172. // [ active actions | inactive actions ]
  29173. // [ active actions >| inactive actions ]
  29174. // s a
  29175. // <-swap->
  29176. // a s
  29177. var actions = this._actions,
  29178. prevIndex = action._cacheIndex,
  29179. lastActiveIndex = this._nActiveActions ++,
  29180. firstInactiveAction = actions[ lastActiveIndex ];
  29181. action._cacheIndex = lastActiveIndex;
  29182. actions[ lastActiveIndex ] = action;
  29183. firstInactiveAction._cacheIndex = prevIndex;
  29184. actions[ prevIndex ] = firstInactiveAction;
  29185. },
  29186. _takeBackAction: function ( action ) {
  29187. // [ active actions | inactive actions ]
  29188. // [ active actions |< inactive actions ]
  29189. // a s
  29190. // <-swap->
  29191. // s a
  29192. var actions = this._actions,
  29193. prevIndex = action._cacheIndex,
  29194. firstInactiveIndex = -- this._nActiveActions,
  29195. lastActiveAction = actions[ firstInactiveIndex ];
  29196. action._cacheIndex = firstInactiveIndex;
  29197. actions[ firstInactiveIndex ] = action;
  29198. lastActiveAction._cacheIndex = prevIndex;
  29199. actions[ prevIndex ] = lastActiveAction;
  29200. },
  29201. // Memory management for PropertyMixer objects
  29202. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  29203. var bindingsByRoot = this._bindingsByRootAndName,
  29204. bindingByName = bindingsByRoot[ rootUuid ],
  29205. bindings = this._bindings;
  29206. if ( bindingByName === undefined ) {
  29207. bindingByName = {};
  29208. bindingsByRoot[ rootUuid ] = bindingByName;
  29209. }
  29210. bindingByName[ trackName ] = binding;
  29211. binding._cacheIndex = bindings.length;
  29212. bindings.push( binding );
  29213. },
  29214. _removeInactiveBinding: function ( binding ) {
  29215. var bindings = this._bindings,
  29216. propBinding = binding.binding,
  29217. rootUuid = propBinding.rootNode.uuid,
  29218. trackName = propBinding.path,
  29219. bindingsByRoot = this._bindingsByRootAndName,
  29220. bindingByName = bindingsByRoot[ rootUuid ],
  29221. lastInactiveBinding = bindings[ bindings.length - 1 ],
  29222. cacheIndex = binding._cacheIndex;
  29223. lastInactiveBinding._cacheIndex = cacheIndex;
  29224. bindings[ cacheIndex ] = lastInactiveBinding;
  29225. bindings.pop();
  29226. delete bindingByName[ trackName ];
  29227. remove_empty_map: {
  29228. for ( var _ in bindingByName ) break remove_empty_map; // eslint-disable-line no-unused-vars
  29229. delete bindingsByRoot[ rootUuid ];
  29230. }
  29231. },
  29232. _lendBinding: function ( binding ) {
  29233. var bindings = this._bindings,
  29234. prevIndex = binding._cacheIndex,
  29235. lastActiveIndex = this._nActiveBindings ++,
  29236. firstInactiveBinding = bindings[ lastActiveIndex ];
  29237. binding._cacheIndex = lastActiveIndex;
  29238. bindings[ lastActiveIndex ] = binding;
  29239. firstInactiveBinding._cacheIndex = prevIndex;
  29240. bindings[ prevIndex ] = firstInactiveBinding;
  29241. },
  29242. _takeBackBinding: function ( binding ) {
  29243. var bindings = this._bindings,
  29244. prevIndex = binding._cacheIndex,
  29245. firstInactiveIndex = -- this._nActiveBindings,
  29246. lastActiveBinding = bindings[ firstInactiveIndex ];
  29247. binding._cacheIndex = firstInactiveIndex;
  29248. bindings[ firstInactiveIndex ] = binding;
  29249. lastActiveBinding._cacheIndex = prevIndex;
  29250. bindings[ prevIndex ] = lastActiveBinding;
  29251. },
  29252. // Memory management of Interpolants for weight and time scale
  29253. _lendControlInterpolant: function () {
  29254. var interpolants = this._controlInterpolants,
  29255. lastActiveIndex = this._nActiveControlInterpolants ++,
  29256. interpolant = interpolants[ lastActiveIndex ];
  29257. if ( interpolant === undefined ) {
  29258. interpolant = new LinearInterpolant(
  29259. new Float32Array( 2 ), new Float32Array( 2 ),
  29260. 1, this._controlInterpolantsResultBuffer );
  29261. interpolant.__cacheIndex = lastActiveIndex;
  29262. interpolants[ lastActiveIndex ] = interpolant;
  29263. }
  29264. return interpolant;
  29265. },
  29266. _takeBackControlInterpolant: function ( interpolant ) {
  29267. var interpolants = this._controlInterpolants,
  29268. prevIndex = interpolant.__cacheIndex,
  29269. firstInactiveIndex = -- this._nActiveControlInterpolants,
  29270. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  29271. interpolant.__cacheIndex = firstInactiveIndex;
  29272. interpolants[ firstInactiveIndex ] = interpolant;
  29273. lastActiveInterpolant.__cacheIndex = prevIndex;
  29274. interpolants[ prevIndex ] = lastActiveInterpolant;
  29275. },
  29276. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  29277. // return an action for a clip optionally using a custom root target
  29278. // object (this method allocates a lot of dynamic memory in case a
  29279. // previously unknown clip/root combination is specified)
  29280. clipAction: function ( clip, optionalRoot ) {
  29281. var root = optionalRoot || this._root,
  29282. rootUuid = root.uuid,
  29283. clipObject = typeof clip === 'string' ?
  29284. AnimationClip.findByName( root, clip ) : clip,
  29285. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  29286. actionsForClip = this._actionsByClip[ clipUuid ],
  29287. prototypeAction = null;
  29288. if ( actionsForClip !== undefined ) {
  29289. var existingAction =
  29290. actionsForClip.actionByRoot[ rootUuid ];
  29291. if ( existingAction !== undefined ) {
  29292. return existingAction;
  29293. }
  29294. // we know the clip, so we don't have to parse all
  29295. // the bindings again but can just copy
  29296. prototypeAction = actionsForClip.knownActions[ 0 ];
  29297. // also, take the clip from the prototype action
  29298. if ( clipObject === null )
  29299. clipObject = prototypeAction._clip;
  29300. }
  29301. // clip must be known when specified via string
  29302. if ( clipObject === null ) return null;
  29303. // allocate all resources required to run it
  29304. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  29305. this._bindAction( newAction, prototypeAction );
  29306. // and make the action known to the memory manager
  29307. this._addInactiveAction( newAction, clipUuid, rootUuid );
  29308. return newAction;
  29309. },
  29310. // get an existing action
  29311. existingAction: function ( clip, optionalRoot ) {
  29312. var root = optionalRoot || this._root,
  29313. rootUuid = root.uuid,
  29314. clipObject = typeof clip === 'string' ?
  29315. AnimationClip.findByName( root, clip ) : clip,
  29316. clipUuid = clipObject ? clipObject.uuid : clip,
  29317. actionsForClip = this._actionsByClip[ clipUuid ];
  29318. if ( actionsForClip !== undefined ) {
  29319. return actionsForClip.actionByRoot[ rootUuid ] || null;
  29320. }
  29321. return null;
  29322. },
  29323. // deactivates all previously scheduled actions
  29324. stopAllAction: function () {
  29325. var actions = this._actions,
  29326. nActions = this._nActiveActions,
  29327. bindings = this._bindings,
  29328. nBindings = this._nActiveBindings;
  29329. this._nActiveActions = 0;
  29330. this._nActiveBindings = 0;
  29331. for ( var i = 0; i !== nActions; ++ i ) {
  29332. actions[ i ].reset();
  29333. }
  29334. for ( var i = 0; i !== nBindings; ++ i ) {
  29335. bindings[ i ].useCount = 0;
  29336. }
  29337. return this;
  29338. },
  29339. // advance the time and update apply the animation
  29340. update: function ( deltaTime ) {
  29341. deltaTime *= this.timeScale;
  29342. var actions = this._actions,
  29343. nActions = this._nActiveActions,
  29344. time = this.time += deltaTime,
  29345. timeDirection = Math.sign( deltaTime ),
  29346. accuIndex = this._accuIndex ^= 1;
  29347. // run active actions
  29348. for ( var i = 0; i !== nActions; ++ i ) {
  29349. var action = actions[ i ];
  29350. action._update( time, deltaTime, timeDirection, accuIndex );
  29351. }
  29352. // update scene graph
  29353. var bindings = this._bindings,
  29354. nBindings = this._nActiveBindings;
  29355. for ( var i = 0; i !== nBindings; ++ i ) {
  29356. bindings[ i ].apply( accuIndex );
  29357. }
  29358. return this;
  29359. },
  29360. // return this mixer's root target object
  29361. getRoot: function () {
  29362. return this._root;
  29363. },
  29364. // free all resources specific to a particular clip
  29365. uncacheClip: function ( clip ) {
  29366. var actions = this._actions,
  29367. clipUuid = clip.uuid,
  29368. actionsByClip = this._actionsByClip,
  29369. actionsForClip = actionsByClip[ clipUuid ];
  29370. if ( actionsForClip !== undefined ) {
  29371. // note: just calling _removeInactiveAction would mess up the
  29372. // iteration state and also require updating the state we can
  29373. // just throw away
  29374. var actionsToRemove = actionsForClip.knownActions;
  29375. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  29376. var action = actionsToRemove[ i ];
  29377. this._deactivateAction( action );
  29378. var cacheIndex = action._cacheIndex,
  29379. lastInactiveAction = actions[ actions.length - 1 ];
  29380. action._cacheIndex = null;
  29381. action._byClipCacheIndex = null;
  29382. lastInactiveAction._cacheIndex = cacheIndex;
  29383. actions[ cacheIndex ] = lastInactiveAction;
  29384. actions.pop();
  29385. this._removeInactiveBindingsForAction( action );
  29386. }
  29387. delete actionsByClip[ clipUuid ];
  29388. }
  29389. },
  29390. // free all resources specific to a particular root target object
  29391. uncacheRoot: function ( root ) {
  29392. var rootUuid = root.uuid,
  29393. actionsByClip = this._actionsByClip;
  29394. for ( var clipUuid in actionsByClip ) {
  29395. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  29396. action = actionByRoot[ rootUuid ];
  29397. if ( action !== undefined ) {
  29398. this._deactivateAction( action );
  29399. this._removeInactiveAction( action );
  29400. }
  29401. }
  29402. var bindingsByRoot = this._bindingsByRootAndName,
  29403. bindingByName = bindingsByRoot[ rootUuid ];
  29404. if ( bindingByName !== undefined ) {
  29405. for ( var trackName in bindingByName ) {
  29406. var binding = bindingByName[ trackName ];
  29407. binding.restoreOriginalState();
  29408. this._removeInactiveBinding( binding );
  29409. }
  29410. }
  29411. },
  29412. // remove a targeted clip from the cache
  29413. uncacheAction: function ( clip, optionalRoot ) {
  29414. var action = this.existingAction( clip, optionalRoot );
  29415. if ( action !== null ) {
  29416. this._deactivateAction( action );
  29417. this._removeInactiveAction( action );
  29418. }
  29419. }
  29420. } );
  29421. /**
  29422. * @author mrdoob / http://mrdoob.com/
  29423. */
  29424. function Uniform( value ) {
  29425. if ( typeof value === 'string' ) {
  29426. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  29427. value = arguments[ 1 ];
  29428. }
  29429. this.value = value;
  29430. }
  29431. Uniform.prototype.clone = function () {
  29432. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  29433. };
  29434. /**
  29435. * @author benaadams / https://twitter.com/ben_a_adams
  29436. */
  29437. function InstancedBufferGeometry() {
  29438. BufferGeometry.call( this );
  29439. this.type = 'InstancedBufferGeometry';
  29440. this.maxInstancedCount = undefined;
  29441. }
  29442. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  29443. constructor: InstancedBufferGeometry,
  29444. isInstancedBufferGeometry: true,
  29445. copy: function ( source ) {
  29446. BufferGeometry.prototype.copy.call( this, source );
  29447. this.maxInstancedCount = source.maxInstancedCount;
  29448. return this;
  29449. },
  29450. clone: function () {
  29451. return new this.constructor().copy( this );
  29452. }
  29453. } );
  29454. /**
  29455. * @author benaadams / https://twitter.com/ben_a_adams
  29456. */
  29457. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  29458. InterleavedBuffer.call( this, array, stride );
  29459. this.meshPerAttribute = meshPerAttribute || 1;
  29460. }
  29461. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  29462. constructor: InstancedInterleavedBuffer,
  29463. isInstancedInterleavedBuffer: true,
  29464. copy: function ( source ) {
  29465. InterleavedBuffer.prototype.copy.call( this, source );
  29466. this.meshPerAttribute = source.meshPerAttribute;
  29467. return this;
  29468. }
  29469. } );
  29470. /**
  29471. * @author benaadams / https://twitter.com/ben_a_adams
  29472. */
  29473. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  29474. BufferAttribute.call( this, array, itemSize );
  29475. this.meshPerAttribute = meshPerAttribute || 1;
  29476. }
  29477. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  29478. constructor: InstancedBufferAttribute,
  29479. isInstancedBufferAttribute: true,
  29480. copy: function ( source ) {
  29481. BufferAttribute.prototype.copy.call( this, source );
  29482. this.meshPerAttribute = source.meshPerAttribute;
  29483. return this;
  29484. }
  29485. } );
  29486. /**
  29487. * @author mrdoob / http://mrdoob.com/
  29488. * @author bhouston / http://clara.io/
  29489. * @author stephomi / http://stephaneginier.com/
  29490. */
  29491. function Raycaster( origin, direction, near, far ) {
  29492. this.ray = new Ray( origin, direction );
  29493. // direction is assumed to be normalized (for accurate distance calculations)
  29494. this.near = near || 0;
  29495. this.far = far || Infinity;
  29496. this.params = {
  29497. Mesh: {},
  29498. Line: {},
  29499. LOD: {},
  29500. Points: { threshold: 1 },
  29501. Sprite: {}
  29502. };
  29503. Object.defineProperties( this.params, {
  29504. PointCloud: {
  29505. get: function () {
  29506. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  29507. return this.Points;
  29508. }
  29509. }
  29510. } );
  29511. }
  29512. function ascSort( a, b ) {
  29513. return a.distance - b.distance;
  29514. }
  29515. function intersectObject( object, raycaster, intersects, recursive ) {
  29516. if ( object.visible === false ) return;
  29517. object.raycast( raycaster, intersects );
  29518. if ( recursive === true ) {
  29519. var children = object.children;
  29520. for ( var i = 0, l = children.length; i < l; i ++ ) {
  29521. intersectObject( children[ i ], raycaster, intersects, true );
  29522. }
  29523. }
  29524. }
  29525. Object.assign( Raycaster.prototype, {
  29526. linePrecision: 1,
  29527. set: function ( origin, direction ) {
  29528. // direction is assumed to be normalized (for accurate distance calculations)
  29529. this.ray.set( origin, direction );
  29530. },
  29531. setFromCamera: function ( coords, camera ) {
  29532. if ( ( camera && camera.isPerspectiveCamera ) ) {
  29533. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  29534. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  29535. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  29536. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  29537. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  29538. } else {
  29539. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  29540. }
  29541. },
  29542. intersectObject: function ( object, recursive, optionalTarget ) {
  29543. var intersects = optionalTarget || [];
  29544. intersectObject( object, this, intersects, recursive );
  29545. intersects.sort( ascSort );
  29546. return intersects;
  29547. },
  29548. intersectObjects: function ( objects, recursive, optionalTarget ) {
  29549. var intersects = optionalTarget || [];
  29550. if ( Array.isArray( objects ) === false ) {
  29551. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  29552. return intersects;
  29553. }
  29554. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  29555. intersectObject( objects[ i ], this, intersects, recursive );
  29556. }
  29557. intersects.sort( ascSort );
  29558. return intersects;
  29559. }
  29560. } );
  29561. /**
  29562. * @author alteredq / http://alteredqualia.com/
  29563. */
  29564. function Clock( autoStart ) {
  29565. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  29566. this.startTime = 0;
  29567. this.oldTime = 0;
  29568. this.elapsedTime = 0;
  29569. this.running = false;
  29570. }
  29571. Object.assign( Clock.prototype, {
  29572. start: function () {
  29573. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  29574. this.oldTime = this.startTime;
  29575. this.elapsedTime = 0;
  29576. this.running = true;
  29577. },
  29578. stop: function () {
  29579. this.getElapsedTime();
  29580. this.running = false;
  29581. this.autoStart = false;
  29582. },
  29583. getElapsedTime: function () {
  29584. this.getDelta();
  29585. return this.elapsedTime;
  29586. },
  29587. getDelta: function () {
  29588. var diff = 0;
  29589. if ( this.autoStart && ! this.running ) {
  29590. this.start();
  29591. return 0;
  29592. }
  29593. if ( this.running ) {
  29594. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  29595. diff = ( newTime - this.oldTime ) / 1000;
  29596. this.oldTime = newTime;
  29597. this.elapsedTime += diff;
  29598. }
  29599. return diff;
  29600. }
  29601. } );
  29602. /**
  29603. * @author bhouston / http://clara.io
  29604. * @author WestLangley / http://github.com/WestLangley
  29605. *
  29606. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  29607. *
  29608. * The poles (phi) are at the positive and negative y axis.
  29609. * The equator starts at positive z.
  29610. */
  29611. function Spherical( radius, phi, theta ) {
  29612. this.radius = ( radius !== undefined ) ? radius : 1.0;
  29613. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  29614. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  29615. return this;
  29616. }
  29617. Object.assign( Spherical.prototype, {
  29618. set: function ( radius, phi, theta ) {
  29619. this.radius = radius;
  29620. this.phi = phi;
  29621. this.theta = theta;
  29622. return this;
  29623. },
  29624. clone: function () {
  29625. return new this.constructor().copy( this );
  29626. },
  29627. copy: function ( other ) {
  29628. this.radius = other.radius;
  29629. this.phi = other.phi;
  29630. this.theta = other.theta;
  29631. return this;
  29632. },
  29633. // restrict phi to be betwee EPS and PI-EPS
  29634. makeSafe: function () {
  29635. var EPS = 0.000001;
  29636. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  29637. return this;
  29638. },
  29639. setFromVector3: function ( vec3 ) {
  29640. this.radius = vec3.length();
  29641. if ( this.radius === 0 ) {
  29642. this.theta = 0;
  29643. this.phi = 0;
  29644. } else {
  29645. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  29646. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  29647. }
  29648. return this;
  29649. }
  29650. } );
  29651. /**
  29652. * @author Mugen87 / https://github.com/Mugen87
  29653. *
  29654. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  29655. *
  29656. */
  29657. function Cylindrical( radius, theta, y ) {
  29658. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  29659. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  29660. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  29661. return this;
  29662. }
  29663. Object.assign( Cylindrical.prototype, {
  29664. set: function ( radius, theta, y ) {
  29665. this.radius = radius;
  29666. this.theta = theta;
  29667. this.y = y;
  29668. return this;
  29669. },
  29670. clone: function () {
  29671. return new this.constructor().copy( this );
  29672. },
  29673. copy: function ( other ) {
  29674. this.radius = other.radius;
  29675. this.theta = other.theta;
  29676. this.y = other.y;
  29677. return this;
  29678. },
  29679. setFromVector3: function ( vec3 ) {
  29680. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  29681. this.theta = Math.atan2( vec3.x, vec3.z );
  29682. this.y = vec3.y;
  29683. return this;
  29684. }
  29685. } );
  29686. /**
  29687. * @author bhouston / http://clara.io
  29688. */
  29689. function Box2( min, max ) {
  29690. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  29691. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  29692. }
  29693. Object.assign( Box2.prototype, {
  29694. set: function ( min, max ) {
  29695. this.min.copy( min );
  29696. this.max.copy( max );
  29697. return this;
  29698. },
  29699. setFromPoints: function ( points ) {
  29700. this.makeEmpty();
  29701. for ( var i = 0, il = points.length; i < il; i ++ ) {
  29702. this.expandByPoint( points[ i ] );
  29703. }
  29704. return this;
  29705. },
  29706. setFromCenterAndSize: function () {
  29707. var v1 = new Vector2();
  29708. return function setFromCenterAndSize( center, size ) {
  29709. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  29710. this.min.copy( center ).sub( halfSize );
  29711. this.max.copy( center ).add( halfSize );
  29712. return this;
  29713. };
  29714. }(),
  29715. clone: function () {
  29716. return new this.constructor().copy( this );
  29717. },
  29718. copy: function ( box ) {
  29719. this.min.copy( box.min );
  29720. this.max.copy( box.max );
  29721. return this;
  29722. },
  29723. makeEmpty: function () {
  29724. this.min.x = this.min.y = + Infinity;
  29725. this.max.x = this.max.y = - Infinity;
  29726. return this;
  29727. },
  29728. isEmpty: function () {
  29729. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  29730. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  29731. },
  29732. getCenter: function ( target ) {
  29733. if ( target === undefined ) {
  29734. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  29735. target = new Vector2();
  29736. }
  29737. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  29738. },
  29739. getSize: function ( target ) {
  29740. if ( target === undefined ) {
  29741. console.warn( 'THREE.Box2: .getSize() target is now required' );
  29742. target = new Vector2();
  29743. }
  29744. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  29745. },
  29746. expandByPoint: function ( point ) {
  29747. this.min.min( point );
  29748. this.max.max( point );
  29749. return this;
  29750. },
  29751. expandByVector: function ( vector ) {
  29752. this.min.sub( vector );
  29753. this.max.add( vector );
  29754. return this;
  29755. },
  29756. expandByScalar: function ( scalar ) {
  29757. this.min.addScalar( - scalar );
  29758. this.max.addScalar( scalar );
  29759. return this;
  29760. },
  29761. containsPoint: function ( point ) {
  29762. return point.x < this.min.x || point.x > this.max.x ||
  29763. point.y < this.min.y || point.y > this.max.y ? false : true;
  29764. },
  29765. containsBox: function ( box ) {
  29766. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  29767. this.min.y <= box.min.y && box.max.y <= this.max.y;
  29768. },
  29769. getParameter: function ( point, target ) {
  29770. // This can potentially have a divide by zero if the box
  29771. // has a size dimension of 0.
  29772. if ( target === undefined ) {
  29773. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  29774. target = new Vector2();
  29775. }
  29776. return target.set(
  29777. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  29778. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  29779. );
  29780. },
  29781. intersectsBox: function ( box ) {
  29782. // using 4 splitting planes to rule out intersections
  29783. return box.max.x < this.min.x || box.min.x > this.max.x ||
  29784. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  29785. },
  29786. clampPoint: function ( point, target ) {
  29787. if ( target === undefined ) {
  29788. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  29789. target = new Vector2();
  29790. }
  29791. return target.copy( point ).clamp( this.min, this.max );
  29792. },
  29793. distanceToPoint: function () {
  29794. var v1 = new Vector2();
  29795. return function distanceToPoint( point ) {
  29796. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  29797. return clampedPoint.sub( point ).length();
  29798. };
  29799. }(),
  29800. intersect: function ( box ) {
  29801. this.min.max( box.min );
  29802. this.max.min( box.max );
  29803. return this;
  29804. },
  29805. union: function ( box ) {
  29806. this.min.min( box.min );
  29807. this.max.max( box.max );
  29808. return this;
  29809. },
  29810. translate: function ( offset ) {
  29811. this.min.add( offset );
  29812. this.max.add( offset );
  29813. return this;
  29814. },
  29815. equals: function ( box ) {
  29816. return box.min.equals( this.min ) && box.max.equals( this.max );
  29817. }
  29818. } );
  29819. /**
  29820. * @author bhouston / http://clara.io
  29821. */
  29822. function Line3( start, end ) {
  29823. this.start = ( start !== undefined ) ? start : new Vector3();
  29824. this.end = ( end !== undefined ) ? end : new Vector3();
  29825. }
  29826. Object.assign( Line3.prototype, {
  29827. set: function ( start, end ) {
  29828. this.start.copy( start );
  29829. this.end.copy( end );
  29830. return this;
  29831. },
  29832. clone: function () {
  29833. return new this.constructor().copy( this );
  29834. },
  29835. copy: function ( line ) {
  29836. this.start.copy( line.start );
  29837. this.end.copy( line.end );
  29838. return this;
  29839. },
  29840. getCenter: function ( target ) {
  29841. if ( target === undefined ) {
  29842. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  29843. target = new Vector3();
  29844. }
  29845. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  29846. },
  29847. delta: function ( target ) {
  29848. if ( target === undefined ) {
  29849. console.warn( 'THREE.Line3: .delta() target is now required' );
  29850. target = new Vector3();
  29851. }
  29852. return target.subVectors( this.end, this.start );
  29853. },
  29854. distanceSq: function () {
  29855. return this.start.distanceToSquared( this.end );
  29856. },
  29857. distance: function () {
  29858. return this.start.distanceTo( this.end );
  29859. },
  29860. at: function ( t, target ) {
  29861. if ( target === undefined ) {
  29862. console.warn( 'THREE.Line3: .at() target is now required' );
  29863. target = new Vector3();
  29864. }
  29865. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29866. },
  29867. closestPointToPointParameter: function () {
  29868. var startP = new Vector3();
  29869. var startEnd = new Vector3();
  29870. return function closestPointToPointParameter( point, clampToLine ) {
  29871. startP.subVectors( point, this.start );
  29872. startEnd.subVectors( this.end, this.start );
  29873. var startEnd2 = startEnd.dot( startEnd );
  29874. var startEnd_startP = startEnd.dot( startP );
  29875. var t = startEnd_startP / startEnd2;
  29876. if ( clampToLine ) {
  29877. t = _Math.clamp( t, 0, 1 );
  29878. }
  29879. return t;
  29880. };
  29881. }(),
  29882. closestPointToPoint: function ( point, clampToLine, target ) {
  29883. var t = this.closestPointToPointParameter( point, clampToLine );
  29884. if ( target === undefined ) {
  29885. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  29886. target = new Vector3();
  29887. }
  29888. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29889. },
  29890. applyMatrix4: function ( matrix ) {
  29891. this.start.applyMatrix4( matrix );
  29892. this.end.applyMatrix4( matrix );
  29893. return this;
  29894. },
  29895. equals: function ( line ) {
  29896. return line.start.equals( this.start ) && line.end.equals( this.end );
  29897. }
  29898. } );
  29899. /**
  29900. * @author alteredq / http://alteredqualia.com/
  29901. */
  29902. function ImmediateRenderObject( material ) {
  29903. Object3D.call( this );
  29904. this.material = material;
  29905. this.render = function ( /* renderCallback */ ) {};
  29906. }
  29907. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  29908. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  29909. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  29910. /**
  29911. * @author mrdoob / http://mrdoob.com/
  29912. * @author WestLangley / http://github.com/WestLangley
  29913. */
  29914. function VertexNormalsHelper( object, size, hex, linewidth ) {
  29915. this.object = object;
  29916. this.size = ( size !== undefined ) ? size : 1;
  29917. var color = ( hex !== undefined ) ? hex : 0xff0000;
  29918. var width = ( linewidth !== undefined ) ? linewidth : 1;
  29919. //
  29920. var nNormals = 0;
  29921. var objGeometry = this.object.geometry;
  29922. if ( objGeometry && objGeometry.isGeometry ) {
  29923. nNormals = objGeometry.faces.length * 3;
  29924. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  29925. nNormals = objGeometry.attributes.normal.count;
  29926. }
  29927. //
  29928. var geometry = new BufferGeometry();
  29929. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  29930. geometry.addAttribute( 'position', positions );
  29931. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  29932. //
  29933. this.matrixAutoUpdate = false;
  29934. this.update();
  29935. }
  29936. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  29937. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  29938. VertexNormalsHelper.prototype.update = ( function () {
  29939. var v1 = new Vector3();
  29940. var v2 = new Vector3();
  29941. var normalMatrix = new Matrix3();
  29942. return function update() {
  29943. var keys = [ 'a', 'b', 'c' ];
  29944. this.object.updateMatrixWorld( true );
  29945. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  29946. var matrixWorld = this.object.matrixWorld;
  29947. var position = this.geometry.attributes.position;
  29948. //
  29949. var objGeometry = this.object.geometry;
  29950. if ( objGeometry && objGeometry.isGeometry ) {
  29951. var vertices = objGeometry.vertices;
  29952. var faces = objGeometry.faces;
  29953. var idx = 0;
  29954. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  29955. var face = faces[ i ];
  29956. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  29957. var vertex = vertices[ face[ keys[ j ] ] ];
  29958. var normal = face.vertexNormals[ j ];
  29959. v1.copy( vertex ).applyMatrix4( matrixWorld );
  29960. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  29961. position.setXYZ( idx, v1.x, v1.y, v1.z );
  29962. idx = idx + 1;
  29963. position.setXYZ( idx, v2.x, v2.y, v2.z );
  29964. idx = idx + 1;
  29965. }
  29966. }
  29967. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  29968. var objPos = objGeometry.attributes.position;
  29969. var objNorm = objGeometry.attributes.normal;
  29970. var idx = 0;
  29971. // for simplicity, ignore index and drawcalls, and render every normal
  29972. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  29973. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  29974. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  29975. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  29976. position.setXYZ( idx, v1.x, v1.y, v1.z );
  29977. idx = idx + 1;
  29978. position.setXYZ( idx, v2.x, v2.y, v2.z );
  29979. idx = idx + 1;
  29980. }
  29981. }
  29982. position.needsUpdate = true;
  29983. };
  29984. }() );
  29985. /**
  29986. * @author alteredq / http://alteredqualia.com/
  29987. * @author mrdoob / http://mrdoob.com/
  29988. * @author WestLangley / http://github.com/WestLangley
  29989. */
  29990. function SpotLightHelper( light, color ) {
  29991. Object3D.call( this );
  29992. this.light = light;
  29993. this.light.updateMatrixWorld();
  29994. this.matrix = light.matrixWorld;
  29995. this.matrixAutoUpdate = false;
  29996. this.color = color;
  29997. var geometry = new BufferGeometry();
  29998. var positions = [
  29999. 0, 0, 0, 0, 0, 1,
  30000. 0, 0, 0, 1, 0, 1,
  30001. 0, 0, 0, - 1, 0, 1,
  30002. 0, 0, 0, 0, 1, 1,
  30003. 0, 0, 0, 0, - 1, 1
  30004. ];
  30005. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  30006. var p1 = ( i / l ) * Math.PI * 2;
  30007. var p2 = ( j / l ) * Math.PI * 2;
  30008. positions.push(
  30009. Math.cos( p1 ), Math.sin( p1 ), 1,
  30010. Math.cos( p2 ), Math.sin( p2 ), 1
  30011. );
  30012. }
  30013. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30014. var material = new LineBasicMaterial( { fog: false } );
  30015. this.cone = new LineSegments( geometry, material );
  30016. this.add( this.cone );
  30017. this.update();
  30018. }
  30019. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  30020. SpotLightHelper.prototype.constructor = SpotLightHelper;
  30021. SpotLightHelper.prototype.dispose = function () {
  30022. this.cone.geometry.dispose();
  30023. this.cone.material.dispose();
  30024. };
  30025. SpotLightHelper.prototype.update = function () {
  30026. var vector = new Vector3();
  30027. var vector2 = new Vector3();
  30028. return function update() {
  30029. this.light.updateMatrixWorld();
  30030. var coneLength = this.light.distance ? this.light.distance : 1000;
  30031. var coneWidth = coneLength * Math.tan( this.light.angle );
  30032. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  30033. vector.setFromMatrixPosition( this.light.matrixWorld );
  30034. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  30035. this.cone.lookAt( vector2.sub( vector ) );
  30036. if ( this.color !== undefined ) {
  30037. this.cone.material.color.set( this.color );
  30038. } else {
  30039. this.cone.material.color.copy( this.light.color );
  30040. }
  30041. };
  30042. }();
  30043. /**
  30044. * @author Sean Griffin / http://twitter.com/sgrif
  30045. * @author Michael Guerrero / http://realitymeltdown.com
  30046. * @author mrdoob / http://mrdoob.com/
  30047. * @author ikerr / http://verold.com
  30048. * @author Mugen87 / https://github.com/Mugen87
  30049. */
  30050. function getBoneList( object ) {
  30051. var boneList = [];
  30052. if ( object && object.isBone ) {
  30053. boneList.push( object );
  30054. }
  30055. for ( var i = 0; i < object.children.length; i ++ ) {
  30056. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  30057. }
  30058. return boneList;
  30059. }
  30060. function SkeletonHelper( object ) {
  30061. var bones = getBoneList( object );
  30062. var geometry = new BufferGeometry();
  30063. var vertices = [];
  30064. var colors = [];
  30065. var color1 = new Color( 0, 0, 1 );
  30066. var color2 = new Color( 0, 1, 0 );
  30067. for ( var i = 0; i < bones.length; i ++ ) {
  30068. var bone = bones[ i ];
  30069. if ( bone.parent && bone.parent.isBone ) {
  30070. vertices.push( 0, 0, 0 );
  30071. vertices.push( 0, 0, 0 );
  30072. colors.push( color1.r, color1.g, color1.b );
  30073. colors.push( color2.r, color2.g, color2.b );
  30074. }
  30075. }
  30076. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30077. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30078. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  30079. LineSegments.call( this, geometry, material );
  30080. this.root = object;
  30081. this.bones = bones;
  30082. this.matrix = object.matrixWorld;
  30083. this.matrixAutoUpdate = false;
  30084. }
  30085. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  30086. SkeletonHelper.prototype.constructor = SkeletonHelper;
  30087. SkeletonHelper.prototype.updateMatrixWorld = function () {
  30088. var vector = new Vector3();
  30089. var boneMatrix = new Matrix4();
  30090. var matrixWorldInv = new Matrix4();
  30091. return function updateMatrixWorld( force ) {
  30092. var bones = this.bones;
  30093. var geometry = this.geometry;
  30094. var position = geometry.getAttribute( 'position' );
  30095. matrixWorldInv.getInverse( this.root.matrixWorld );
  30096. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  30097. var bone = bones[ i ];
  30098. if ( bone.parent && bone.parent.isBone ) {
  30099. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  30100. vector.setFromMatrixPosition( boneMatrix );
  30101. position.setXYZ( j, vector.x, vector.y, vector.z );
  30102. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  30103. vector.setFromMatrixPosition( boneMatrix );
  30104. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  30105. j += 2;
  30106. }
  30107. }
  30108. geometry.getAttribute( 'position' ).needsUpdate = true;
  30109. Object3D.prototype.updateMatrixWorld.call( this, force );
  30110. };
  30111. }();
  30112. /**
  30113. * @author alteredq / http://alteredqualia.com/
  30114. * @author mrdoob / http://mrdoob.com/
  30115. */
  30116. function PointLightHelper( light, sphereSize, color ) {
  30117. this.light = light;
  30118. this.light.updateMatrixWorld();
  30119. this.color = color;
  30120. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  30121. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  30122. Mesh.call( this, geometry, material );
  30123. this.matrix = this.light.matrixWorld;
  30124. this.matrixAutoUpdate = false;
  30125. this.update();
  30126. /*
  30127. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  30128. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  30129. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  30130. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  30131. var d = light.distance;
  30132. if ( d === 0.0 ) {
  30133. this.lightDistance.visible = false;
  30134. } else {
  30135. this.lightDistance.scale.set( d, d, d );
  30136. }
  30137. this.add( this.lightDistance );
  30138. */
  30139. }
  30140. PointLightHelper.prototype = Object.create( Mesh.prototype );
  30141. PointLightHelper.prototype.constructor = PointLightHelper;
  30142. PointLightHelper.prototype.dispose = function () {
  30143. this.geometry.dispose();
  30144. this.material.dispose();
  30145. };
  30146. PointLightHelper.prototype.update = function () {
  30147. if ( this.color !== undefined ) {
  30148. this.material.color.set( this.color );
  30149. } else {
  30150. this.material.color.copy( this.light.color );
  30151. }
  30152. /*
  30153. var d = this.light.distance;
  30154. if ( d === 0.0 ) {
  30155. this.lightDistance.visible = false;
  30156. } else {
  30157. this.lightDistance.visible = true;
  30158. this.lightDistance.scale.set( d, d, d );
  30159. }
  30160. */
  30161. };
  30162. /**
  30163. * @author abelnation / http://github.com/abelnation
  30164. * @author Mugen87 / http://github.com/Mugen87
  30165. * @author WestLangley / http://github.com/WestLangley
  30166. */
  30167. function RectAreaLightHelper( light, color ) {
  30168. Object3D.call( this );
  30169. this.light = light;
  30170. this.light.updateMatrixWorld();
  30171. this.matrix = light.matrixWorld;
  30172. this.matrixAutoUpdate = false;
  30173. this.color = color;
  30174. var material = new LineBasicMaterial( { fog: false } );
  30175. var geometry = new BufferGeometry();
  30176. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  30177. this.line = new Line( geometry, material );
  30178. this.add( this.line );
  30179. this.update();
  30180. }
  30181. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  30182. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  30183. RectAreaLightHelper.prototype.dispose = function () {
  30184. this.children[ 0 ].geometry.dispose();
  30185. this.children[ 0 ].material.dispose();
  30186. };
  30187. RectAreaLightHelper.prototype.update = function () {
  30188. // calculate new dimensions of the helper
  30189. var hx = this.light.width * 0.5;
  30190. var hy = this.light.height * 0.5;
  30191. var position = this.line.geometry.attributes.position;
  30192. var array = position.array;
  30193. // update vertices
  30194. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  30195. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  30196. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  30197. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  30198. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  30199. position.needsUpdate = true;
  30200. if ( this.color !== undefined ) {
  30201. this.line.material.color.set( this.color );
  30202. } else {
  30203. this.line.material.color.copy( this.light.color );
  30204. }
  30205. };
  30206. /**
  30207. * @author alteredq / http://alteredqualia.com/
  30208. * @author mrdoob / http://mrdoob.com/
  30209. * @author Mugen87 / https://github.com/Mugen87
  30210. */
  30211. function HemisphereLightHelper( light, size, color ) {
  30212. Object3D.call( this );
  30213. this.light = light;
  30214. this.light.updateMatrixWorld();
  30215. this.matrix = light.matrixWorld;
  30216. this.matrixAutoUpdate = false;
  30217. this.color = color;
  30218. var geometry = new OctahedronBufferGeometry( size );
  30219. geometry.rotateY( Math.PI * 0.5 );
  30220. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  30221. if ( this.color === undefined ) this.material.vertexColors = VertexColors;
  30222. var position = geometry.getAttribute( 'position' );
  30223. var colors = new Float32Array( position.count * 3 );
  30224. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  30225. this.add( new Mesh( geometry, this.material ) );
  30226. this.update();
  30227. }
  30228. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  30229. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  30230. HemisphereLightHelper.prototype.dispose = function () {
  30231. this.children[ 0 ].geometry.dispose();
  30232. this.children[ 0 ].material.dispose();
  30233. };
  30234. HemisphereLightHelper.prototype.update = function () {
  30235. var vector = new Vector3();
  30236. var color1 = new Color();
  30237. var color2 = new Color();
  30238. return function update() {
  30239. var mesh = this.children[ 0 ];
  30240. if ( this.color !== undefined ) {
  30241. this.material.color.set( this.color );
  30242. } else {
  30243. var colors = mesh.geometry.getAttribute( 'color' );
  30244. color1.copy( this.light.color );
  30245. color2.copy( this.light.groundColor );
  30246. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  30247. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  30248. colors.setXYZ( i, color.r, color.g, color.b );
  30249. }
  30250. colors.needsUpdate = true;
  30251. }
  30252. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  30253. };
  30254. }();
  30255. /**
  30256. * @author mrdoob / http://mrdoob.com/
  30257. */
  30258. function GridHelper( size, divisions, color1, color2 ) {
  30259. size = size || 10;
  30260. divisions = divisions || 10;
  30261. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  30262. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  30263. var center = divisions / 2;
  30264. var step = size / divisions;
  30265. var halfSize = size / 2;
  30266. var vertices = [], colors = [];
  30267. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  30268. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  30269. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  30270. var color = i === center ? color1 : color2;
  30271. color.toArray( colors, j ); j += 3;
  30272. color.toArray( colors, j ); j += 3;
  30273. color.toArray( colors, j ); j += 3;
  30274. color.toArray( colors, j ); j += 3;
  30275. }
  30276. var geometry = new BufferGeometry();
  30277. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30278. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30279. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  30280. LineSegments.call( this, geometry, material );
  30281. }
  30282. GridHelper.prototype = Object.create( LineSegments.prototype );
  30283. GridHelper.prototype.constructor = GridHelper;
  30284. /**
  30285. * @author mrdoob / http://mrdoob.com/
  30286. * @author Mugen87 / http://github.com/Mugen87
  30287. * @author Hectate / http://www.github.com/Hectate
  30288. */
  30289. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  30290. radius = radius || 10;
  30291. radials = radials || 16;
  30292. circles = circles || 8;
  30293. divisions = divisions || 64;
  30294. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  30295. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  30296. var vertices = [];
  30297. var colors = [];
  30298. var x, z;
  30299. var v, i, j, r, color;
  30300. // create the radials
  30301. for ( i = 0; i <= radials; i ++ ) {
  30302. v = ( i / radials ) * ( Math.PI * 2 );
  30303. x = Math.sin( v ) * radius;
  30304. z = Math.cos( v ) * radius;
  30305. vertices.push( 0, 0, 0 );
  30306. vertices.push( x, 0, z );
  30307. color = ( i & 1 ) ? color1 : color2;
  30308. colors.push( color.r, color.g, color.b );
  30309. colors.push( color.r, color.g, color.b );
  30310. }
  30311. // create the circles
  30312. for ( i = 0; i <= circles; i ++ ) {
  30313. color = ( i & 1 ) ? color1 : color2;
  30314. r = radius - ( radius / circles * i );
  30315. for ( j = 0; j < divisions; j ++ ) {
  30316. // first vertex
  30317. v = ( j / divisions ) * ( Math.PI * 2 );
  30318. x = Math.sin( v ) * r;
  30319. z = Math.cos( v ) * r;
  30320. vertices.push( x, 0, z );
  30321. colors.push( color.r, color.g, color.b );
  30322. // second vertex
  30323. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  30324. x = Math.sin( v ) * r;
  30325. z = Math.cos( v ) * r;
  30326. vertices.push( x, 0, z );
  30327. colors.push( color.r, color.g, color.b );
  30328. }
  30329. }
  30330. var geometry = new BufferGeometry();
  30331. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30332. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30333. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  30334. LineSegments.call( this, geometry, material );
  30335. }
  30336. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  30337. PolarGridHelper.prototype.constructor = PolarGridHelper;
  30338. /**
  30339. * @author mrdoob / http://mrdoob.com/
  30340. * @author WestLangley / http://github.com/WestLangley
  30341. */
  30342. function FaceNormalsHelper( object, size, hex, linewidth ) {
  30343. // FaceNormalsHelper only supports THREE.Geometry
  30344. this.object = object;
  30345. this.size = ( size !== undefined ) ? size : 1;
  30346. var color = ( hex !== undefined ) ? hex : 0xffff00;
  30347. var width = ( linewidth !== undefined ) ? linewidth : 1;
  30348. //
  30349. var nNormals = 0;
  30350. var objGeometry = this.object.geometry;
  30351. if ( objGeometry && objGeometry.isGeometry ) {
  30352. nNormals = objGeometry.faces.length;
  30353. } else {
  30354. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  30355. }
  30356. //
  30357. var geometry = new BufferGeometry();
  30358. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  30359. geometry.addAttribute( 'position', positions );
  30360. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  30361. //
  30362. this.matrixAutoUpdate = false;
  30363. this.update();
  30364. }
  30365. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  30366. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  30367. FaceNormalsHelper.prototype.update = ( function () {
  30368. var v1 = new Vector3();
  30369. var v2 = new Vector3();
  30370. var normalMatrix = new Matrix3();
  30371. return function update() {
  30372. this.object.updateMatrixWorld( true );
  30373. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  30374. var matrixWorld = this.object.matrixWorld;
  30375. var position = this.geometry.attributes.position;
  30376. //
  30377. var objGeometry = this.object.geometry;
  30378. var vertices = objGeometry.vertices;
  30379. var faces = objGeometry.faces;
  30380. var idx = 0;
  30381. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  30382. var face = faces[ i ];
  30383. var normal = face.normal;
  30384. v1.copy( vertices[ face.a ] )
  30385. .add( vertices[ face.b ] )
  30386. .add( vertices[ face.c ] )
  30387. .divideScalar( 3 )
  30388. .applyMatrix4( matrixWorld );
  30389. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  30390. position.setXYZ( idx, v1.x, v1.y, v1.z );
  30391. idx = idx + 1;
  30392. position.setXYZ( idx, v2.x, v2.y, v2.z );
  30393. idx = idx + 1;
  30394. }
  30395. position.needsUpdate = true;
  30396. };
  30397. }() );
  30398. /**
  30399. * @author alteredq / http://alteredqualia.com/
  30400. * @author mrdoob / http://mrdoob.com/
  30401. * @author WestLangley / http://github.com/WestLangley
  30402. */
  30403. function DirectionalLightHelper( light, size, color ) {
  30404. Object3D.call( this );
  30405. this.light = light;
  30406. this.light.updateMatrixWorld();
  30407. this.matrix = light.matrixWorld;
  30408. this.matrixAutoUpdate = false;
  30409. this.color = color;
  30410. if ( size === undefined ) size = 1;
  30411. var geometry = new BufferGeometry();
  30412. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  30413. - size, size, 0,
  30414. size, size, 0,
  30415. size, - size, 0,
  30416. - size, - size, 0,
  30417. - size, size, 0
  30418. ], 3 ) );
  30419. var material = new LineBasicMaterial( { fog: false } );
  30420. this.lightPlane = new Line( geometry, material );
  30421. this.add( this.lightPlane );
  30422. geometry = new BufferGeometry();
  30423. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  30424. this.targetLine = new Line( geometry, material );
  30425. this.add( this.targetLine );
  30426. this.update();
  30427. }
  30428. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  30429. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  30430. DirectionalLightHelper.prototype.dispose = function () {
  30431. this.lightPlane.geometry.dispose();
  30432. this.lightPlane.material.dispose();
  30433. this.targetLine.geometry.dispose();
  30434. this.targetLine.material.dispose();
  30435. };
  30436. DirectionalLightHelper.prototype.update = function () {
  30437. var v1 = new Vector3();
  30438. var v2 = new Vector3();
  30439. var v3 = new Vector3();
  30440. return function update() {
  30441. v1.setFromMatrixPosition( this.light.matrixWorld );
  30442. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  30443. v3.subVectors( v2, v1 );
  30444. this.lightPlane.lookAt( v3 );
  30445. if ( this.color !== undefined ) {
  30446. this.lightPlane.material.color.set( this.color );
  30447. this.targetLine.material.color.set( this.color );
  30448. } else {
  30449. this.lightPlane.material.color.copy( this.light.color );
  30450. this.targetLine.material.color.copy( this.light.color );
  30451. }
  30452. this.targetLine.lookAt( v3 );
  30453. this.targetLine.scale.z = v3.length();
  30454. };
  30455. }();
  30456. /**
  30457. * @author alteredq / http://alteredqualia.com/
  30458. * @author Mugen87 / https://github.com/Mugen87
  30459. *
  30460. * - shows frustum, line of sight and up of the camera
  30461. * - suitable for fast updates
  30462. * - based on frustum visualization in lightgl.js shadowmap example
  30463. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  30464. */
  30465. function CameraHelper( camera ) {
  30466. var geometry = new BufferGeometry();
  30467. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  30468. var vertices = [];
  30469. var colors = [];
  30470. var pointMap = {};
  30471. // colors
  30472. var colorFrustum = new Color( 0xffaa00 );
  30473. var colorCone = new Color( 0xff0000 );
  30474. var colorUp = new Color( 0x00aaff );
  30475. var colorTarget = new Color( 0xffffff );
  30476. var colorCross = new Color( 0x333333 );
  30477. // near
  30478. addLine( 'n1', 'n2', colorFrustum );
  30479. addLine( 'n2', 'n4', colorFrustum );
  30480. addLine( 'n4', 'n3', colorFrustum );
  30481. addLine( 'n3', 'n1', colorFrustum );
  30482. // far
  30483. addLine( 'f1', 'f2', colorFrustum );
  30484. addLine( 'f2', 'f4', colorFrustum );
  30485. addLine( 'f4', 'f3', colorFrustum );
  30486. addLine( 'f3', 'f1', colorFrustum );
  30487. // sides
  30488. addLine( 'n1', 'f1', colorFrustum );
  30489. addLine( 'n2', 'f2', colorFrustum );
  30490. addLine( 'n3', 'f3', colorFrustum );
  30491. addLine( 'n4', 'f4', colorFrustum );
  30492. // cone
  30493. addLine( 'p', 'n1', colorCone );
  30494. addLine( 'p', 'n2', colorCone );
  30495. addLine( 'p', 'n3', colorCone );
  30496. addLine( 'p', 'n4', colorCone );
  30497. // up
  30498. addLine( 'u1', 'u2', colorUp );
  30499. addLine( 'u2', 'u3', colorUp );
  30500. addLine( 'u3', 'u1', colorUp );
  30501. // target
  30502. addLine( 'c', 't', colorTarget );
  30503. addLine( 'p', 'c', colorCross );
  30504. // cross
  30505. addLine( 'cn1', 'cn2', colorCross );
  30506. addLine( 'cn3', 'cn4', colorCross );
  30507. addLine( 'cf1', 'cf2', colorCross );
  30508. addLine( 'cf3', 'cf4', colorCross );
  30509. function addLine( a, b, color ) {
  30510. addPoint( a, color );
  30511. addPoint( b, color );
  30512. }
  30513. function addPoint( id, color ) {
  30514. vertices.push( 0, 0, 0 );
  30515. colors.push( color.r, color.g, color.b );
  30516. if ( pointMap[ id ] === undefined ) {
  30517. pointMap[ id ] = [];
  30518. }
  30519. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  30520. }
  30521. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30522. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30523. LineSegments.call( this, geometry, material );
  30524. this.camera = camera;
  30525. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  30526. this.matrix = camera.matrixWorld;
  30527. this.matrixAutoUpdate = false;
  30528. this.pointMap = pointMap;
  30529. this.update();
  30530. }
  30531. CameraHelper.prototype = Object.create( LineSegments.prototype );
  30532. CameraHelper.prototype.constructor = CameraHelper;
  30533. CameraHelper.prototype.update = function () {
  30534. var geometry, pointMap;
  30535. var vector = new Vector3();
  30536. var camera = new Camera();
  30537. function setPoint( point, x, y, z ) {
  30538. vector.set( x, y, z ).unproject( camera );
  30539. var points = pointMap[ point ];
  30540. if ( points !== undefined ) {
  30541. var position = geometry.getAttribute( 'position' );
  30542. for ( var i = 0, l = points.length; i < l; i ++ ) {
  30543. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  30544. }
  30545. }
  30546. }
  30547. return function update() {
  30548. geometry = this.geometry;
  30549. pointMap = this.pointMap;
  30550. var w = 1, h = 1;
  30551. // we need just camera projection matrix
  30552. // world matrix must be identity
  30553. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  30554. // center / target
  30555. setPoint( 'c', 0, 0, - 1 );
  30556. setPoint( 't', 0, 0, 1 );
  30557. // near
  30558. setPoint( 'n1', - w, - h, - 1 );
  30559. setPoint( 'n2', w, - h, - 1 );
  30560. setPoint( 'n3', - w, h, - 1 );
  30561. setPoint( 'n4', w, h, - 1 );
  30562. // far
  30563. setPoint( 'f1', - w, - h, 1 );
  30564. setPoint( 'f2', w, - h, 1 );
  30565. setPoint( 'f3', - w, h, 1 );
  30566. setPoint( 'f4', w, h, 1 );
  30567. // up
  30568. setPoint( 'u1', w * 0.7, h * 1.1, - 1 );
  30569. setPoint( 'u2', - w * 0.7, h * 1.1, - 1 );
  30570. setPoint( 'u3', 0, h * 2, - 1 );
  30571. // cross
  30572. setPoint( 'cf1', - w, 0, 1 );
  30573. setPoint( 'cf2', w, 0, 1 );
  30574. setPoint( 'cf3', 0, - h, 1 );
  30575. setPoint( 'cf4', 0, h, 1 );
  30576. setPoint( 'cn1', - w, 0, - 1 );
  30577. setPoint( 'cn2', w, 0, - 1 );
  30578. setPoint( 'cn3', 0, - h, - 1 );
  30579. setPoint( 'cn4', 0, h, - 1 );
  30580. geometry.getAttribute( 'position' ).needsUpdate = true;
  30581. };
  30582. }();
  30583. /**
  30584. * @author mrdoob / http://mrdoob.com/
  30585. * @author Mugen87 / http://github.com/Mugen87
  30586. */
  30587. function BoxHelper( object, color ) {
  30588. this.object = object;
  30589. if ( color === undefined ) color = 0xffff00;
  30590. 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 ] );
  30591. var positions = new Float32Array( 8 * 3 );
  30592. var geometry = new BufferGeometry();
  30593. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30594. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  30595. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  30596. this.matrixAutoUpdate = false;
  30597. this.update();
  30598. }
  30599. BoxHelper.prototype = Object.create( LineSegments.prototype );
  30600. BoxHelper.prototype.constructor = BoxHelper;
  30601. BoxHelper.prototype.update = ( function () {
  30602. var box = new Box3();
  30603. return function update( object ) {
  30604. if ( object !== undefined ) {
  30605. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  30606. }
  30607. if ( this.object !== undefined ) {
  30608. box.setFromObject( this.object );
  30609. }
  30610. if ( box.isEmpty() ) return;
  30611. var min = box.min;
  30612. var max = box.max;
  30613. /*
  30614. 5____4
  30615. 1/___0/|
  30616. | 6__|_7
  30617. 2/___3/
  30618. 0: max.x, max.y, max.z
  30619. 1: min.x, max.y, max.z
  30620. 2: min.x, min.y, max.z
  30621. 3: max.x, min.y, max.z
  30622. 4: max.x, max.y, min.z
  30623. 5: min.x, max.y, min.z
  30624. 6: min.x, min.y, min.z
  30625. 7: max.x, min.y, min.z
  30626. */
  30627. var position = this.geometry.attributes.position;
  30628. var array = position.array;
  30629. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  30630. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  30631. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  30632. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  30633. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  30634. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  30635. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  30636. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  30637. position.needsUpdate = true;
  30638. this.geometry.computeBoundingSphere();
  30639. };
  30640. } )();
  30641. BoxHelper.prototype.setFromObject = function ( object ) {
  30642. this.object = object;
  30643. this.update();
  30644. return this;
  30645. };
  30646. /**
  30647. * @author WestLangley / http://github.com/WestLangley
  30648. */
  30649. function Box3Helper( box, hex ) {
  30650. this.type = 'Box3Helper';
  30651. this.box = box;
  30652. var color = ( hex !== undefined ) ? hex : 0xffff00;
  30653. 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 ] );
  30654. 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 ];
  30655. var geometry = new BufferGeometry();
  30656. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30657. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30658. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  30659. this.geometry.computeBoundingSphere();
  30660. }
  30661. Box3Helper.prototype = Object.create( LineSegments.prototype );
  30662. Box3Helper.prototype.constructor = Box3Helper;
  30663. Box3Helper.prototype.updateMatrixWorld = function ( force ) {
  30664. var box = this.box;
  30665. if ( box.isEmpty() ) return;
  30666. box.getCenter( this.position );
  30667. box.getSize( this.scale );
  30668. this.scale.multiplyScalar( 0.5 );
  30669. Object3D.prototype.updateMatrixWorld.call( this, force );
  30670. };
  30671. /**
  30672. * @author WestLangley / http://github.com/WestLangley
  30673. */
  30674. function PlaneHelper( plane, size, hex ) {
  30675. this.type = 'PlaneHelper';
  30676. this.plane = plane;
  30677. this.size = ( size === undefined ) ? 1 : size;
  30678. var color = ( hex !== undefined ) ? hex : 0xffff00;
  30679. 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 ];
  30680. var geometry = new BufferGeometry();
  30681. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30682. geometry.computeBoundingSphere();
  30683. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  30684. //
  30685. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  30686. var geometry2 = new BufferGeometry();
  30687. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  30688. geometry2.computeBoundingSphere();
  30689. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  30690. }
  30691. PlaneHelper.prototype = Object.create( Line.prototype );
  30692. PlaneHelper.prototype.constructor = PlaneHelper;
  30693. PlaneHelper.prototype.updateMatrixWorld = function ( force ) {
  30694. var scale = - this.plane.constant;
  30695. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  30696. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  30697. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  30698. this.lookAt( this.plane.normal );
  30699. Object3D.prototype.updateMatrixWorld.call( this, force );
  30700. };
  30701. /**
  30702. * @author WestLangley / http://github.com/WestLangley
  30703. * @author zz85 / http://github.com/zz85
  30704. * @author bhouston / http://clara.io
  30705. *
  30706. * Creates an arrow for visualizing directions
  30707. *
  30708. * Parameters:
  30709. * dir - Vector3
  30710. * origin - Vector3
  30711. * length - Number
  30712. * color - color in hex value
  30713. * headLength - Number
  30714. * headWidth - Number
  30715. */
  30716. var lineGeometry, coneGeometry;
  30717. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  30718. // dir is assumed to be normalized
  30719. Object3D.call( this );
  30720. if ( color === undefined ) color = 0xffff00;
  30721. if ( length === undefined ) length = 1;
  30722. if ( headLength === undefined ) headLength = 0.2 * length;
  30723. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  30724. if ( lineGeometry === undefined ) {
  30725. lineGeometry = new BufferGeometry();
  30726. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  30727. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  30728. coneGeometry.translate( 0, - 0.5, 0 );
  30729. }
  30730. this.position.copy( origin );
  30731. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  30732. this.line.matrixAutoUpdate = false;
  30733. this.add( this.line );
  30734. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  30735. this.cone.matrixAutoUpdate = false;
  30736. this.add( this.cone );
  30737. this.setDirection( dir );
  30738. this.setLength( length, headLength, headWidth );
  30739. }
  30740. ArrowHelper.prototype = Object.create( Object3D.prototype );
  30741. ArrowHelper.prototype.constructor = ArrowHelper;
  30742. ArrowHelper.prototype.setDirection = ( function () {
  30743. var axis = new Vector3();
  30744. var radians;
  30745. return function setDirection( dir ) {
  30746. // dir is assumed to be normalized
  30747. if ( dir.y > 0.99999 ) {
  30748. this.quaternion.set( 0, 0, 0, 1 );
  30749. } else if ( dir.y < - 0.99999 ) {
  30750. this.quaternion.set( 1, 0, 0, 0 );
  30751. } else {
  30752. axis.set( dir.z, 0, - dir.x ).normalize();
  30753. radians = Math.acos( dir.y );
  30754. this.quaternion.setFromAxisAngle( axis, radians );
  30755. }
  30756. };
  30757. }() );
  30758. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  30759. if ( headLength === undefined ) headLength = 0.2 * length;
  30760. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  30761. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  30762. this.line.updateMatrix();
  30763. this.cone.scale.set( headWidth, headLength, headWidth );
  30764. this.cone.position.y = length;
  30765. this.cone.updateMatrix();
  30766. };
  30767. ArrowHelper.prototype.setColor = function ( color ) {
  30768. this.line.material.color.copy( color );
  30769. this.cone.material.color.copy( color );
  30770. };
  30771. /**
  30772. * @author sroucheray / http://sroucheray.org/
  30773. * @author mrdoob / http://mrdoob.com/
  30774. */
  30775. function AxesHelper( size ) {
  30776. size = size || 1;
  30777. var vertices = [
  30778. 0, 0, 0, size, 0, 0,
  30779. 0, 0, 0, 0, size, 0,
  30780. 0, 0, 0, 0, 0, size
  30781. ];
  30782. var colors = [
  30783. 1, 0, 0, 1, 0.6, 0,
  30784. 0, 1, 0, 0.6, 1, 0,
  30785. 0, 0, 1, 0, 0.6, 1
  30786. ];
  30787. var geometry = new BufferGeometry();
  30788. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30789. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30790. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  30791. LineSegments.call( this, geometry, material );
  30792. }
  30793. AxesHelper.prototype = Object.create( LineSegments.prototype );
  30794. AxesHelper.prototype.constructor = AxesHelper;
  30795. /**
  30796. * @author mrdoob / http://mrdoob.com/
  30797. */
  30798. function Face4( a, b, c, d, normal, color, materialIndex ) {
  30799. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  30800. return new Face3( a, b, c, normal, color, materialIndex );
  30801. }
  30802. var LineStrip = 0;
  30803. var LinePieces = 1;
  30804. function MeshFaceMaterial( materials ) {
  30805. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  30806. return materials;
  30807. }
  30808. function MultiMaterial( materials ) {
  30809. if ( materials === undefined ) materials = [];
  30810. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  30811. materials.isMultiMaterial = true;
  30812. materials.materials = materials;
  30813. materials.clone = function () {
  30814. return materials.slice();
  30815. };
  30816. return materials;
  30817. }
  30818. function PointCloud( geometry, material ) {
  30819. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  30820. return new Points( geometry, material );
  30821. }
  30822. function Particle( material ) {
  30823. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  30824. return new Sprite( material );
  30825. }
  30826. function ParticleSystem( geometry, material ) {
  30827. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  30828. return new Points( geometry, material );
  30829. }
  30830. function PointCloudMaterial( parameters ) {
  30831. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  30832. return new PointsMaterial( parameters );
  30833. }
  30834. function ParticleBasicMaterial( parameters ) {
  30835. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  30836. return new PointsMaterial( parameters );
  30837. }
  30838. function ParticleSystemMaterial( parameters ) {
  30839. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  30840. return new PointsMaterial( parameters );
  30841. }
  30842. function Vertex( x, y, z ) {
  30843. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  30844. return new Vector3( x, y, z );
  30845. }
  30846. //
  30847. function DynamicBufferAttribute( array, itemSize ) {
  30848. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  30849. return new BufferAttribute( array, itemSize ).setDynamic( true );
  30850. }
  30851. function Int8Attribute( array, itemSize ) {
  30852. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  30853. return new Int8BufferAttribute( array, itemSize );
  30854. }
  30855. function Uint8Attribute( array, itemSize ) {
  30856. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  30857. return new Uint8BufferAttribute( array, itemSize );
  30858. }
  30859. function Uint8ClampedAttribute( array, itemSize ) {
  30860. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  30861. return new Uint8ClampedBufferAttribute( array, itemSize );
  30862. }
  30863. function Int16Attribute( array, itemSize ) {
  30864. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  30865. return new Int16BufferAttribute( array, itemSize );
  30866. }
  30867. function Uint16Attribute( array, itemSize ) {
  30868. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  30869. return new Uint16BufferAttribute( array, itemSize );
  30870. }
  30871. function Int32Attribute( array, itemSize ) {
  30872. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  30873. return new Int32BufferAttribute( array, itemSize );
  30874. }
  30875. function Uint32Attribute( array, itemSize ) {
  30876. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  30877. return new Uint32BufferAttribute( array, itemSize );
  30878. }
  30879. function Float32Attribute( array, itemSize ) {
  30880. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  30881. return new Float32BufferAttribute( array, itemSize );
  30882. }
  30883. function Float64Attribute( array, itemSize ) {
  30884. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  30885. return new Float64BufferAttribute( array, itemSize );
  30886. }
  30887. //
  30888. Curve.create = function ( construct, getPoint ) {
  30889. console.log( 'THREE.Curve.create() has been deprecated' );
  30890. construct.prototype = Object.create( Curve.prototype );
  30891. construct.prototype.constructor = construct;
  30892. construct.prototype.getPoint = getPoint;
  30893. return construct;
  30894. };
  30895. //
  30896. Object.assign( CurvePath.prototype, {
  30897. createPointsGeometry: function ( divisions ) {
  30898. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30899. // generate geometry from path points (for Line or Points objects)
  30900. var pts = this.getPoints( divisions );
  30901. return this.createGeometry( pts );
  30902. },
  30903. createSpacedPointsGeometry: function ( divisions ) {
  30904. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30905. // generate geometry from equidistant sampling along the path
  30906. var pts = this.getSpacedPoints( divisions );
  30907. return this.createGeometry( pts );
  30908. },
  30909. createGeometry: function ( points ) {
  30910. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30911. var geometry = new Geometry();
  30912. for ( var i = 0, l = points.length; i < l; i ++ ) {
  30913. var point = points[ i ];
  30914. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  30915. }
  30916. return geometry;
  30917. }
  30918. } );
  30919. //
  30920. Object.assign( Path.prototype, {
  30921. fromPoints: function ( points ) {
  30922. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  30923. this.setFromPoints( points );
  30924. }
  30925. } );
  30926. //
  30927. function ClosedSplineCurve3( points ) {
  30928. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30929. CatmullRomCurve3.call( this, points );
  30930. this.type = 'catmullrom';
  30931. this.closed = true;
  30932. }
  30933. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30934. //
  30935. function SplineCurve3( points ) {
  30936. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30937. CatmullRomCurve3.call( this, points );
  30938. this.type = 'catmullrom';
  30939. }
  30940. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30941. //
  30942. function Spline( points ) {
  30943. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  30944. CatmullRomCurve3.call( this, points );
  30945. this.type = 'catmullrom';
  30946. }
  30947. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  30948. Object.assign( Spline.prototype, {
  30949. initFromArray: function ( /* a */ ) {
  30950. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  30951. },
  30952. getControlPointsArray: function ( /* optionalTarget */ ) {
  30953. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  30954. },
  30955. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  30956. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  30957. }
  30958. } );
  30959. //
  30960. function AxisHelper( size ) {
  30961. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  30962. return new AxesHelper( size );
  30963. }
  30964. function BoundingBoxHelper( object, color ) {
  30965. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  30966. return new BoxHelper( object, color );
  30967. }
  30968. function EdgesHelper( object, hex ) {
  30969. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  30970. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30971. }
  30972. GridHelper.prototype.setColors = function () {
  30973. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  30974. };
  30975. SkeletonHelper.prototype.update = function () {
  30976. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  30977. };
  30978. function WireframeHelper( object, hex ) {
  30979. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  30980. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30981. }
  30982. //
  30983. Object.assign( Loader.prototype, {
  30984. extractUrlBase: function ( url ) {
  30985. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  30986. return LoaderUtils.extractUrlBase( url );
  30987. }
  30988. } );
  30989. function XHRLoader( manager ) {
  30990. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  30991. return new FileLoader( manager );
  30992. }
  30993. function BinaryTextureLoader( manager ) {
  30994. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  30995. return new DataTextureLoader( manager );
  30996. }
  30997. //
  30998. Object.assign( Box2.prototype, {
  30999. center: function ( optionalTarget ) {
  31000. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  31001. return this.getCenter( optionalTarget );
  31002. },
  31003. empty: function () {
  31004. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  31005. return this.isEmpty();
  31006. },
  31007. isIntersectionBox: function ( box ) {
  31008. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  31009. return this.intersectsBox( box );
  31010. },
  31011. size: function ( optionalTarget ) {
  31012. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  31013. return this.getSize( optionalTarget );
  31014. }
  31015. } );
  31016. Object.assign( Box3.prototype, {
  31017. center: function ( optionalTarget ) {
  31018. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  31019. return this.getCenter( optionalTarget );
  31020. },
  31021. empty: function () {
  31022. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  31023. return this.isEmpty();
  31024. },
  31025. isIntersectionBox: function ( box ) {
  31026. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  31027. return this.intersectsBox( box );
  31028. },
  31029. isIntersectionSphere: function ( sphere ) {
  31030. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  31031. return this.intersectsSphere( sphere );
  31032. },
  31033. size: function ( optionalTarget ) {
  31034. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  31035. return this.getSize( optionalTarget );
  31036. }
  31037. } );
  31038. Line3.prototype.center = function ( optionalTarget ) {
  31039. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  31040. return this.getCenter( optionalTarget );
  31041. };
  31042. Object.assign( _Math, {
  31043. random16: function () {
  31044. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  31045. return Math.random();
  31046. },
  31047. nearestPowerOfTwo: function ( value ) {
  31048. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  31049. return _Math.floorPowerOfTwo( value );
  31050. },
  31051. nextPowerOfTwo: function ( value ) {
  31052. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  31053. return _Math.ceilPowerOfTwo( value );
  31054. }
  31055. } );
  31056. Object.assign( Matrix3.prototype, {
  31057. flattenToArrayOffset: function ( array, offset ) {
  31058. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  31059. return this.toArray( array, offset );
  31060. },
  31061. multiplyVector3: function ( vector ) {
  31062. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  31063. return vector.applyMatrix3( this );
  31064. },
  31065. multiplyVector3Array: function ( /* a */ ) {
  31066. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  31067. },
  31068. applyToBuffer: function ( buffer /*, offset, length */ ) {
  31069. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  31070. return this.applyToBufferAttribute( buffer );
  31071. },
  31072. applyToVector3Array: function ( /* array, offset, length */ ) {
  31073. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  31074. }
  31075. } );
  31076. Object.assign( Matrix4.prototype, {
  31077. extractPosition: function ( m ) {
  31078. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  31079. return this.copyPosition( m );
  31080. },
  31081. flattenToArrayOffset: function ( array, offset ) {
  31082. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  31083. return this.toArray( array, offset );
  31084. },
  31085. getPosition: function () {
  31086. var v1;
  31087. return function getPosition() {
  31088. if ( v1 === undefined ) v1 = new Vector3();
  31089. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  31090. return v1.setFromMatrixColumn( this, 3 );
  31091. };
  31092. }(),
  31093. setRotationFromQuaternion: function ( q ) {
  31094. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  31095. return this.makeRotationFromQuaternion( q );
  31096. },
  31097. multiplyToArray: function () {
  31098. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  31099. },
  31100. multiplyVector3: function ( vector ) {
  31101. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  31102. return vector.applyMatrix4( this );
  31103. },
  31104. multiplyVector4: function ( vector ) {
  31105. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  31106. return vector.applyMatrix4( this );
  31107. },
  31108. multiplyVector3Array: function ( /* a */ ) {
  31109. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  31110. },
  31111. rotateAxis: function ( v ) {
  31112. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  31113. v.transformDirection( this );
  31114. },
  31115. crossVector: function ( vector ) {
  31116. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  31117. return vector.applyMatrix4( this );
  31118. },
  31119. translate: function () {
  31120. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  31121. },
  31122. rotateX: function () {
  31123. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  31124. },
  31125. rotateY: function () {
  31126. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  31127. },
  31128. rotateZ: function () {
  31129. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  31130. },
  31131. rotateByAxis: function () {
  31132. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  31133. },
  31134. applyToBuffer: function ( buffer /*, offset, length */ ) {
  31135. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  31136. return this.applyToBufferAttribute( buffer );
  31137. },
  31138. applyToVector3Array: function ( /* array, offset, length */ ) {
  31139. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  31140. },
  31141. makeFrustum: function ( left, right, bottom, top, near, far ) {
  31142. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  31143. return this.makePerspective( left, right, top, bottom, near, far );
  31144. }
  31145. } );
  31146. Plane.prototype.isIntersectionLine = function ( line ) {
  31147. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  31148. return this.intersectsLine( line );
  31149. };
  31150. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  31151. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  31152. return vector.applyQuaternion( this );
  31153. };
  31154. Object.assign( Ray.prototype, {
  31155. isIntersectionBox: function ( box ) {
  31156. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  31157. return this.intersectsBox( box );
  31158. },
  31159. isIntersectionPlane: function ( plane ) {
  31160. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  31161. return this.intersectsPlane( plane );
  31162. },
  31163. isIntersectionSphere: function ( sphere ) {
  31164. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  31165. return this.intersectsSphere( sphere );
  31166. }
  31167. } );
  31168. Object.assign( Triangle.prototype, {
  31169. area: function () {
  31170. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  31171. return this.getArea();
  31172. },
  31173. barycoordFromPoint: function ( point, target ) {
  31174. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  31175. return this.getBarycoord( point, target );
  31176. },
  31177. midpoint: function ( target ) {
  31178. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  31179. return this.getMidpoint( target );
  31180. },
  31181. normal: function ( target ) {
  31182. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  31183. return this.getNormal( target );
  31184. },
  31185. plane: function ( target ) {
  31186. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  31187. return this.getPlane( target );
  31188. }
  31189. } );
  31190. Object.assign( Triangle, {
  31191. barycoordFromPoint: function ( point, a, b, c, target ) {
  31192. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  31193. return Triangle.getBarycoord( point, a, b, c, target );
  31194. },
  31195. normal: function ( a, b, c, target ) {
  31196. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  31197. return Triangle.getNormal( a, b, c, target );
  31198. }
  31199. } );
  31200. Object.assign( Shape.prototype, {
  31201. extractAllPoints: function ( divisions ) {
  31202. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  31203. return this.extractPoints( divisions );
  31204. },
  31205. extrude: function ( options ) {
  31206. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  31207. return new ExtrudeGeometry( this, options );
  31208. },
  31209. makeGeometry: function ( options ) {
  31210. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  31211. return new ShapeGeometry( this, options );
  31212. }
  31213. } );
  31214. Object.assign( Vector2.prototype, {
  31215. fromAttribute: function ( attribute, index, offset ) {
  31216. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  31217. return this.fromBufferAttribute( attribute, index, offset );
  31218. },
  31219. distanceToManhattan: function ( v ) {
  31220. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  31221. return this.manhattanDistanceTo( v );
  31222. },
  31223. lengthManhattan: function () {
  31224. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  31225. return this.manhattanLength();
  31226. }
  31227. } );
  31228. Object.assign( Vector3.prototype, {
  31229. setEulerFromRotationMatrix: function () {
  31230. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  31231. },
  31232. setEulerFromQuaternion: function () {
  31233. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  31234. },
  31235. getPositionFromMatrix: function ( m ) {
  31236. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  31237. return this.setFromMatrixPosition( m );
  31238. },
  31239. getScaleFromMatrix: function ( m ) {
  31240. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  31241. return this.setFromMatrixScale( m );
  31242. },
  31243. getColumnFromMatrix: function ( index, matrix ) {
  31244. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  31245. return this.setFromMatrixColumn( matrix, index );
  31246. },
  31247. applyProjection: function ( m ) {
  31248. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  31249. return this.applyMatrix4( m );
  31250. },
  31251. fromAttribute: function ( attribute, index, offset ) {
  31252. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  31253. return this.fromBufferAttribute( attribute, index, offset );
  31254. },
  31255. distanceToManhattan: function ( v ) {
  31256. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  31257. return this.manhattanDistanceTo( v );
  31258. },
  31259. lengthManhattan: function () {
  31260. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  31261. return this.manhattanLength();
  31262. }
  31263. } );
  31264. Object.assign( Vector4.prototype, {
  31265. fromAttribute: function ( attribute, index, offset ) {
  31266. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  31267. return this.fromBufferAttribute( attribute, index, offset );
  31268. },
  31269. lengthManhattan: function () {
  31270. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  31271. return this.manhattanLength();
  31272. }
  31273. } );
  31274. //
  31275. Object.assign( Geometry.prototype, {
  31276. computeTangents: function () {
  31277. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  31278. },
  31279. computeLineDistances: function () {
  31280. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  31281. }
  31282. } );
  31283. Object.assign( Object3D.prototype, {
  31284. getChildByName: function ( name ) {
  31285. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  31286. return this.getObjectByName( name );
  31287. },
  31288. renderDepth: function () {
  31289. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  31290. },
  31291. translate: function ( distance, axis ) {
  31292. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  31293. return this.translateOnAxis( axis, distance );
  31294. },
  31295. getWorldRotation: function () {
  31296. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  31297. }
  31298. } );
  31299. Object.defineProperties( Object3D.prototype, {
  31300. eulerOrder: {
  31301. get: function () {
  31302. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  31303. return this.rotation.order;
  31304. },
  31305. set: function ( value ) {
  31306. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  31307. this.rotation.order = value;
  31308. }
  31309. },
  31310. useQuaternion: {
  31311. get: function () {
  31312. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  31313. },
  31314. set: function () {
  31315. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  31316. }
  31317. }
  31318. } );
  31319. Object.defineProperties( LOD.prototype, {
  31320. objects: {
  31321. get: function () {
  31322. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  31323. return this.levels;
  31324. }
  31325. }
  31326. } );
  31327. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  31328. get: function () {
  31329. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  31330. },
  31331. set: function () {
  31332. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  31333. }
  31334. } );
  31335. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  31336. get: function () {
  31337. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  31338. return this.arcLengthDivisions;
  31339. },
  31340. set: function ( value ) {
  31341. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  31342. this.arcLengthDivisions = value;
  31343. }
  31344. } );
  31345. //
  31346. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  31347. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  31348. "Use .setFocalLength and .filmGauge for a photographic setup." );
  31349. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  31350. this.setFocalLength( focalLength );
  31351. };
  31352. //
  31353. Object.defineProperties( Light.prototype, {
  31354. onlyShadow: {
  31355. set: function () {
  31356. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  31357. }
  31358. },
  31359. shadowCameraFov: {
  31360. set: function ( value ) {
  31361. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  31362. this.shadow.camera.fov = value;
  31363. }
  31364. },
  31365. shadowCameraLeft: {
  31366. set: function ( value ) {
  31367. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  31368. this.shadow.camera.left = value;
  31369. }
  31370. },
  31371. shadowCameraRight: {
  31372. set: function ( value ) {
  31373. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  31374. this.shadow.camera.right = value;
  31375. }
  31376. },
  31377. shadowCameraTop: {
  31378. set: function ( value ) {
  31379. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  31380. this.shadow.camera.top = value;
  31381. }
  31382. },
  31383. shadowCameraBottom: {
  31384. set: function ( value ) {
  31385. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  31386. this.shadow.camera.bottom = value;
  31387. }
  31388. },
  31389. shadowCameraNear: {
  31390. set: function ( value ) {
  31391. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  31392. this.shadow.camera.near = value;
  31393. }
  31394. },
  31395. shadowCameraFar: {
  31396. set: function ( value ) {
  31397. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  31398. this.shadow.camera.far = value;
  31399. }
  31400. },
  31401. shadowCameraVisible: {
  31402. set: function () {
  31403. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  31404. }
  31405. },
  31406. shadowBias: {
  31407. set: function ( value ) {
  31408. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  31409. this.shadow.bias = value;
  31410. }
  31411. },
  31412. shadowDarkness: {
  31413. set: function () {
  31414. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  31415. }
  31416. },
  31417. shadowMapWidth: {
  31418. set: function ( value ) {
  31419. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  31420. this.shadow.mapSize.width = value;
  31421. }
  31422. },
  31423. shadowMapHeight: {
  31424. set: function ( value ) {
  31425. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  31426. this.shadow.mapSize.height = value;
  31427. }
  31428. }
  31429. } );
  31430. //
  31431. Object.defineProperties( BufferAttribute.prototype, {
  31432. length: {
  31433. get: function () {
  31434. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  31435. return this.array.length;
  31436. }
  31437. },
  31438. copyIndicesArray: function ( /* indices */ ) {
  31439. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  31440. }
  31441. } );
  31442. Object.assign( BufferGeometry.prototype, {
  31443. addIndex: function ( index ) {
  31444. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  31445. this.setIndex( index );
  31446. },
  31447. addDrawCall: function ( start, count, indexOffset ) {
  31448. if ( indexOffset !== undefined ) {
  31449. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  31450. }
  31451. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  31452. this.addGroup( start, count );
  31453. },
  31454. clearDrawCalls: function () {
  31455. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  31456. this.clearGroups();
  31457. },
  31458. computeTangents: function () {
  31459. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  31460. },
  31461. computeOffsets: function () {
  31462. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  31463. }
  31464. } );
  31465. Object.defineProperties( BufferGeometry.prototype, {
  31466. drawcalls: {
  31467. get: function () {
  31468. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  31469. return this.groups;
  31470. }
  31471. },
  31472. offsets: {
  31473. get: function () {
  31474. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  31475. return this.groups;
  31476. }
  31477. }
  31478. } );
  31479. //
  31480. Object.assign( ExtrudeBufferGeometry.prototype, {
  31481. getArrays: function () {
  31482. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  31483. },
  31484. addShapeList: function () {
  31485. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  31486. },
  31487. addShape: function () {
  31488. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  31489. }
  31490. } );
  31491. //
  31492. Object.defineProperties( Uniform.prototype, {
  31493. dynamic: {
  31494. set: function () {
  31495. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  31496. }
  31497. },
  31498. onUpdate: {
  31499. value: function () {
  31500. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  31501. return this;
  31502. }
  31503. }
  31504. } );
  31505. //
  31506. Object.defineProperties( Material.prototype, {
  31507. wrapAround: {
  31508. get: function () {
  31509. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  31510. },
  31511. set: function () {
  31512. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  31513. }
  31514. },
  31515. wrapRGB: {
  31516. get: function () {
  31517. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  31518. return new Color();
  31519. }
  31520. },
  31521. shading: {
  31522. get: function () {
  31523. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  31524. },
  31525. set: function ( value ) {
  31526. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  31527. this.flatShading = ( value === FlatShading );
  31528. }
  31529. }
  31530. } );
  31531. Object.defineProperties( MeshPhongMaterial.prototype, {
  31532. metal: {
  31533. get: function () {
  31534. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  31535. return false;
  31536. },
  31537. set: function () {
  31538. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  31539. }
  31540. }
  31541. } );
  31542. Object.defineProperties( ShaderMaterial.prototype, {
  31543. derivatives: {
  31544. get: function () {
  31545. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  31546. return this.extensions.derivatives;
  31547. },
  31548. set: function ( value ) {
  31549. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  31550. this.extensions.derivatives = value;
  31551. }
  31552. }
  31553. } );
  31554. //
  31555. Object.assign( WebGLRenderer.prototype, {
  31556. animate: function ( callback ) {
  31557. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  31558. this.setAnimationLoop( callback );
  31559. },
  31560. getCurrentRenderTarget: function () {
  31561. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  31562. return this.getRenderTarget();
  31563. },
  31564. getMaxAnisotropy: function () {
  31565. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  31566. return this.capabilities.getMaxAnisotropy();
  31567. },
  31568. getPrecision: function () {
  31569. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  31570. return this.capabilities.precision;
  31571. },
  31572. resetGLState: function () {
  31573. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  31574. return this.state.reset();
  31575. },
  31576. supportsFloatTextures: function () {
  31577. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  31578. return this.extensions.get( 'OES_texture_float' );
  31579. },
  31580. supportsHalfFloatTextures: function () {
  31581. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  31582. return this.extensions.get( 'OES_texture_half_float' );
  31583. },
  31584. supportsStandardDerivatives: function () {
  31585. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  31586. return this.extensions.get( 'OES_standard_derivatives' );
  31587. },
  31588. supportsCompressedTextureS3TC: function () {
  31589. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  31590. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  31591. },
  31592. supportsCompressedTexturePVRTC: function () {
  31593. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  31594. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  31595. },
  31596. supportsBlendMinMax: function () {
  31597. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  31598. return this.extensions.get( 'EXT_blend_minmax' );
  31599. },
  31600. supportsVertexTextures: function () {
  31601. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  31602. return this.capabilities.vertexTextures;
  31603. },
  31604. supportsInstancedArrays: function () {
  31605. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  31606. return this.extensions.get( 'ANGLE_instanced_arrays' );
  31607. },
  31608. enableScissorTest: function ( boolean ) {
  31609. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  31610. this.setScissorTest( boolean );
  31611. },
  31612. initMaterial: function () {
  31613. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  31614. },
  31615. addPrePlugin: function () {
  31616. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  31617. },
  31618. addPostPlugin: function () {
  31619. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  31620. },
  31621. updateShadowMap: function () {
  31622. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  31623. },
  31624. setFaceCulling: function () {
  31625. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  31626. }
  31627. } );
  31628. Object.defineProperties( WebGLRenderer.prototype, {
  31629. shadowMapEnabled: {
  31630. get: function () {
  31631. return this.shadowMap.enabled;
  31632. },
  31633. set: function ( value ) {
  31634. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  31635. this.shadowMap.enabled = value;
  31636. }
  31637. },
  31638. shadowMapType: {
  31639. get: function () {
  31640. return this.shadowMap.type;
  31641. },
  31642. set: function ( value ) {
  31643. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  31644. this.shadowMap.type = value;
  31645. }
  31646. },
  31647. shadowMapCullFace: {
  31648. get: function () {
  31649. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  31650. return undefined;
  31651. },
  31652. set: function ( /* value */ ) {
  31653. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  31654. }
  31655. }
  31656. } );
  31657. Object.defineProperties( WebGLShadowMap.prototype, {
  31658. cullFace: {
  31659. get: function () {
  31660. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  31661. return undefined;
  31662. },
  31663. set: function ( /* cullFace */ ) {
  31664. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  31665. }
  31666. },
  31667. renderReverseSided: {
  31668. get: function () {
  31669. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  31670. return undefined;
  31671. },
  31672. set: function () {
  31673. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  31674. }
  31675. },
  31676. renderSingleSided: {
  31677. get: function () {
  31678. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  31679. return undefined;
  31680. },
  31681. set: function () {
  31682. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  31683. }
  31684. }
  31685. } );
  31686. //
  31687. Object.defineProperties( WebGLRenderTarget.prototype, {
  31688. wrapS: {
  31689. get: function () {
  31690. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31691. return this.texture.wrapS;
  31692. },
  31693. set: function ( value ) {
  31694. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31695. this.texture.wrapS = value;
  31696. }
  31697. },
  31698. wrapT: {
  31699. get: function () {
  31700. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31701. return this.texture.wrapT;
  31702. },
  31703. set: function ( value ) {
  31704. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31705. this.texture.wrapT = value;
  31706. }
  31707. },
  31708. magFilter: {
  31709. get: function () {
  31710. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31711. return this.texture.magFilter;
  31712. },
  31713. set: function ( value ) {
  31714. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31715. this.texture.magFilter = value;
  31716. }
  31717. },
  31718. minFilter: {
  31719. get: function () {
  31720. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31721. return this.texture.minFilter;
  31722. },
  31723. set: function ( value ) {
  31724. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31725. this.texture.minFilter = value;
  31726. }
  31727. },
  31728. anisotropy: {
  31729. get: function () {
  31730. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31731. return this.texture.anisotropy;
  31732. },
  31733. set: function ( value ) {
  31734. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31735. this.texture.anisotropy = value;
  31736. }
  31737. },
  31738. offset: {
  31739. get: function () {
  31740. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31741. return this.texture.offset;
  31742. },
  31743. set: function ( value ) {
  31744. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31745. this.texture.offset = value;
  31746. }
  31747. },
  31748. repeat: {
  31749. get: function () {
  31750. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31751. return this.texture.repeat;
  31752. },
  31753. set: function ( value ) {
  31754. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31755. this.texture.repeat = value;
  31756. }
  31757. },
  31758. format: {
  31759. get: function () {
  31760. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31761. return this.texture.format;
  31762. },
  31763. set: function ( value ) {
  31764. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31765. this.texture.format = value;
  31766. }
  31767. },
  31768. type: {
  31769. get: function () {
  31770. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31771. return this.texture.type;
  31772. },
  31773. set: function ( value ) {
  31774. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31775. this.texture.type = value;
  31776. }
  31777. },
  31778. generateMipmaps: {
  31779. get: function () {
  31780. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31781. return this.texture.generateMipmaps;
  31782. },
  31783. set: function ( value ) {
  31784. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31785. this.texture.generateMipmaps = value;
  31786. }
  31787. }
  31788. } );
  31789. //
  31790. Object.defineProperties( WebVRManager.prototype, {
  31791. standing: {
  31792. set: function ( /* value */ ) {
  31793. console.warn( 'THREE.WebVRManager: .standing has been removed.' );
  31794. }
  31795. }
  31796. } );
  31797. //
  31798. Audio.prototype.load = function ( file ) {
  31799. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  31800. var scope = this;
  31801. var audioLoader = new AudioLoader();
  31802. audioLoader.load( file, function ( buffer ) {
  31803. scope.setBuffer( buffer );
  31804. } );
  31805. return this;
  31806. };
  31807. AudioAnalyser.prototype.getData = function () {
  31808. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  31809. return this.getFrequencyData();
  31810. };
  31811. //
  31812. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  31813. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  31814. return this.update( renderer, scene );
  31815. };
  31816. //
  31817. var GeometryUtils = {
  31818. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  31819. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  31820. var matrix;
  31821. if ( geometry2.isMesh ) {
  31822. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  31823. matrix = geometry2.matrix;
  31824. geometry2 = geometry2.geometry;
  31825. }
  31826. geometry1.merge( geometry2, matrix, materialIndexOffset );
  31827. },
  31828. center: function ( geometry ) {
  31829. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  31830. return geometry.center();
  31831. }
  31832. };
  31833. ImageUtils.crossOrigin = undefined;
  31834. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  31835. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  31836. var loader = new TextureLoader();
  31837. loader.setCrossOrigin( this.crossOrigin );
  31838. var texture = loader.load( url, onLoad, undefined, onError );
  31839. if ( mapping ) texture.mapping = mapping;
  31840. return texture;
  31841. };
  31842. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  31843. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  31844. var loader = new CubeTextureLoader();
  31845. loader.setCrossOrigin( this.crossOrigin );
  31846. var texture = loader.load( urls, onLoad, undefined, onError );
  31847. if ( mapping ) texture.mapping = mapping;
  31848. return texture;
  31849. };
  31850. ImageUtils.loadCompressedTexture = function () {
  31851. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  31852. };
  31853. ImageUtils.loadCompressedTextureCube = function () {
  31854. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  31855. };
  31856. //
  31857. function Projector() {
  31858. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  31859. this.projectVector = function ( vector, camera ) {
  31860. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  31861. vector.project( camera );
  31862. };
  31863. this.unprojectVector = function ( vector, camera ) {
  31864. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  31865. vector.unproject( camera );
  31866. };
  31867. this.pickingRay = function () {
  31868. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  31869. };
  31870. }
  31871. //
  31872. function CanvasRenderer() {
  31873. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  31874. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  31875. this.clear = function () {};
  31876. this.render = function () {};
  31877. this.setClearColor = function () {};
  31878. this.setSize = function () {};
  31879. }
  31880. //
  31881. var SceneUtils = {
  31882. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  31883. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  31884. },
  31885. detach: function ( /* child, parent, scene */ ) {
  31886. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  31887. },
  31888. attach: function ( /* child, scene, parent */ ) {
  31889. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  31890. }
  31891. };
  31892. //
  31893. function LensFlare() {
  31894. console.error( 'THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js' );
  31895. }
  31896. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  31897. exports.WebGLRenderTarget = WebGLRenderTarget;
  31898. exports.WebGLRenderer = WebGLRenderer;
  31899. exports.ShaderLib = ShaderLib;
  31900. exports.UniformsLib = UniformsLib;
  31901. exports.UniformsUtils = UniformsUtils;
  31902. exports.ShaderChunk = ShaderChunk;
  31903. exports.FogExp2 = FogExp2;
  31904. exports.Fog = Fog;
  31905. exports.Scene = Scene;
  31906. exports.Sprite = Sprite;
  31907. exports.LOD = LOD;
  31908. exports.SkinnedMesh = SkinnedMesh;
  31909. exports.Skeleton = Skeleton;
  31910. exports.Bone = Bone;
  31911. exports.Mesh = Mesh;
  31912. exports.LineSegments = LineSegments;
  31913. exports.LineLoop = LineLoop;
  31914. exports.Line = Line;
  31915. exports.Points = Points;
  31916. exports.Group = Group;
  31917. exports.VideoTexture = VideoTexture;
  31918. exports.DataTexture = DataTexture;
  31919. exports.CompressedTexture = CompressedTexture;
  31920. exports.CubeTexture = CubeTexture;
  31921. exports.CanvasTexture = CanvasTexture;
  31922. exports.DepthTexture = DepthTexture;
  31923. exports.Texture = Texture;
  31924. exports.CompressedTextureLoader = CompressedTextureLoader;
  31925. exports.DataTextureLoader = DataTextureLoader;
  31926. exports.CubeTextureLoader = CubeTextureLoader;
  31927. exports.TextureLoader = TextureLoader;
  31928. exports.ObjectLoader = ObjectLoader;
  31929. exports.MaterialLoader = MaterialLoader;
  31930. exports.BufferGeometryLoader = BufferGeometryLoader;
  31931. exports.DefaultLoadingManager = DefaultLoadingManager;
  31932. exports.LoadingManager = LoadingManager;
  31933. exports.JSONLoader = JSONLoader;
  31934. exports.ImageLoader = ImageLoader;
  31935. exports.ImageBitmapLoader = ImageBitmapLoader;
  31936. exports.FontLoader = FontLoader;
  31937. exports.FileLoader = FileLoader;
  31938. exports.Loader = Loader;
  31939. exports.LoaderUtils = LoaderUtils;
  31940. exports.Cache = Cache;
  31941. exports.AudioLoader = AudioLoader;
  31942. exports.SpotLightShadow = SpotLightShadow;
  31943. exports.SpotLight = SpotLight;
  31944. exports.PointLight = PointLight;
  31945. exports.RectAreaLight = RectAreaLight;
  31946. exports.HemisphereLight = HemisphereLight;
  31947. exports.DirectionalLightShadow = DirectionalLightShadow;
  31948. exports.DirectionalLight = DirectionalLight;
  31949. exports.AmbientLight = AmbientLight;
  31950. exports.LightShadow = LightShadow;
  31951. exports.Light = Light;
  31952. exports.StereoCamera = StereoCamera;
  31953. exports.PerspectiveCamera = PerspectiveCamera;
  31954. exports.OrthographicCamera = OrthographicCamera;
  31955. exports.CubeCamera = CubeCamera;
  31956. exports.ArrayCamera = ArrayCamera;
  31957. exports.Camera = Camera;
  31958. exports.AudioListener = AudioListener;
  31959. exports.PositionalAudio = PositionalAudio;
  31960. exports.AudioContext = AudioContext;
  31961. exports.AudioAnalyser = AudioAnalyser;
  31962. exports.Audio = Audio;
  31963. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  31964. exports.StringKeyframeTrack = StringKeyframeTrack;
  31965. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  31966. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  31967. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  31968. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  31969. exports.PropertyMixer = PropertyMixer;
  31970. exports.PropertyBinding = PropertyBinding;
  31971. exports.KeyframeTrack = KeyframeTrack;
  31972. exports.AnimationUtils = AnimationUtils;
  31973. exports.AnimationObjectGroup = AnimationObjectGroup;
  31974. exports.AnimationMixer = AnimationMixer;
  31975. exports.AnimationClip = AnimationClip;
  31976. exports.Uniform = Uniform;
  31977. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  31978. exports.BufferGeometry = BufferGeometry;
  31979. exports.Geometry = Geometry;
  31980. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  31981. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  31982. exports.InterleavedBuffer = InterleavedBuffer;
  31983. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  31984. exports.Face3 = Face3;
  31985. exports.Object3D = Object3D;
  31986. exports.Raycaster = Raycaster;
  31987. exports.Layers = Layers;
  31988. exports.EventDispatcher = EventDispatcher;
  31989. exports.Clock = Clock;
  31990. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  31991. exports.LinearInterpolant = LinearInterpolant;
  31992. exports.DiscreteInterpolant = DiscreteInterpolant;
  31993. exports.CubicInterpolant = CubicInterpolant;
  31994. exports.Interpolant = Interpolant;
  31995. exports.Triangle = Triangle;
  31996. exports.Math = _Math;
  31997. exports.Spherical = Spherical;
  31998. exports.Cylindrical = Cylindrical;
  31999. exports.Plane = Plane;
  32000. exports.Frustum = Frustum;
  32001. exports.Sphere = Sphere;
  32002. exports.Ray = Ray;
  32003. exports.Matrix4 = Matrix4;
  32004. exports.Matrix3 = Matrix3;
  32005. exports.Box3 = Box3;
  32006. exports.Box2 = Box2;
  32007. exports.Line3 = Line3;
  32008. exports.Euler = Euler;
  32009. exports.Vector4 = Vector4;
  32010. exports.Vector3 = Vector3;
  32011. exports.Vector2 = Vector2;
  32012. exports.Quaternion = Quaternion;
  32013. exports.Color = Color;
  32014. exports.ImmediateRenderObject = ImmediateRenderObject;
  32015. exports.VertexNormalsHelper = VertexNormalsHelper;
  32016. exports.SpotLightHelper = SpotLightHelper;
  32017. exports.SkeletonHelper = SkeletonHelper;
  32018. exports.PointLightHelper = PointLightHelper;
  32019. exports.RectAreaLightHelper = RectAreaLightHelper;
  32020. exports.HemisphereLightHelper = HemisphereLightHelper;
  32021. exports.GridHelper = GridHelper;
  32022. exports.PolarGridHelper = PolarGridHelper;
  32023. exports.FaceNormalsHelper = FaceNormalsHelper;
  32024. exports.DirectionalLightHelper = DirectionalLightHelper;
  32025. exports.CameraHelper = CameraHelper;
  32026. exports.BoxHelper = BoxHelper;
  32027. exports.Box3Helper = Box3Helper;
  32028. exports.PlaneHelper = PlaneHelper;
  32029. exports.ArrowHelper = ArrowHelper;
  32030. exports.AxesHelper = AxesHelper;
  32031. exports.Shape = Shape;
  32032. exports.Path = Path;
  32033. exports.ShapePath = ShapePath;
  32034. exports.Font = Font;
  32035. exports.CurvePath = CurvePath;
  32036. exports.Curve = Curve;
  32037. exports.ImageUtils = ImageUtils;
  32038. exports.ShapeUtils = ShapeUtils;
  32039. exports.WebGLUtils = WebGLUtils;
  32040. exports.WireframeGeometry = WireframeGeometry;
  32041. exports.ParametricGeometry = ParametricGeometry;
  32042. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  32043. exports.TetrahedronGeometry = TetrahedronGeometry;
  32044. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  32045. exports.OctahedronGeometry = OctahedronGeometry;
  32046. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  32047. exports.IcosahedronGeometry = IcosahedronGeometry;
  32048. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  32049. exports.DodecahedronGeometry = DodecahedronGeometry;
  32050. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  32051. exports.PolyhedronGeometry = PolyhedronGeometry;
  32052. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  32053. exports.TubeGeometry = TubeGeometry;
  32054. exports.TubeBufferGeometry = TubeBufferGeometry;
  32055. exports.TorusKnotGeometry = TorusKnotGeometry;
  32056. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  32057. exports.TorusGeometry = TorusGeometry;
  32058. exports.TorusBufferGeometry = TorusBufferGeometry;
  32059. exports.TextGeometry = TextGeometry;
  32060. exports.TextBufferGeometry = TextBufferGeometry;
  32061. exports.SphereGeometry = SphereGeometry;
  32062. exports.SphereBufferGeometry = SphereBufferGeometry;
  32063. exports.RingGeometry = RingGeometry;
  32064. exports.RingBufferGeometry = RingBufferGeometry;
  32065. exports.PlaneGeometry = PlaneGeometry;
  32066. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  32067. exports.LatheGeometry = LatheGeometry;
  32068. exports.LatheBufferGeometry = LatheBufferGeometry;
  32069. exports.ShapeGeometry = ShapeGeometry;
  32070. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  32071. exports.ExtrudeGeometry = ExtrudeGeometry;
  32072. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  32073. exports.EdgesGeometry = EdgesGeometry;
  32074. exports.ConeGeometry = ConeGeometry;
  32075. exports.ConeBufferGeometry = ConeBufferGeometry;
  32076. exports.CylinderGeometry = CylinderGeometry;
  32077. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  32078. exports.CircleGeometry = CircleGeometry;
  32079. exports.CircleBufferGeometry = CircleBufferGeometry;
  32080. exports.BoxGeometry = BoxGeometry;
  32081. exports.BoxBufferGeometry = BoxBufferGeometry;
  32082. exports.ShadowMaterial = ShadowMaterial;
  32083. exports.SpriteMaterial = SpriteMaterial;
  32084. exports.RawShaderMaterial = RawShaderMaterial;
  32085. exports.ShaderMaterial = ShaderMaterial;
  32086. exports.PointsMaterial = PointsMaterial;
  32087. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  32088. exports.MeshStandardMaterial = MeshStandardMaterial;
  32089. exports.MeshPhongMaterial = MeshPhongMaterial;
  32090. exports.MeshToonMaterial = MeshToonMaterial;
  32091. exports.MeshNormalMaterial = MeshNormalMaterial;
  32092. exports.MeshLambertMaterial = MeshLambertMaterial;
  32093. exports.MeshDepthMaterial = MeshDepthMaterial;
  32094. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  32095. exports.MeshBasicMaterial = MeshBasicMaterial;
  32096. exports.LineDashedMaterial = LineDashedMaterial;
  32097. exports.LineBasicMaterial = LineBasicMaterial;
  32098. exports.Material = Material;
  32099. exports.Float64BufferAttribute = Float64BufferAttribute;
  32100. exports.Float32BufferAttribute = Float32BufferAttribute;
  32101. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  32102. exports.Int32BufferAttribute = Int32BufferAttribute;
  32103. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  32104. exports.Int16BufferAttribute = Int16BufferAttribute;
  32105. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  32106. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  32107. exports.Int8BufferAttribute = Int8BufferAttribute;
  32108. exports.BufferAttribute = BufferAttribute;
  32109. exports.ArcCurve = ArcCurve;
  32110. exports.CatmullRomCurve3 = CatmullRomCurve3;
  32111. exports.CubicBezierCurve = CubicBezierCurve;
  32112. exports.CubicBezierCurve3 = CubicBezierCurve3;
  32113. exports.EllipseCurve = EllipseCurve;
  32114. exports.LineCurve = LineCurve;
  32115. exports.LineCurve3 = LineCurve3;
  32116. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  32117. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  32118. exports.SplineCurve = SplineCurve;
  32119. exports.REVISION = REVISION;
  32120. exports.MOUSE = MOUSE;
  32121. exports.CullFaceNone = CullFaceNone;
  32122. exports.CullFaceBack = CullFaceBack;
  32123. exports.CullFaceFront = CullFaceFront;
  32124. exports.CullFaceFrontBack = CullFaceFrontBack;
  32125. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  32126. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  32127. exports.BasicShadowMap = BasicShadowMap;
  32128. exports.PCFShadowMap = PCFShadowMap;
  32129. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  32130. exports.FrontSide = FrontSide;
  32131. exports.BackSide = BackSide;
  32132. exports.DoubleSide = DoubleSide;
  32133. exports.FlatShading = FlatShading;
  32134. exports.SmoothShading = SmoothShading;
  32135. exports.NoColors = NoColors;
  32136. exports.FaceColors = FaceColors;
  32137. exports.VertexColors = VertexColors;
  32138. exports.NoBlending = NoBlending;
  32139. exports.NormalBlending = NormalBlending;
  32140. exports.AdditiveBlending = AdditiveBlending;
  32141. exports.SubtractiveBlending = SubtractiveBlending;
  32142. exports.MultiplyBlending = MultiplyBlending;
  32143. exports.CustomBlending = CustomBlending;
  32144. exports.AddEquation = AddEquation;
  32145. exports.SubtractEquation = SubtractEquation;
  32146. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  32147. exports.MinEquation = MinEquation;
  32148. exports.MaxEquation = MaxEquation;
  32149. exports.ZeroFactor = ZeroFactor;
  32150. exports.OneFactor = OneFactor;
  32151. exports.SrcColorFactor = SrcColorFactor;
  32152. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  32153. exports.SrcAlphaFactor = SrcAlphaFactor;
  32154. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  32155. exports.DstAlphaFactor = DstAlphaFactor;
  32156. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  32157. exports.DstColorFactor = DstColorFactor;
  32158. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  32159. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  32160. exports.NeverDepth = NeverDepth;
  32161. exports.AlwaysDepth = AlwaysDepth;
  32162. exports.LessDepth = LessDepth;
  32163. exports.LessEqualDepth = LessEqualDepth;
  32164. exports.EqualDepth = EqualDepth;
  32165. exports.GreaterEqualDepth = GreaterEqualDepth;
  32166. exports.GreaterDepth = GreaterDepth;
  32167. exports.NotEqualDepth = NotEqualDepth;
  32168. exports.MultiplyOperation = MultiplyOperation;
  32169. exports.MixOperation = MixOperation;
  32170. exports.AddOperation = AddOperation;
  32171. exports.NoToneMapping = NoToneMapping;
  32172. exports.LinearToneMapping = LinearToneMapping;
  32173. exports.ReinhardToneMapping = ReinhardToneMapping;
  32174. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  32175. exports.CineonToneMapping = CineonToneMapping;
  32176. exports.UVMapping = UVMapping;
  32177. exports.CubeReflectionMapping = CubeReflectionMapping;
  32178. exports.CubeRefractionMapping = CubeRefractionMapping;
  32179. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  32180. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  32181. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  32182. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  32183. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  32184. exports.RepeatWrapping = RepeatWrapping;
  32185. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  32186. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  32187. exports.NearestFilter = NearestFilter;
  32188. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  32189. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  32190. exports.LinearFilter = LinearFilter;
  32191. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  32192. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  32193. exports.UnsignedByteType = UnsignedByteType;
  32194. exports.ByteType = ByteType;
  32195. exports.ShortType = ShortType;
  32196. exports.UnsignedShortType = UnsignedShortType;
  32197. exports.IntType = IntType;
  32198. exports.UnsignedIntType = UnsignedIntType;
  32199. exports.FloatType = FloatType;
  32200. exports.HalfFloatType = HalfFloatType;
  32201. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  32202. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  32203. exports.UnsignedShort565Type = UnsignedShort565Type;
  32204. exports.UnsignedInt248Type = UnsignedInt248Type;
  32205. exports.AlphaFormat = AlphaFormat;
  32206. exports.RGBFormat = RGBFormat;
  32207. exports.RGBAFormat = RGBAFormat;
  32208. exports.LuminanceFormat = LuminanceFormat;
  32209. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  32210. exports.RGBEFormat = RGBEFormat;
  32211. exports.DepthFormat = DepthFormat;
  32212. exports.DepthStencilFormat = DepthStencilFormat;
  32213. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  32214. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  32215. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  32216. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  32217. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  32218. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  32219. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  32220. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  32221. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  32222. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  32223. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  32224. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  32225. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  32226. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  32227. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  32228. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  32229. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  32230. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  32231. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  32232. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  32233. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  32234. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  32235. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  32236. exports.LoopOnce = LoopOnce;
  32237. exports.LoopRepeat = LoopRepeat;
  32238. exports.LoopPingPong = LoopPingPong;
  32239. exports.InterpolateDiscrete = InterpolateDiscrete;
  32240. exports.InterpolateLinear = InterpolateLinear;
  32241. exports.InterpolateSmooth = InterpolateSmooth;
  32242. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  32243. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  32244. exports.WrapAroundEnding = WrapAroundEnding;
  32245. exports.TrianglesDrawMode = TrianglesDrawMode;
  32246. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  32247. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  32248. exports.LinearEncoding = LinearEncoding;
  32249. exports.sRGBEncoding = sRGBEncoding;
  32250. exports.GammaEncoding = GammaEncoding;
  32251. exports.RGBEEncoding = RGBEEncoding;
  32252. exports.LogLuvEncoding = LogLuvEncoding;
  32253. exports.RGBM7Encoding = RGBM7Encoding;
  32254. exports.RGBM16Encoding = RGBM16Encoding;
  32255. exports.RGBDEncoding = RGBDEncoding;
  32256. exports.BasicDepthPacking = BasicDepthPacking;
  32257. exports.RGBADepthPacking = RGBADepthPacking;
  32258. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  32259. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  32260. exports.CubeGeometry = BoxGeometry;
  32261. exports.Face4 = Face4;
  32262. exports.LineStrip = LineStrip;
  32263. exports.LinePieces = LinePieces;
  32264. exports.MeshFaceMaterial = MeshFaceMaterial;
  32265. exports.MultiMaterial = MultiMaterial;
  32266. exports.PointCloud = PointCloud;
  32267. exports.Particle = Particle;
  32268. exports.ParticleSystem = ParticleSystem;
  32269. exports.PointCloudMaterial = PointCloudMaterial;
  32270. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  32271. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  32272. exports.Vertex = Vertex;
  32273. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  32274. exports.Int8Attribute = Int8Attribute;
  32275. exports.Uint8Attribute = Uint8Attribute;
  32276. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  32277. exports.Int16Attribute = Int16Attribute;
  32278. exports.Uint16Attribute = Uint16Attribute;
  32279. exports.Int32Attribute = Int32Attribute;
  32280. exports.Uint32Attribute = Uint32Attribute;
  32281. exports.Float32Attribute = Float32Attribute;
  32282. exports.Float64Attribute = Float64Attribute;
  32283. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  32284. exports.SplineCurve3 = SplineCurve3;
  32285. exports.Spline = Spline;
  32286. exports.AxisHelper = AxisHelper;
  32287. exports.BoundingBoxHelper = BoundingBoxHelper;
  32288. exports.EdgesHelper = EdgesHelper;
  32289. exports.WireframeHelper = WireframeHelper;
  32290. exports.XHRLoader = XHRLoader;
  32291. exports.BinaryTextureLoader = BinaryTextureLoader;
  32292. exports.GeometryUtils = GeometryUtils;
  32293. exports.Projector = Projector;
  32294. exports.CanvasRenderer = CanvasRenderer;
  32295. exports.SceneUtils = SceneUtils;
  32296. exports.LensFlare = LensFlare;
  32297. Object.defineProperty(exports, '__esModule', { value: true });
  32298. })));
  32299. },{}],41:[function(_dereq_,module,exports){
  32300. /**
  32301. * @author mrdoob / http://mrdoob.com/
  32302. * @author Mugen87 / https://github.com/Mugen87
  32303. */
  32304. THREE.ColladaLoader = function ( manager ) {
  32305. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  32306. };
  32307. THREE.ColladaLoader.prototype = {
  32308. constructor: THREE.ColladaLoader,
  32309. crossOrigin: 'anonymous',
  32310. load: function ( url, onLoad, onProgress, onError ) {
  32311. var scope = this;
  32312. var path = scope.path === undefined ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path;
  32313. var loader = new THREE.FileLoader( scope.manager );
  32314. loader.load( url, function ( text ) {
  32315. onLoad( scope.parse( text, path ) );
  32316. }, onProgress, onError );
  32317. },
  32318. setPath: function ( value ) {
  32319. this.path = value;
  32320. return this;
  32321. },
  32322. options: {
  32323. set convertUpAxis( value ) {
  32324. console.warn( 'THREE.ColladaLoader: options.convertUpAxis() has been removed. Up axis is converted automatically.' );
  32325. }
  32326. },
  32327. setCrossOrigin: function ( value ) {
  32328. this.crossOrigin = value;
  32329. return this;
  32330. },
  32331. parse: function ( text, path ) {
  32332. function getElementsByTagName( xml, name ) {
  32333. // Non recursive xml.getElementsByTagName() ...
  32334. var array = [];
  32335. var childNodes = xml.childNodes;
  32336. for ( var i = 0, l = childNodes.length; i < l; i ++ ) {
  32337. var child = childNodes[ i ];
  32338. if ( child.nodeName === name ) {
  32339. array.push( child );
  32340. }
  32341. }
  32342. return array;
  32343. }
  32344. function parseStrings( text ) {
  32345. if ( text.length === 0 ) return [];
  32346. var parts = text.trim().split( /\s+/ );
  32347. var array = new Array( parts.length );
  32348. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32349. array[ i ] = parts[ i ];
  32350. }
  32351. return array;
  32352. }
  32353. function parseFloats( text ) {
  32354. if ( text.length === 0 ) return [];
  32355. var parts = text.trim().split( /\s+/ );
  32356. var array = new Array( parts.length );
  32357. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32358. array[ i ] = parseFloat( parts[ i ] );
  32359. }
  32360. return array;
  32361. }
  32362. function parseInts( text ) {
  32363. if ( text.length === 0 ) return [];
  32364. var parts = text.trim().split( /\s+/ );
  32365. var array = new Array( parts.length );
  32366. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32367. array[ i ] = parseInt( parts[ i ] );
  32368. }
  32369. return array;
  32370. }
  32371. function parseId( text ) {
  32372. return text.substring( 1 );
  32373. }
  32374. function generateId() {
  32375. return 'three_default_' + ( count ++ );
  32376. }
  32377. function isEmpty( object ) {
  32378. return Object.keys( object ).length === 0;
  32379. }
  32380. // asset
  32381. function parseAsset( xml ) {
  32382. return {
  32383. unit: parseAssetUnit( getElementsByTagName( xml, 'unit' )[ 0 ] ),
  32384. upAxis: parseAssetUpAxis( getElementsByTagName( xml, 'up_axis' )[ 0 ] )
  32385. };
  32386. }
  32387. function parseAssetUnit( xml ) {
  32388. if ( ( xml !== undefined ) && ( xml.hasAttribute( 'meter' ) === true ) ) {
  32389. return parseFloat( xml.getAttribute( 'meter' ) );
  32390. } else {
  32391. return 1; // default 1 meter
  32392. }
  32393. }
  32394. function parseAssetUpAxis( xml ) {
  32395. return xml !== undefined ? xml.textContent : 'Y_UP';
  32396. }
  32397. // library
  32398. function parseLibrary( xml, libraryName, nodeName, parser ) {
  32399. var library = getElementsByTagName( xml, libraryName )[ 0 ];
  32400. if ( library !== undefined ) {
  32401. var elements = getElementsByTagName( library, nodeName );
  32402. for ( var i = 0; i < elements.length; i ++ ) {
  32403. parser( elements[ i ] );
  32404. }
  32405. }
  32406. }
  32407. function buildLibrary( data, builder ) {
  32408. for ( var name in data ) {
  32409. var object = data[ name ];
  32410. object.build = builder( data[ name ] );
  32411. }
  32412. }
  32413. // get
  32414. function getBuild( data, builder ) {
  32415. if ( data.build !== undefined ) return data.build;
  32416. data.build = builder( data );
  32417. return data.build;
  32418. }
  32419. // animation
  32420. function parseAnimation( xml ) {
  32421. var data = {
  32422. sources: {},
  32423. samplers: {},
  32424. channels: {}
  32425. };
  32426. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32427. var child = xml.childNodes[ i ];
  32428. if ( child.nodeType !== 1 ) continue;
  32429. var id;
  32430. switch ( child.nodeName ) {
  32431. case 'source':
  32432. id = child.getAttribute( 'id' );
  32433. data.sources[ id ] = parseSource( child );
  32434. break;
  32435. case 'sampler':
  32436. id = child.getAttribute( 'id' );
  32437. data.samplers[ id ] = parseAnimationSampler( child );
  32438. break;
  32439. case 'channel':
  32440. id = child.getAttribute( 'target' );
  32441. data.channels[ id ] = parseAnimationChannel( child );
  32442. break;
  32443. default:
  32444. console.log( child );
  32445. }
  32446. }
  32447. library.animations[ xml.getAttribute( 'id' ) ] = data;
  32448. }
  32449. function parseAnimationSampler( xml ) {
  32450. var data = {
  32451. inputs: {},
  32452. };
  32453. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32454. var child = xml.childNodes[ i ];
  32455. if ( child.nodeType !== 1 ) continue;
  32456. switch ( child.nodeName ) {
  32457. case 'input':
  32458. var id = parseId( child.getAttribute( 'source' ) );
  32459. var semantic = child.getAttribute( 'semantic' );
  32460. data.inputs[ semantic ] = id;
  32461. break;
  32462. }
  32463. }
  32464. return data;
  32465. }
  32466. function parseAnimationChannel( xml ) {
  32467. var data = {};
  32468. var target = xml.getAttribute( 'target' );
  32469. // parsing SID Addressing Syntax
  32470. var parts = target.split( '/' );
  32471. var id = parts.shift();
  32472. var sid = parts.shift();
  32473. // check selection syntax
  32474. var arraySyntax = ( sid.indexOf( '(' ) !== - 1 );
  32475. var memberSyntax = ( sid.indexOf( '.' ) !== - 1 );
  32476. if ( memberSyntax ) {
  32477. // member selection access
  32478. parts = sid.split( '.' );
  32479. sid = parts.shift();
  32480. data.member = parts.shift();
  32481. } else if ( arraySyntax ) {
  32482. // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
  32483. var indices = sid.split( '(' );
  32484. sid = indices.shift();
  32485. for ( var i = 0; i < indices.length; i ++ ) {
  32486. indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) );
  32487. }
  32488. data.indices = indices;
  32489. }
  32490. data.id = id;
  32491. data.sid = sid;
  32492. data.arraySyntax = arraySyntax;
  32493. data.memberSyntax = memberSyntax;
  32494. data.sampler = parseId( xml.getAttribute( 'source' ) );
  32495. return data;
  32496. }
  32497. function buildAnimation( data ) {
  32498. var tracks = [];
  32499. var channels = data.channels;
  32500. var samplers = data.samplers;
  32501. var sources = data.sources;
  32502. for ( var target in channels ) {
  32503. if ( channels.hasOwnProperty( target ) ) {
  32504. var channel = channels[ target ];
  32505. var sampler = samplers[ channel.sampler ];
  32506. var inputId = sampler.inputs.INPUT;
  32507. var outputId = sampler.inputs.OUTPUT;
  32508. var inputSource = sources[ inputId ];
  32509. var outputSource = sources[ outputId ];
  32510. var animation = buildAnimationChannel( channel, inputSource, outputSource );
  32511. createKeyframeTracks( animation, tracks );
  32512. }
  32513. }
  32514. return tracks;
  32515. }
  32516. function getAnimation( id ) {
  32517. return getBuild( library.animations[ id ], buildAnimation );
  32518. }
  32519. function buildAnimationChannel( channel, inputSource, outputSource ) {
  32520. var node = library.nodes[ channel.id ];
  32521. var object3D = getNode( node.id );
  32522. var transform = node.transforms[ channel.sid ];
  32523. var defaultMatrix = node.matrix.clone().transpose();
  32524. var time, stride;
  32525. var i, il, j, jl;
  32526. var data = {};
  32527. // the collada spec allows the animation of data in various ways.
  32528. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic
  32529. switch ( transform ) {
  32530. case 'matrix':
  32531. for ( i = 0, il = inputSource.array.length; i < il; i ++ ) {
  32532. time = inputSource.array[ i ];
  32533. stride = i * outputSource.stride;
  32534. if ( data[ time ] === undefined ) data[ time ] = {};
  32535. if ( channel.arraySyntax === true ) {
  32536. var value = outputSource.array[ stride ];
  32537. var index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ];
  32538. data[ time ][ index ] = value;
  32539. } else {
  32540. for ( j = 0, jl = outputSource.stride; j < jl; j ++ ) {
  32541. data[ time ][ j ] = outputSource.array[ stride + j ];
  32542. }
  32543. }
  32544. }
  32545. break;
  32546. case 'translate':
  32547. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  32548. break;
  32549. case 'rotate':
  32550. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  32551. break;
  32552. case 'scale':
  32553. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  32554. break;
  32555. }
  32556. var keyframes = prepareAnimationData( data, defaultMatrix );
  32557. var animation = {
  32558. name: object3D.uuid,
  32559. keyframes: keyframes
  32560. };
  32561. return animation;
  32562. }
  32563. function prepareAnimationData( data, defaultMatrix ) {
  32564. var keyframes = [];
  32565. // transfer data into a sortable array
  32566. for ( var time in data ) {
  32567. keyframes.push( { time: parseFloat( time ), value: data[ time ] } );
  32568. }
  32569. // ensure keyframes are sorted by time
  32570. keyframes.sort( ascending );
  32571. // now we clean up all animation data, so we can use them for keyframe tracks
  32572. for ( var i = 0; i < 16; i ++ ) {
  32573. transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );
  32574. }
  32575. return keyframes;
  32576. // array sort function
  32577. function ascending( a, b ) {
  32578. return a.time - b.time;
  32579. }
  32580. }
  32581. var position = new THREE.Vector3();
  32582. var scale = new THREE.Vector3();
  32583. var quaternion = new THREE.Quaternion();
  32584. function createKeyframeTracks( animation, tracks ) {
  32585. var keyframes = animation.keyframes;
  32586. var name = animation.name;
  32587. var times = [];
  32588. var positionData = [];
  32589. var quaternionData = [];
  32590. var scaleData = [];
  32591. for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
  32592. var keyframe = keyframes[ i ];
  32593. var time = keyframe.time;
  32594. var value = keyframe.value;
  32595. matrix.fromArray( value ).transpose();
  32596. matrix.decompose( position, quaternion, scale );
  32597. times.push( time );
  32598. positionData.push( position.x, position.y, position.z );
  32599. quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  32600. scaleData.push( scale.x, scale.y, scale.z );
  32601. }
  32602. if ( positionData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.position', times, positionData ) );
  32603. if ( quaternionData.length > 0 ) tracks.push( new THREE.QuaternionKeyframeTrack( name + '.quaternion', times, quaternionData ) );
  32604. if ( scaleData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.scale', times, scaleData ) );
  32605. return tracks;
  32606. }
  32607. function transformAnimationData( keyframes, property, defaultValue ) {
  32608. var keyframe;
  32609. var empty = true;
  32610. var i, l;
  32611. // check, if values of a property are missing in our keyframes
  32612. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  32613. keyframe = keyframes[ i ];
  32614. if ( keyframe.value[ property ] === undefined ) {
  32615. keyframe.value[ property ] = null; // mark as missing
  32616. } else {
  32617. empty = false;
  32618. }
  32619. }
  32620. if ( empty === true ) {
  32621. // no values at all, so we set a default value
  32622. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  32623. keyframe = keyframes[ i ];
  32624. keyframe.value[ property ] = defaultValue;
  32625. }
  32626. } else {
  32627. // filling gaps
  32628. createMissingKeyframes( keyframes, property );
  32629. }
  32630. }
  32631. function createMissingKeyframes( keyframes, property ) {
  32632. var prev, next;
  32633. for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
  32634. var keyframe = keyframes[ i ];
  32635. if ( keyframe.value[ property ] === null ) {
  32636. prev = getPrev( keyframes, i, property );
  32637. next = getNext( keyframes, i, property );
  32638. if ( prev === null ) {
  32639. keyframe.value[ property ] = next.value[ property ];
  32640. continue;
  32641. }
  32642. if ( next === null ) {
  32643. keyframe.value[ property ] = prev.value[ property ];
  32644. continue;
  32645. }
  32646. interpolate( keyframe, prev, next, property );
  32647. }
  32648. }
  32649. }
  32650. function getPrev( keyframes, i, property ) {
  32651. while ( i >= 0 ) {
  32652. var keyframe = keyframes[ i ];
  32653. if ( keyframe.value[ property ] !== null ) return keyframe;
  32654. i --;
  32655. }
  32656. return null;
  32657. }
  32658. function getNext( keyframes, i, property ) {
  32659. while ( i < keyframes.length ) {
  32660. var keyframe = keyframes[ i ];
  32661. if ( keyframe.value[ property ] !== null ) return keyframe;
  32662. i ++;
  32663. }
  32664. return null;
  32665. }
  32666. function interpolate( key, prev, next, property ) {
  32667. if ( ( next.time - prev.time ) === 0 ) {
  32668. key.value[ property ] = prev.value[ property ];
  32669. return;
  32670. }
  32671. key.value[ property ] = ( ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) ) + prev.value[ property ];
  32672. }
  32673. // animation clips
  32674. function parseAnimationClip( xml ) {
  32675. var data = {
  32676. name: xml.getAttribute( 'id' ) || 'default',
  32677. start: parseFloat( xml.getAttribute( 'start' ) || 0 ),
  32678. end: parseFloat( xml.getAttribute( 'end' ) || 0 ),
  32679. animations: []
  32680. };
  32681. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32682. var child = xml.childNodes[ i ];
  32683. if ( child.nodeType !== 1 ) continue;
  32684. switch ( child.nodeName ) {
  32685. case 'instance_animation':
  32686. data.animations.push( parseId( child.getAttribute( 'url' ) ) );
  32687. break;
  32688. }
  32689. }
  32690. library.clips[ xml.getAttribute( 'id' ) ] = data;
  32691. }
  32692. function buildAnimationClip( data ) {
  32693. var tracks = [];
  32694. var name = data.name;
  32695. var duration = ( data.end - data.start ) || - 1;
  32696. var animations = data.animations;
  32697. for ( var i = 0, il = animations.length; i < il; i ++ ) {
  32698. var animationTracks = getAnimation( animations[ i ] );
  32699. for ( var j = 0, jl = animationTracks.length; j < jl; j ++ ) {
  32700. tracks.push( animationTracks[ j ] );
  32701. }
  32702. }
  32703. return new THREE.AnimationClip( name, duration, tracks );
  32704. }
  32705. function getAnimationClip( id ) {
  32706. return getBuild( library.clips[ id ], buildAnimationClip );
  32707. }
  32708. // controller
  32709. function parseController( xml ) {
  32710. var data = {};
  32711. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32712. var child = xml.childNodes[ i ];
  32713. if ( child.nodeType !== 1 ) continue;
  32714. switch ( child.nodeName ) {
  32715. case 'skin':
  32716. // there is exactly one skin per controller
  32717. data.id = parseId( child.getAttribute( 'source' ) );
  32718. data.skin = parseSkin( child );
  32719. break;
  32720. case 'morph':
  32721. data.id = parseId( child.getAttribute( 'source' ) );
  32722. console.warn( 'THREE.ColladaLoader: Morph target animation not supported yet.' );
  32723. break;
  32724. }
  32725. }
  32726. library.controllers[ xml.getAttribute( 'id' ) ] = data;
  32727. }
  32728. function parseSkin( xml ) {
  32729. var data = {
  32730. sources: {}
  32731. };
  32732. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32733. var child = xml.childNodes[ i ];
  32734. if ( child.nodeType !== 1 ) continue;
  32735. switch ( child.nodeName ) {
  32736. case 'bind_shape_matrix':
  32737. data.bindShapeMatrix = parseFloats( child.textContent );
  32738. break;
  32739. case 'source':
  32740. var id = child.getAttribute( 'id' );
  32741. data.sources[ id ] = parseSource( child );
  32742. break;
  32743. case 'joints':
  32744. data.joints = parseJoints( child );
  32745. break;
  32746. case 'vertex_weights':
  32747. data.vertexWeights = parseVertexWeights( child );
  32748. break;
  32749. }
  32750. }
  32751. return data;
  32752. }
  32753. function parseJoints( xml ) {
  32754. var data = {
  32755. inputs: {}
  32756. };
  32757. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32758. var child = xml.childNodes[ i ];
  32759. if ( child.nodeType !== 1 ) continue;
  32760. switch ( child.nodeName ) {
  32761. case 'input':
  32762. var semantic = child.getAttribute( 'semantic' );
  32763. var id = parseId( child.getAttribute( 'source' ) );
  32764. data.inputs[ semantic ] = id;
  32765. break;
  32766. }
  32767. }
  32768. return data;
  32769. }
  32770. function parseVertexWeights( xml ) {
  32771. var data = {
  32772. inputs: {}
  32773. };
  32774. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32775. var child = xml.childNodes[ i ];
  32776. if ( child.nodeType !== 1 ) continue;
  32777. switch ( child.nodeName ) {
  32778. case 'input':
  32779. var semantic = child.getAttribute( 'semantic' );
  32780. var id = parseId( child.getAttribute( 'source' ) );
  32781. var offset = parseInt( child.getAttribute( 'offset' ) );
  32782. data.inputs[ semantic ] = { id: id, offset: offset };
  32783. break;
  32784. case 'vcount':
  32785. data.vcount = parseInts( child.textContent );
  32786. break;
  32787. case 'v':
  32788. data.v = parseInts( child.textContent );
  32789. break;
  32790. }
  32791. }
  32792. return data;
  32793. }
  32794. function buildController( data ) {
  32795. var build = {
  32796. id: data.id
  32797. };
  32798. var geometry = library.geometries[ build.id ];
  32799. if ( data.skin !== undefined ) {
  32800. build.skin = buildSkin( data.skin );
  32801. // we enhance the 'sources' property of the corresponding geometry with our skin data
  32802. geometry.sources.skinIndices = build.skin.indices;
  32803. geometry.sources.skinWeights = build.skin.weights;
  32804. }
  32805. return build;
  32806. }
  32807. function buildSkin( data ) {
  32808. var BONE_LIMIT = 4;
  32809. var build = {
  32810. joints: [], // this must be an array to preserve the joint order
  32811. indices: {
  32812. array: [],
  32813. stride: BONE_LIMIT
  32814. },
  32815. weights: {
  32816. array: [],
  32817. stride: BONE_LIMIT
  32818. }
  32819. };
  32820. var sources = data.sources;
  32821. var vertexWeights = data.vertexWeights;
  32822. var vcount = vertexWeights.vcount;
  32823. var v = vertexWeights.v;
  32824. var jointOffset = vertexWeights.inputs.JOINT.offset;
  32825. var weightOffset = vertexWeights.inputs.WEIGHT.offset;
  32826. var jointSource = data.sources[ data.joints.inputs.JOINT ];
  32827. var inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
  32828. var weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
  32829. var stride = 0;
  32830. var i, j, l;
  32831. // procces skin data for each vertex
  32832. for ( i = 0, l = vcount.length; i < l; i ++ ) {
  32833. var jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
  32834. var vertexSkinData = [];
  32835. for ( j = 0; j < jointCount; j ++ ) {
  32836. var skinIndex = v[ stride + jointOffset ];
  32837. var weightId = v[ stride + weightOffset ];
  32838. var skinWeight = weights[ weightId ];
  32839. vertexSkinData.push( { index: skinIndex, weight: skinWeight } );
  32840. stride += 2;
  32841. }
  32842. // we sort the joints in descending order based on the weights.
  32843. // this ensures, we only procced the most important joints of the vertex
  32844. vertexSkinData.sort( descending );
  32845. // now we provide for each vertex a set of four index and weight values.
  32846. // the order of the skin data matches the order of vertices
  32847. for ( j = 0; j < BONE_LIMIT; j ++ ) {
  32848. var d = vertexSkinData[ j ];
  32849. if ( d !== undefined ) {
  32850. build.indices.array.push( d.index );
  32851. build.weights.array.push( d.weight );
  32852. } else {
  32853. build.indices.array.push( 0 );
  32854. build.weights.array.push( 0 );
  32855. }
  32856. }
  32857. }
  32858. // setup bind matrix
  32859. if ( data.bindShapeMatrix ) {
  32860. build.bindMatrix = new THREE.Matrix4().fromArray( data.bindShapeMatrix ).transpose();
  32861. } else {
  32862. build.bindMatrix = new THREE.Matrix4().identity();
  32863. }
  32864. // process bones and inverse bind matrix data
  32865. for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {
  32866. var name = jointSource.array[ i ];
  32867. var boneInverse = new THREE.Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
  32868. build.joints.push( { name: name, boneInverse: boneInverse } );
  32869. }
  32870. return build;
  32871. // array sort function
  32872. function descending( a, b ) {
  32873. return b.weight - a.weight;
  32874. }
  32875. }
  32876. function getController( id ) {
  32877. return getBuild( library.controllers[ id ], buildController );
  32878. }
  32879. // image
  32880. function parseImage( xml ) {
  32881. var data = {
  32882. init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent
  32883. };
  32884. library.images[ xml.getAttribute( 'id' ) ] = data;
  32885. }
  32886. function buildImage( data ) {
  32887. if ( data.build !== undefined ) return data.build;
  32888. return data.init_from;
  32889. }
  32890. function getImage( id ) {
  32891. var data = library.images[ id ];
  32892. if ( data !== undefined ) {
  32893. return getBuild( data, buildImage );
  32894. }
  32895. console.warn( 'THREE.ColladaLoader: Couldn\'t find image with ID:', id );
  32896. return null;
  32897. }
  32898. // effect
  32899. function parseEffect( xml ) {
  32900. var data = {};
  32901. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32902. var child = xml.childNodes[ i ];
  32903. if ( child.nodeType !== 1 ) continue;
  32904. switch ( child.nodeName ) {
  32905. case 'profile_COMMON':
  32906. data.profile = parseEffectProfileCOMMON( child );
  32907. break;
  32908. }
  32909. }
  32910. library.effects[ xml.getAttribute( 'id' ) ] = data;
  32911. }
  32912. function parseEffectProfileCOMMON( xml ) {
  32913. var data = {
  32914. surfaces: {},
  32915. samplers: {}
  32916. };
  32917. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32918. var child = xml.childNodes[ i ];
  32919. if ( child.nodeType !== 1 ) continue;
  32920. switch ( child.nodeName ) {
  32921. case 'newparam':
  32922. parseEffectNewparam( child, data );
  32923. break;
  32924. case 'technique':
  32925. data.technique = parseEffectTechnique( child );
  32926. break;
  32927. case 'extra':
  32928. data.extra = parseEffectExtra( child );
  32929. break;
  32930. }
  32931. }
  32932. return data;
  32933. }
  32934. function parseEffectNewparam( xml, data ) {
  32935. var sid = xml.getAttribute( 'sid' );
  32936. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32937. var child = xml.childNodes[ i ];
  32938. if ( child.nodeType !== 1 ) continue;
  32939. switch ( child.nodeName ) {
  32940. case 'surface':
  32941. data.surfaces[ sid ] = parseEffectSurface( child );
  32942. break;
  32943. case 'sampler2D':
  32944. data.samplers[ sid ] = parseEffectSampler( child );
  32945. break;
  32946. }
  32947. }
  32948. }
  32949. function parseEffectSurface( xml ) {
  32950. var data = {};
  32951. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32952. var child = xml.childNodes[ i ];
  32953. if ( child.nodeType !== 1 ) continue;
  32954. switch ( child.nodeName ) {
  32955. case 'init_from':
  32956. data.init_from = child.textContent;
  32957. break;
  32958. }
  32959. }
  32960. return data;
  32961. }
  32962. function parseEffectSampler( xml ) {
  32963. var data = {};
  32964. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32965. var child = xml.childNodes[ i ];
  32966. if ( child.nodeType !== 1 ) continue;
  32967. switch ( child.nodeName ) {
  32968. case 'source':
  32969. data.source = child.textContent;
  32970. break;
  32971. }
  32972. }
  32973. return data;
  32974. }
  32975. function parseEffectTechnique( xml ) {
  32976. var data = {};
  32977. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32978. var child = xml.childNodes[ i ];
  32979. if ( child.nodeType !== 1 ) continue;
  32980. switch ( child.nodeName ) {
  32981. case 'constant':
  32982. case 'lambert':
  32983. case 'blinn':
  32984. case 'phong':
  32985. data.type = child.nodeName;
  32986. data.parameters = parseEffectParameters( child );
  32987. break;
  32988. }
  32989. }
  32990. return data;
  32991. }
  32992. function parseEffectParameters( xml ) {
  32993. var data = {};
  32994. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32995. var child = xml.childNodes[ i ];
  32996. if ( child.nodeType !== 1 ) continue;
  32997. switch ( child.nodeName ) {
  32998. case 'emission':
  32999. case 'diffuse':
  33000. case 'specular':
  33001. case 'shininess':
  33002. case 'transparency':
  33003. data[ child.nodeName ] = parseEffectParameter( child );
  33004. break;
  33005. case 'transparent':
  33006. data[ child.nodeName ] = {
  33007. opaque: child.getAttribute( 'opaque' ),
  33008. data: parseEffectParameter( child )
  33009. };
  33010. break;
  33011. }
  33012. }
  33013. return data;
  33014. }
  33015. function parseEffectParameter( xml ) {
  33016. var data = {};
  33017. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33018. var child = xml.childNodes[ i ];
  33019. if ( child.nodeType !== 1 ) continue;
  33020. switch ( child.nodeName ) {
  33021. case 'color':
  33022. data[ child.nodeName ] = parseFloats( child.textContent );
  33023. break;
  33024. case 'float':
  33025. data[ child.nodeName ] = parseFloat( child.textContent );
  33026. break;
  33027. case 'texture':
  33028. data[ child.nodeName ] = { id: child.getAttribute( 'texture' ), extra: parseEffectParameterTexture( child ) };
  33029. break;
  33030. }
  33031. }
  33032. return data;
  33033. }
  33034. function parseEffectParameterTexture( xml ) {
  33035. var data = {
  33036. technique: {}
  33037. };
  33038. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33039. var child = xml.childNodes[ i ];
  33040. if ( child.nodeType !== 1 ) continue;
  33041. switch ( child.nodeName ) {
  33042. case 'extra':
  33043. parseEffectParameterTextureExtra( child, data );
  33044. break;
  33045. }
  33046. }
  33047. return data;
  33048. }
  33049. function parseEffectParameterTextureExtra( xml, data ) {
  33050. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33051. var child = xml.childNodes[ i ];
  33052. if ( child.nodeType !== 1 ) continue;
  33053. switch ( child.nodeName ) {
  33054. case 'technique':
  33055. parseEffectParameterTextureExtraTechnique( child, data );
  33056. break;
  33057. }
  33058. }
  33059. }
  33060. function parseEffectParameterTextureExtraTechnique( xml, data ) {
  33061. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33062. var child = xml.childNodes[ i ];
  33063. if ( child.nodeType !== 1 ) continue;
  33064. switch ( child.nodeName ) {
  33065. case 'repeatU':
  33066. case 'repeatV':
  33067. case 'offsetU':
  33068. case 'offsetV':
  33069. data.technique[ child.nodeName ] = parseFloat( child.textContent );
  33070. break;
  33071. case 'wrapU':
  33072. case 'wrapV':
  33073. // some files have values for wrapU/wrapV which become NaN via parseInt
  33074. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  33075. data.technique[ child.nodeName ] = 1;
  33076. } else if ( child.textContent.toUpperCase() === 'FALSE' ) {
  33077. data.technique[ child.nodeName ] = 0;
  33078. } else {
  33079. data.technique[ child.nodeName ] = parseInt( child.textContent );
  33080. }
  33081. break;
  33082. }
  33083. }
  33084. }
  33085. function parseEffectExtra( xml ) {
  33086. var data = {};
  33087. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33088. var child = xml.childNodes[ i ];
  33089. if ( child.nodeType !== 1 ) continue;
  33090. switch ( child.nodeName ) {
  33091. case 'technique':
  33092. data.technique = parseEffectExtraTechnique( child );
  33093. break;
  33094. }
  33095. }
  33096. return data;
  33097. }
  33098. function parseEffectExtraTechnique( xml ) {
  33099. var data = {};
  33100. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33101. var child = xml.childNodes[ i ];
  33102. if ( child.nodeType !== 1 ) continue;
  33103. switch ( child.nodeName ) {
  33104. case 'double_sided':
  33105. data[ child.nodeName ] = parseInt( child.textContent );
  33106. break;
  33107. }
  33108. }
  33109. return data;
  33110. }
  33111. function buildEffect( data ) {
  33112. return data;
  33113. }
  33114. function getEffect( id ) {
  33115. return getBuild( library.effects[ id ], buildEffect );
  33116. }
  33117. // material
  33118. function parseMaterial( xml ) {
  33119. var data = {
  33120. name: xml.getAttribute( 'name' )
  33121. };
  33122. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33123. var child = xml.childNodes[ i ];
  33124. if ( child.nodeType !== 1 ) continue;
  33125. switch ( child.nodeName ) {
  33126. case 'instance_effect':
  33127. data.url = parseId( child.getAttribute( 'url' ) );
  33128. break;
  33129. }
  33130. }
  33131. library.materials[ xml.getAttribute( 'id' ) ] = data;
  33132. }
  33133. function getTextureLoader( image ) {
  33134. var loader;
  33135. var extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/
  33136. extension = extension.toLowerCase();
  33137. switch ( extension ) {
  33138. case 'tga':
  33139. loader = tgaLoader;
  33140. break;
  33141. default:
  33142. loader = textureLoader;
  33143. }
  33144. return loader;
  33145. }
  33146. function buildMaterial( data ) {
  33147. var effect = getEffect( data.url );
  33148. var technique = effect.profile.technique;
  33149. var extra = effect.profile.extra;
  33150. var material;
  33151. switch ( technique.type ) {
  33152. case 'phong':
  33153. case 'blinn':
  33154. material = new THREE.MeshPhongMaterial();
  33155. break;
  33156. case 'lambert':
  33157. material = new THREE.MeshLambertMaterial();
  33158. break;
  33159. default:
  33160. material = new THREE.MeshBasicMaterial();
  33161. break;
  33162. }
  33163. material.name = data.name;
  33164. function getTexture( textureObject ) {
  33165. var sampler = effect.profile.samplers[ textureObject.id ];
  33166. var image = null;
  33167. // get image
  33168. if ( sampler !== undefined ) {
  33169. var surface = effect.profile.surfaces[ sampler.source ];
  33170. image = getImage( surface.init_from );
  33171. } else {
  33172. console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
  33173. image = getImage( textureObject.id );
  33174. }
  33175. // create texture if image is avaiable
  33176. if ( image !== null ) {
  33177. var loader = getTextureLoader( image );
  33178. if ( loader !== undefined ) {
  33179. var texture = loader.load( image );
  33180. var extra = textureObject.extra;
  33181. if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
  33182. var technique = extra.technique;
  33183. texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  33184. texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  33185. texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
  33186. texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
  33187. } else {
  33188. texture.wrapS = THREE.RepeatWrapping;
  33189. texture.wrapT = THREE.RepeatWrapping;
  33190. }
  33191. return texture;
  33192. } else {
  33193. console.warn( 'THREE.ColladaLoader: Loader for texture %s not found.', image );
  33194. return null;
  33195. }
  33196. } else {
  33197. console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );
  33198. return null;
  33199. }
  33200. }
  33201. var parameters = technique.parameters;
  33202. for ( var key in parameters ) {
  33203. var parameter = parameters[ key ];
  33204. switch ( key ) {
  33205. case 'diffuse':
  33206. if ( parameter.color ) material.color.fromArray( parameter.color );
  33207. if ( parameter.texture ) material.map = getTexture( parameter.texture );
  33208. break;
  33209. case 'specular':
  33210. if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
  33211. if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
  33212. break;
  33213. case 'shininess':
  33214. if ( parameter.float && material.shininess ) material.shininess = parameter.float;
  33215. break;
  33216. case 'emission':
  33217. if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
  33218. if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture );
  33219. break;
  33220. }
  33221. }
  33222. //
  33223. var transparent = parameters[ 'transparent' ];
  33224. var transparency = parameters[ 'transparency' ];
  33225. // <transparency> does not exist but <transparent>
  33226. if ( transparency === undefined && transparent ) {
  33227. transparency = {
  33228. float: 1
  33229. };
  33230. }
  33231. // <transparent> does not exist but <transparency>
  33232. if ( transparent === undefined && transparency ) {
  33233. transparent = {
  33234. opaque: 'A_ONE',
  33235. data: {
  33236. color: [ 1, 1, 1, 1 ]
  33237. } };
  33238. }
  33239. if ( transparent && transparency ) {
  33240. // handle case if a texture exists but no color
  33241. if ( transparent.data.texture ) {
  33242. // we do not set an alpha map (see #13792)
  33243. material.transparent = true;
  33244. } else {
  33245. var color = transparent.data.color;
  33246. switch ( transparent.opaque ) {
  33247. case 'A_ONE':
  33248. material.opacity = color[ 3 ] * transparency.float;
  33249. break;
  33250. case 'RGB_ZERO':
  33251. material.opacity = 1 - ( color[ 0 ] * transparency.float );
  33252. break;
  33253. case 'A_ZERO':
  33254. material.opacity = 1 - ( color[ 3 ] * transparency.float );
  33255. break;
  33256. case 'RGB_ONE':
  33257. material.opacity = color[ 0 ] * transparency.float;
  33258. break;
  33259. default:
  33260. console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
  33261. }
  33262. if ( material.opacity < 1 ) material.transparent = true;
  33263. }
  33264. }
  33265. //
  33266. if ( extra !== undefined && extra.technique !== undefined && extra.technique.double_sided === 1 ) {
  33267. material.side = THREE.DoubleSide;
  33268. }
  33269. return material;
  33270. }
  33271. function getMaterial( id ) {
  33272. return getBuild( library.materials[ id ], buildMaterial );
  33273. }
  33274. // camera
  33275. function parseCamera( xml ) {
  33276. var data = {
  33277. name: xml.getAttribute( 'name' )
  33278. };
  33279. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33280. var child = xml.childNodes[ i ];
  33281. if ( child.nodeType !== 1 ) continue;
  33282. switch ( child.nodeName ) {
  33283. case 'optics':
  33284. data.optics = parseCameraOptics( child );
  33285. break;
  33286. }
  33287. }
  33288. library.cameras[ xml.getAttribute( 'id' ) ] = data;
  33289. }
  33290. function parseCameraOptics( xml ) {
  33291. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33292. var child = xml.childNodes[ i ];
  33293. switch ( child.nodeName ) {
  33294. case 'technique_common':
  33295. return parseCameraTechnique( child );
  33296. }
  33297. }
  33298. return {};
  33299. }
  33300. function parseCameraTechnique( xml ) {
  33301. var data = {};
  33302. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33303. var child = xml.childNodes[ i ];
  33304. switch ( child.nodeName ) {
  33305. case 'perspective':
  33306. case 'orthographic':
  33307. data.technique = child.nodeName;
  33308. data.parameters = parseCameraParameters( child );
  33309. break;
  33310. }
  33311. }
  33312. return data;
  33313. }
  33314. function parseCameraParameters( xml ) {
  33315. var data = {};
  33316. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33317. var child = xml.childNodes[ i ];
  33318. switch ( child.nodeName ) {
  33319. case 'xfov':
  33320. case 'yfov':
  33321. case 'xmag':
  33322. case 'ymag':
  33323. case 'znear':
  33324. case 'zfar':
  33325. case 'aspect_ratio':
  33326. data[ child.nodeName ] = parseFloat( child.textContent );
  33327. break;
  33328. }
  33329. }
  33330. return data;
  33331. }
  33332. function buildCamera( data ) {
  33333. var camera;
  33334. switch ( data.optics.technique ) {
  33335. case 'perspective':
  33336. camera = new THREE.PerspectiveCamera(
  33337. data.optics.parameters.yfov,
  33338. data.optics.parameters.aspect_ratio,
  33339. data.optics.parameters.znear,
  33340. data.optics.parameters.zfar
  33341. );
  33342. break;
  33343. case 'orthographic':
  33344. var ymag = data.optics.parameters.ymag;
  33345. var xmag = data.optics.parameters.xmag;
  33346. var aspectRatio = data.optics.parameters.aspect_ratio;
  33347. xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag;
  33348. ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag;
  33349. xmag *= 0.5;
  33350. ymag *= 0.5;
  33351. camera = new THREE.OrthographicCamera(
  33352. - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  33353. data.optics.parameters.znear,
  33354. data.optics.parameters.zfar
  33355. );
  33356. break;
  33357. default:
  33358. camera = new THREE.PerspectiveCamera();
  33359. break;
  33360. }
  33361. camera.name = data.name;
  33362. return camera;
  33363. }
  33364. function getCamera( id ) {
  33365. var data = library.cameras[ id ];
  33366. if ( data !== undefined ) {
  33367. return getBuild( data, buildCamera );
  33368. }
  33369. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  33370. return null;
  33371. }
  33372. // light
  33373. function parseLight( xml ) {
  33374. var data = {};
  33375. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33376. var child = xml.childNodes[ i ];
  33377. if ( child.nodeType !== 1 ) continue;
  33378. switch ( child.nodeName ) {
  33379. case 'technique_common':
  33380. data = parseLightTechnique( child );
  33381. break;
  33382. }
  33383. }
  33384. library.lights[ xml.getAttribute( 'id' ) ] = data;
  33385. }
  33386. function parseLightTechnique( xml ) {
  33387. var data = {};
  33388. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33389. var child = xml.childNodes[ i ];
  33390. if ( child.nodeType !== 1 ) continue;
  33391. switch ( child.nodeName ) {
  33392. case 'directional':
  33393. case 'point':
  33394. case 'spot':
  33395. case 'ambient':
  33396. data.technique = child.nodeName;
  33397. data.parameters = parseLightParameters( child );
  33398. }
  33399. }
  33400. return data;
  33401. }
  33402. function parseLightParameters( xml ) {
  33403. var data = {};
  33404. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33405. var child = xml.childNodes[ i ];
  33406. if ( child.nodeType !== 1 ) continue;
  33407. switch ( child.nodeName ) {
  33408. case 'color':
  33409. var array = parseFloats( child.textContent );
  33410. data.color = new THREE.Color().fromArray( array );
  33411. break;
  33412. case 'falloff_angle':
  33413. data.falloffAngle = parseFloat( child.textContent );
  33414. break;
  33415. case 'quadratic_attenuation':
  33416. var f = parseFloat( child.textContent );
  33417. data.distance = f ? Math.sqrt( 1 / f ) : 0;
  33418. break;
  33419. }
  33420. }
  33421. return data;
  33422. }
  33423. function buildLight( data ) {
  33424. var light;
  33425. switch ( data.technique ) {
  33426. case 'directional':
  33427. light = new THREE.DirectionalLight();
  33428. break;
  33429. case 'point':
  33430. light = new THREE.PointLight();
  33431. break;
  33432. case 'spot':
  33433. light = new THREE.SpotLight();
  33434. break;
  33435. case 'ambient':
  33436. light = new THREE.AmbientLight();
  33437. break;
  33438. }
  33439. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  33440. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  33441. return light;
  33442. }
  33443. function getLight( id ) {
  33444. var data = library.lights[ id ];
  33445. if ( data !== undefined ) {
  33446. return getBuild( data, buildLight );
  33447. }
  33448. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  33449. return null;
  33450. }
  33451. // geometry
  33452. function parseGeometry( xml ) {
  33453. var data = {
  33454. name: xml.getAttribute( 'name' ),
  33455. sources: {},
  33456. vertices: {},
  33457. primitives: []
  33458. };
  33459. var mesh = getElementsByTagName( xml, 'mesh' )[ 0 ];
  33460. // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
  33461. if ( mesh === undefined ) return;
  33462. for ( var i = 0; i < mesh.childNodes.length; i ++ ) {
  33463. var child = mesh.childNodes[ i ];
  33464. if ( child.nodeType !== 1 ) continue;
  33465. var id = child.getAttribute( 'id' );
  33466. switch ( child.nodeName ) {
  33467. case 'source':
  33468. data.sources[ id ] = parseSource( child );
  33469. break;
  33470. case 'vertices':
  33471. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  33472. data.vertices = parseGeometryVertices( child );
  33473. break;
  33474. case 'polygons':
  33475. console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
  33476. break;
  33477. case 'lines':
  33478. case 'linestrips':
  33479. case 'polylist':
  33480. case 'triangles':
  33481. data.primitives.push( parseGeometryPrimitive( child ) );
  33482. break;
  33483. default:
  33484. console.log( child );
  33485. }
  33486. }
  33487. library.geometries[ xml.getAttribute( 'id' ) ] = data;
  33488. }
  33489. function parseSource( xml ) {
  33490. var data = {
  33491. array: [],
  33492. stride: 3
  33493. };
  33494. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33495. var child = xml.childNodes[ i ];
  33496. if ( child.nodeType !== 1 ) continue;
  33497. switch ( child.nodeName ) {
  33498. case 'float_array':
  33499. data.array = parseFloats( child.textContent );
  33500. break;
  33501. case 'Name_array':
  33502. data.array = parseStrings( child.textContent );
  33503. break;
  33504. case 'technique_common':
  33505. var accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
  33506. if ( accessor !== undefined ) {
  33507. data.stride = parseInt( accessor.getAttribute( 'stride' ) );
  33508. }
  33509. break;
  33510. }
  33511. }
  33512. return data;
  33513. }
  33514. function parseGeometryVertices( xml ) {
  33515. var data = {};
  33516. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33517. var child = xml.childNodes[ i ];
  33518. if ( child.nodeType !== 1 ) continue;
  33519. data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
  33520. }
  33521. return data;
  33522. }
  33523. function parseGeometryPrimitive( xml ) {
  33524. var primitive = {
  33525. type: xml.nodeName,
  33526. material: xml.getAttribute( 'material' ),
  33527. count: parseInt( xml.getAttribute( 'count' ) ),
  33528. inputs: {},
  33529. stride: 0,
  33530. hasUV: false
  33531. };
  33532. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33533. var child = xml.childNodes[ i ];
  33534. if ( child.nodeType !== 1 ) continue;
  33535. switch ( child.nodeName ) {
  33536. case 'input':
  33537. var id = parseId( child.getAttribute( 'source' ) );
  33538. var semantic = child.getAttribute( 'semantic' );
  33539. var offset = parseInt( child.getAttribute( 'offset' ) );
  33540. primitive.inputs[ semantic ] = { id: id, offset: offset };
  33541. primitive.stride = Math.max( primitive.stride, offset + 1 );
  33542. if ( semantic === 'TEXCOORD' ) primitive.hasUV = true;
  33543. break;
  33544. case 'vcount':
  33545. primitive.vcount = parseInts( child.textContent );
  33546. break;
  33547. case 'p':
  33548. primitive.p = parseInts( child.textContent );
  33549. break;
  33550. }
  33551. }
  33552. return primitive;
  33553. }
  33554. function groupPrimitives( primitives ) {
  33555. var build = {};
  33556. for ( var i = 0; i < primitives.length; i ++ ) {
  33557. var primitive = primitives[ i ];
  33558. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  33559. build[ primitive.type ].push( primitive );
  33560. }
  33561. return build;
  33562. }
  33563. function checkUVCoordinates( primitives ) {
  33564. var count = 0;
  33565. for ( var i = 0, l = primitives.length; i < l; i ++ ) {
  33566. var primitive = primitives[ i ];
  33567. if ( primitive.hasUV === true ) {
  33568. count ++;
  33569. }
  33570. }
  33571. if ( count > 0 && count < primitives.length ) {
  33572. primitives.uvsNeedsFix = true;
  33573. }
  33574. }
  33575. function buildGeometry( data ) {
  33576. var build = {};
  33577. var sources = data.sources;
  33578. var vertices = data.vertices;
  33579. var primitives = data.primitives;
  33580. if ( primitives.length === 0 ) return {};
  33581. // our goal is to create one buffer geometry for a single type of primitives
  33582. // first, we group all primitives by their type
  33583. var groupedPrimitives = groupPrimitives( primitives );
  33584. for ( var type in groupedPrimitives ) {
  33585. var primitiveType = groupedPrimitives[ type ];
  33586. // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  33587. checkUVCoordinates( primitiveType );
  33588. // third, create a buffer geometry for each type of primitives
  33589. build[ type ] = buildGeometryType( primitiveType, sources, vertices );
  33590. }
  33591. return build;
  33592. }
  33593. function buildGeometryType( primitives, sources, vertices ) {
  33594. var build = {};
  33595. var position = { array: [], stride: 0 };
  33596. var normal = { array: [], stride: 0 };
  33597. var uv = { array: [], stride: 0 };
  33598. var color = { array: [], stride: 0 };
  33599. var skinIndex = { array: [], stride: 4 };
  33600. var skinWeight = { array: [], stride: 4 };
  33601. var geometry = new THREE.BufferGeometry();
  33602. var materialKeys = [];
  33603. var start = 0;
  33604. for ( var p = 0; p < primitives.length; p ++ ) {
  33605. var primitive = primitives[ p ];
  33606. var inputs = primitive.inputs;
  33607. // groups
  33608. var count = 0;
  33609. switch ( primitive.type ) {
  33610. case 'lines':
  33611. case 'linestrips':
  33612. count = primitive.count * 2;
  33613. break;
  33614. case 'triangles':
  33615. count = primitive.count * 3;
  33616. break;
  33617. case 'polylist':
  33618. for ( var g = 0; g < primitive.count; g ++ ) {
  33619. var vc = primitive.vcount[ g ];
  33620. switch ( vc ) {
  33621. case 3:
  33622. count += 3; // single triangle
  33623. break;
  33624. case 4:
  33625. count += 6; // quad, subdivided into two triangles
  33626. break;
  33627. default:
  33628. count += ( vc - 2 ) * 3; // polylist with more than four vertices
  33629. break;
  33630. }
  33631. }
  33632. break;
  33633. default:
  33634. console.warn( 'THREE.ColladaLoader: Unknow primitive type:', primitive.type );
  33635. }
  33636. geometry.addGroup( start, count, p );
  33637. start += count;
  33638. // material
  33639. if ( primitive.material ) {
  33640. materialKeys.push( primitive.material );
  33641. }
  33642. // geometry data
  33643. for ( var name in inputs ) {
  33644. var input = inputs[ name ];
  33645. switch ( name ) {
  33646. case 'VERTEX':
  33647. for ( var key in vertices ) {
  33648. var id = vertices[ key ];
  33649. switch ( key ) {
  33650. case 'POSITION':
  33651. var prevLength = position.array.length;
  33652. buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  33653. position.stride = sources[ id ].stride;
  33654. if ( sources.skinWeights && sources.skinIndices ) {
  33655. buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  33656. buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  33657. }
  33658. // see #3803
  33659. if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
  33660. var count = ( position.array.length - prevLength ) / position.stride;
  33661. for ( var i = 0; i < count; i ++ ) {
  33662. // fill missing uv coordinates
  33663. uv.array.push( 0, 0 );
  33664. }
  33665. }
  33666. break;
  33667. case 'NORMAL':
  33668. buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  33669. normal.stride = sources[ id ].stride;
  33670. break;
  33671. case 'COLOR':
  33672. buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  33673. color.stride = sources[ id ].stride;
  33674. break;
  33675. case 'TEXCOORD':
  33676. buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  33677. uv.stride = sources[ id ].stride;
  33678. break;
  33679. default:
  33680. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  33681. }
  33682. }
  33683. break;
  33684. case 'NORMAL':
  33685. buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  33686. normal.stride = sources[ input.id ].stride;
  33687. break;
  33688. case 'COLOR':
  33689. buildGeometryData( primitive, sources[ input.id ], input.offset, color.array );
  33690. color.stride = sources[ input.id ].stride;
  33691. break;
  33692. case 'TEXCOORD':
  33693. buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  33694. uv.stride = sources[ input.id ].stride;
  33695. break;
  33696. }
  33697. }
  33698. }
  33699. // build geometry
  33700. if ( position.array.length > 0 ) geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( position.array, position.stride ) );
  33701. if ( normal.array.length > 0 ) geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normal.array, normal.stride ) );
  33702. if ( color.array.length > 0 ) geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( color.array, color.stride ) );
  33703. if ( uv.array.length > 0 ) geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( uv.array, uv.stride ) );
  33704. if ( skinIndex.array.length > 0 ) geometry.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  33705. if ( skinWeight.array.length > 0 ) geometry.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  33706. build.data = geometry;
  33707. build.type = primitives[ 0 ].type;
  33708. build.materialKeys = materialKeys;
  33709. return build;
  33710. }
  33711. function buildGeometryData( primitive, source, offset, array ) {
  33712. var indices = primitive.p;
  33713. var stride = primitive.stride;
  33714. var vcount = primitive.vcount;
  33715. function pushVector( i ) {
  33716. var index = indices[ i + offset ] * sourceStride;
  33717. var length = index + sourceStride;
  33718. for ( ; index < length; index ++ ) {
  33719. array.push( sourceArray[ index ] );
  33720. }
  33721. }
  33722. var sourceArray = source.array;
  33723. var sourceStride = source.stride;
  33724. if ( primitive.vcount !== undefined ) {
  33725. var index = 0;
  33726. for ( var i = 0, l = vcount.length; i < l; i ++ ) {
  33727. var count = vcount[ i ];
  33728. if ( count === 4 ) {
  33729. var a = index + stride * 0;
  33730. var b = index + stride * 1;
  33731. var c = index + stride * 2;
  33732. var d = index + stride * 3;
  33733. pushVector( a ); pushVector( b ); pushVector( d );
  33734. pushVector( b ); pushVector( c ); pushVector( d );
  33735. } else if ( count === 3 ) {
  33736. var a = index + stride * 0;
  33737. var b = index + stride * 1;
  33738. var c = index + stride * 2;
  33739. pushVector( a ); pushVector( b ); pushVector( c );
  33740. } else if ( count > 4 ) {
  33741. for ( var k = 1, kl = ( count - 2 ); k <= kl; k ++ ) {
  33742. var a = index + stride * 0;
  33743. var b = index + stride * k;
  33744. var c = index + stride * ( k + 1 );
  33745. pushVector( a ); pushVector( b ); pushVector( c );
  33746. }
  33747. }
  33748. index += stride * count;
  33749. }
  33750. } else {
  33751. for ( var i = 0, l = indices.length; i < l; i += stride ) {
  33752. pushVector( i );
  33753. }
  33754. }
  33755. }
  33756. function getGeometry( id ) {
  33757. return getBuild( library.geometries[ id ], buildGeometry );
  33758. }
  33759. // kinematics
  33760. function parseKinematicsModel( xml ) {
  33761. var data = {
  33762. name: xml.getAttribute( 'name' ) || '',
  33763. joints: {},
  33764. links: []
  33765. };
  33766. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33767. var child = xml.childNodes[ i ];
  33768. if ( child.nodeType !== 1 ) continue;
  33769. switch ( child.nodeName ) {
  33770. case 'technique_common':
  33771. parseKinematicsTechniqueCommon( child, data );
  33772. break;
  33773. }
  33774. }
  33775. library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
  33776. }
  33777. function buildKinematicsModel( data ) {
  33778. if ( data.build !== undefined ) return data.build;
  33779. return data;
  33780. }
  33781. function getKinematicsModel( id ) {
  33782. return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
  33783. }
  33784. function parseKinematicsTechniqueCommon( xml, data ) {
  33785. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33786. var child = xml.childNodes[ i ];
  33787. if ( child.nodeType !== 1 ) continue;
  33788. switch ( child.nodeName ) {
  33789. case 'joint':
  33790. data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
  33791. break;
  33792. case 'link':
  33793. data.links.push( parseKinematicsLink( child ) );
  33794. break;
  33795. }
  33796. }
  33797. }
  33798. function parseKinematicsJoint( xml ) {
  33799. var data;
  33800. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33801. var child = xml.childNodes[ i ];
  33802. if ( child.nodeType !== 1 ) continue;
  33803. switch ( child.nodeName ) {
  33804. case 'prismatic':
  33805. case 'revolute':
  33806. data = parseKinematicsJointParameter( child );
  33807. break;
  33808. }
  33809. }
  33810. return data;
  33811. }
  33812. function parseKinematicsJointParameter( xml, data ) {
  33813. var data = {
  33814. sid: xml.getAttribute( 'sid' ),
  33815. name: xml.getAttribute( 'name' ) || '',
  33816. axis: new THREE.Vector3(),
  33817. limits: {
  33818. min: 0,
  33819. max: 0
  33820. },
  33821. type: xml.nodeName,
  33822. static: false,
  33823. zeroPosition: 0,
  33824. middlePosition: 0
  33825. };
  33826. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33827. var child = xml.childNodes[ i ];
  33828. if ( child.nodeType !== 1 ) continue;
  33829. switch ( child.nodeName ) {
  33830. case 'axis':
  33831. var array = parseFloats( child.textContent );
  33832. data.axis.fromArray( array );
  33833. break;
  33834. case 'limits':
  33835. var max = child.getElementsByTagName( 'max' )[ 0 ];
  33836. var min = child.getElementsByTagName( 'min' )[ 0 ];
  33837. data.limits.max = parseFloat( max.textContent );
  33838. data.limits.min = parseFloat( min.textContent );
  33839. break;
  33840. }
  33841. }
  33842. // if min is equal to or greater than max, consider the joint static
  33843. if ( data.limits.min >= data.limits.max ) {
  33844. data.static = true;
  33845. }
  33846. // calculate middle position
  33847. data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
  33848. return data;
  33849. }
  33850. function parseKinematicsLink( xml ) {
  33851. var data = {
  33852. sid: xml.getAttribute( 'sid' ),
  33853. name: xml.getAttribute( 'name' ) || '',
  33854. attachments: [],
  33855. transforms: []
  33856. };
  33857. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33858. var child = xml.childNodes[ i ];
  33859. if ( child.nodeType !== 1 ) continue;
  33860. switch ( child.nodeName ) {
  33861. case 'attachment_full':
  33862. data.attachments.push( parseKinematicsAttachment( child ) );
  33863. break;
  33864. case 'matrix':
  33865. case 'translate':
  33866. case 'rotate':
  33867. data.transforms.push( parseKinematicsTransform( child ) );
  33868. break;
  33869. }
  33870. }
  33871. return data;
  33872. }
  33873. function parseKinematicsAttachment( xml ) {
  33874. var data = {
  33875. joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
  33876. transforms: [],
  33877. links: []
  33878. };
  33879. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33880. var child = xml.childNodes[ i ];
  33881. if ( child.nodeType !== 1 ) continue;
  33882. switch ( child.nodeName ) {
  33883. case 'link':
  33884. data.links.push( parseKinematicsLink( child ) );
  33885. break;
  33886. case 'matrix':
  33887. case 'translate':
  33888. case 'rotate':
  33889. data.transforms.push( parseKinematicsTransform( child ) );
  33890. break;
  33891. }
  33892. }
  33893. return data;
  33894. }
  33895. function parseKinematicsTransform( xml ) {
  33896. var data = {
  33897. type: xml.nodeName
  33898. };
  33899. var array = parseFloats( xml.textContent );
  33900. switch ( data.type ) {
  33901. case 'matrix':
  33902. data.obj = new THREE.Matrix4();
  33903. data.obj.fromArray( array ).transpose();
  33904. break;
  33905. case 'translate':
  33906. data.obj = new THREE.Vector3();
  33907. data.obj.fromArray( array );
  33908. break;
  33909. case 'rotate':
  33910. data.obj = new THREE.Vector3();
  33911. data.obj.fromArray( array );
  33912. data.angle = THREE.Math.degToRad( array[ 3 ] );
  33913. break;
  33914. }
  33915. return data;
  33916. }
  33917. // physics
  33918. function parsePhysicsModel( xml ) {
  33919. var data = {
  33920. name: xml.getAttribute( 'name' ) || '',
  33921. rigidBodies: {}
  33922. };
  33923. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33924. var child = xml.childNodes[ i ];
  33925. if ( child.nodeType !== 1 ) continue;
  33926. switch ( child.nodeName ) {
  33927. case 'rigid_body':
  33928. data.rigidBodies[ child.getAttribute( 'name' ) ] = {};
  33929. parsePhysicsRigidBody( child, data.rigidBodies[ child.getAttribute( 'name' ) ] );
  33930. break;
  33931. }
  33932. }
  33933. library.physicsModels[ xml.getAttribute( 'id' ) ] = data;
  33934. }
  33935. function parsePhysicsRigidBody( xml, data ) {
  33936. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33937. var child = xml.childNodes[ i ];
  33938. if ( child.nodeType !== 1 ) continue;
  33939. switch ( child.nodeName ) {
  33940. case 'technique_common':
  33941. parsePhysicsTechniqueCommon( child, data );
  33942. break;
  33943. }
  33944. }
  33945. }
  33946. function parsePhysicsTechniqueCommon( xml, data ) {
  33947. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33948. var child = xml.childNodes[ i ];
  33949. if ( child.nodeType !== 1 ) continue;
  33950. switch ( child.nodeName ) {
  33951. case 'inertia':
  33952. data.inertia = parseFloats( child.textContent );
  33953. break;
  33954. case 'mass':
  33955. data.mass = parseFloats( child.textContent )[0];
  33956. break;
  33957. }
  33958. }
  33959. }
  33960. // scene
  33961. function parseKinematicsScene( xml ) {
  33962. var data = {
  33963. bindJointAxis: []
  33964. };
  33965. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33966. var child = xml.childNodes[ i ];
  33967. if ( child.nodeType !== 1 ) continue;
  33968. switch ( child.nodeName ) {
  33969. case 'bind_joint_axis':
  33970. data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
  33971. break;
  33972. }
  33973. }
  33974. library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
  33975. }
  33976. function parseKinematicsBindJointAxis( xml ) {
  33977. var data = {
  33978. target: xml.getAttribute( 'target' ).split( '/' ).pop()
  33979. };
  33980. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33981. var child = xml.childNodes[ i ];
  33982. if ( child.nodeType !== 1 ) continue;
  33983. switch ( child.nodeName ) {
  33984. case 'axis':
  33985. var param = child.getElementsByTagName( 'param' )[ 0 ];
  33986. data.axis = param.textContent;
  33987. var tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
  33988. data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 );
  33989. break;
  33990. }
  33991. }
  33992. return data;
  33993. }
  33994. function buildKinematicsScene( data ) {
  33995. if ( data.build !== undefined ) return data.build;
  33996. return data;
  33997. }
  33998. function getKinematicsScene( id ) {
  33999. return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
  34000. }
  34001. function setupKinematics() {
  34002. var kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
  34003. var kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
  34004. var visualSceneId = Object.keys( library.visualScenes )[ 0 ];
  34005. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  34006. var kinematicsModel = getKinematicsModel( kinematicsModelId );
  34007. var kinematicsScene = getKinematicsScene( kinematicsSceneId );
  34008. var visualScene = getVisualScene( visualSceneId );
  34009. var bindJointAxis = kinematicsScene.bindJointAxis;
  34010. var jointMap = {};
  34011. for ( var i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  34012. var axis = bindJointAxis[ i ];
  34013. // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  34014. var targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  34015. if ( targetElement ) {
  34016. // get the parent of the transfrom element
  34017. var parentVisualElement = targetElement.parentElement;
  34018. // connect the joint of the kinematics model with the element in the visual scene
  34019. connect( axis.jointIndex, parentVisualElement );
  34020. }
  34021. }
  34022. function connect( jointIndex, visualElement ) {
  34023. var visualElementName = visualElement.getAttribute( 'name' );
  34024. var joint = kinematicsModel.joints[ jointIndex ];
  34025. visualScene.traverse( function ( object ) {
  34026. if ( object.name === visualElementName ) {
  34027. jointMap[ jointIndex ] = {
  34028. object: object,
  34029. transforms: buildTransformList( visualElement ),
  34030. joint: joint,
  34031. position: joint.zeroPosition
  34032. };
  34033. }
  34034. } );
  34035. }
  34036. var m0 = new THREE.Matrix4();
  34037. kinematics = {
  34038. joints: kinematicsModel && kinematicsModel.joints,
  34039. getJointValue: function ( jointIndex ) {
  34040. var jointData = jointMap[ jointIndex ];
  34041. if ( jointData ) {
  34042. return jointData.position;
  34043. } else {
  34044. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  34045. }
  34046. },
  34047. setJointValue: function ( jointIndex, value ) {
  34048. var jointData = jointMap[ jointIndex ];
  34049. if ( jointData ) {
  34050. var joint = jointData.joint;
  34051. if ( value > joint.limits.max || value < joint.limits.min ) {
  34052. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  34053. } else if ( joint.static ) {
  34054. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  34055. } else {
  34056. var object = jointData.object;
  34057. var axis = joint.axis;
  34058. var transforms = jointData.transforms;
  34059. matrix.identity();
  34060. // each update, we have to apply all transforms in the correct order
  34061. for ( var i = 0; i < transforms.length; i ++ ) {
  34062. var transform = transforms[ i ];
  34063. // if there is a connection of the transform node with a joint, apply the joint value
  34064. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  34065. switch ( joint.type ) {
  34066. case 'revolute':
  34067. matrix.multiply( m0.makeRotationAxis( axis, THREE.Math.degToRad( value ) ) );
  34068. break;
  34069. case 'prismatic':
  34070. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  34071. break;
  34072. default:
  34073. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  34074. break;
  34075. }
  34076. } else {
  34077. switch ( transform.type ) {
  34078. case 'matrix':
  34079. matrix.multiply( transform.obj );
  34080. break;
  34081. case 'translate':
  34082. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  34083. break;
  34084. case 'scale':
  34085. matrix.scale( transform.obj );
  34086. break;
  34087. case 'rotate':
  34088. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  34089. break;
  34090. }
  34091. }
  34092. }
  34093. object.matrix.copy( matrix );
  34094. object.matrix.decompose( object.position, object.quaternion, object.scale );
  34095. jointMap[ jointIndex ].position = value;
  34096. }
  34097. } else {
  34098. console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
  34099. }
  34100. }
  34101. };
  34102. }
  34103. function buildTransformList( node ) {
  34104. var transforms = [];
  34105. var xml = collada.querySelector( '[id="' + node.id + '"]' );
  34106. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34107. var child = xml.childNodes[ i ];
  34108. if ( child.nodeType !== 1 ) continue;
  34109. switch ( child.nodeName ) {
  34110. case 'matrix':
  34111. var array = parseFloats( child.textContent );
  34112. var matrix = new THREE.Matrix4().fromArray( array ).transpose();
  34113. transforms.push( {
  34114. sid: child.getAttribute( 'sid' ),
  34115. type: child.nodeName,
  34116. obj: matrix
  34117. } );
  34118. break;
  34119. case 'translate':
  34120. case 'scale':
  34121. var array = parseFloats( child.textContent );
  34122. var vector = new THREE.Vector3().fromArray( array );
  34123. transforms.push( {
  34124. sid: child.getAttribute( 'sid' ),
  34125. type: child.nodeName,
  34126. obj: vector
  34127. } );
  34128. break;
  34129. case 'rotate':
  34130. var array = parseFloats( child.textContent );
  34131. var vector = new THREE.Vector3().fromArray( array );
  34132. var angle = THREE.Math.degToRad( array[ 3 ] );
  34133. transforms.push( {
  34134. sid: child.getAttribute( 'sid' ),
  34135. type: child.nodeName,
  34136. obj: vector,
  34137. angle: angle
  34138. } );
  34139. break;
  34140. }
  34141. }
  34142. return transforms;
  34143. }
  34144. // nodes
  34145. function prepareNodes( xml ) {
  34146. var elements = xml.getElementsByTagName( 'node' );
  34147. // ensure all node elements have id attributes
  34148. for ( var i = 0; i < elements.length; i ++ ) {
  34149. var element = elements[ i ];
  34150. if ( element.hasAttribute( 'id' ) === false ) {
  34151. element.setAttribute( 'id', generateId() );
  34152. }
  34153. }
  34154. }
  34155. var matrix = new THREE.Matrix4();
  34156. var vector = new THREE.Vector3();
  34157. function parseNode( xml ) {
  34158. var data = {
  34159. name: xml.getAttribute( 'name' ) || '',
  34160. type: xml.getAttribute( 'type' ),
  34161. id: xml.getAttribute( 'id' ),
  34162. sid: xml.getAttribute( 'sid' ),
  34163. matrix: new THREE.Matrix4(),
  34164. nodes: [],
  34165. instanceCameras: [],
  34166. instanceControllers: [],
  34167. instanceLights: [],
  34168. instanceGeometries: [],
  34169. instanceNodes: [],
  34170. transforms: {}
  34171. };
  34172. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34173. var child = xml.childNodes[ i ];
  34174. if ( child.nodeType !== 1 ) continue;
  34175. switch ( child.nodeName ) {
  34176. case 'node':
  34177. data.nodes.push( child.getAttribute( 'id' ) );
  34178. parseNode( child );
  34179. break;
  34180. case 'instance_camera':
  34181. data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
  34182. break;
  34183. case 'instance_controller':
  34184. data.instanceControllers.push( parseNodeInstance( child ) );
  34185. break;
  34186. case 'instance_light':
  34187. data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
  34188. break;
  34189. case 'instance_geometry':
  34190. data.instanceGeometries.push( parseNodeInstance( child ) );
  34191. break;
  34192. case 'instance_node':
  34193. data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
  34194. break;
  34195. case 'matrix':
  34196. var array = parseFloats( child.textContent );
  34197. data.matrix.multiply( matrix.fromArray( array ).transpose() );
  34198. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34199. break;
  34200. case 'translate':
  34201. var array = parseFloats( child.textContent );
  34202. vector.fromArray( array );
  34203. data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
  34204. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34205. break;
  34206. case 'rotate':
  34207. var array = parseFloats( child.textContent );
  34208. var angle = THREE.Math.degToRad( array[ 3 ] );
  34209. data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
  34210. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34211. break;
  34212. case 'scale':
  34213. var array = parseFloats( child.textContent );
  34214. data.matrix.scale( vector.fromArray( array ) );
  34215. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34216. break;
  34217. case 'extra':
  34218. break;
  34219. default:
  34220. console.log( child );
  34221. }
  34222. }
  34223. if ( hasNode( data.id ) ) {
  34224. console.warn( 'THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id );
  34225. } else {
  34226. library.nodes[ data.id ] = data;
  34227. }
  34228. return data;
  34229. }
  34230. function parseNodeInstance( xml ) {
  34231. var data = {
  34232. id: parseId( xml.getAttribute( 'url' ) ),
  34233. materials: {},
  34234. skeletons: []
  34235. };
  34236. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34237. var child = xml.childNodes[ i ];
  34238. switch ( child.nodeName ) {
  34239. case 'bind_material':
  34240. var instances = child.getElementsByTagName( 'instance_material' );
  34241. for ( var j = 0; j < instances.length; j ++ ) {
  34242. var instance = instances[ j ];
  34243. var symbol = instance.getAttribute( 'symbol' );
  34244. var target = instance.getAttribute( 'target' );
  34245. data.materials[ symbol ] = parseId( target );
  34246. }
  34247. break;
  34248. case 'skeleton':
  34249. data.skeletons.push( parseId( child.textContent ) );
  34250. break;
  34251. default:
  34252. break;
  34253. }
  34254. }
  34255. return data;
  34256. }
  34257. function buildSkeleton( skeletons, joints ) {
  34258. var boneData = [];
  34259. var sortedBoneData = [];
  34260. var i, j, data;
  34261. // a skeleton can have multiple root bones. collada expresses this
  34262. // situtation with multiple "skeleton" tags per controller instance
  34263. for ( i = 0; i < skeletons.length; i ++ ) {
  34264. var skeleton = skeletons[ i ];
  34265. var root;
  34266. if ( hasNode( skeleton ) ) {
  34267. root = getNode( skeleton );
  34268. buildBoneHierarchy( root, joints, boneData );
  34269. } else if ( hasVisualScene( skeleton ) ) {
  34270. // handle case where the skeleton refers to the visual scene (#13335)
  34271. var visualScene = library.visualScenes[ skeleton ];
  34272. var children = visualScene.children;
  34273. for ( var j = 0; j < children.length; j ++ ) {
  34274. var child = children[ j ];
  34275. if ( child.type === 'JOINT' ) {
  34276. var root = getNode( child.id );
  34277. buildBoneHierarchy( root, joints, boneData );
  34278. }
  34279. }
  34280. } else {
  34281. console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
  34282. }
  34283. }
  34284. // sort bone data (the order is defined in the corresponding controller)
  34285. for ( i = 0; i < joints.length; i ++ ) {
  34286. for ( j = 0; j < boneData.length; j ++ ) {
  34287. data = boneData[ j ];
  34288. if ( data.bone.name === joints[ i ].name ) {
  34289. sortedBoneData[ i ] = data;
  34290. data.processed = true;
  34291. break;
  34292. }
  34293. }
  34294. }
  34295. // add unprocessed bone data at the end of the list
  34296. for ( i = 0; i < boneData.length; i ++ ) {
  34297. data = boneData[ i ];
  34298. if ( data.processed === false ) {
  34299. sortedBoneData.push( data );
  34300. data.processed = true;
  34301. }
  34302. }
  34303. // setup arrays for skeleton creation
  34304. var bones = [];
  34305. var boneInverses = [];
  34306. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  34307. data = sortedBoneData[ i ];
  34308. bones.push( data.bone );
  34309. boneInverses.push( data.boneInverse );
  34310. }
  34311. return new THREE.Skeleton( bones, boneInverses );
  34312. }
  34313. function buildBoneHierarchy( root, joints, boneData ) {
  34314. // setup bone data from visual scene
  34315. root.traverse( function ( object ) {
  34316. if ( object.isBone === true ) {
  34317. var boneInverse;
  34318. // retrieve the boneInverse from the controller data
  34319. for ( var i = 0; i < joints.length; i ++ ) {
  34320. var joint = joints[ i ];
  34321. if ( joint.name === object.name ) {
  34322. boneInverse = joint.boneInverse;
  34323. break;
  34324. }
  34325. }
  34326. if ( boneInverse === undefined ) {
  34327. // Unfortunately, there can be joints in the visual scene that are not part of the
  34328. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  34329. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  34330. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  34331. // ensure a correct animation of the model.
  34332. boneInverse = new THREE.Matrix4();
  34333. }
  34334. boneData.push( { bone: object, boneInverse: boneInverse, processed: false } );
  34335. }
  34336. } );
  34337. }
  34338. function buildNode( data ) {
  34339. var objects = [];
  34340. var matrix = data.matrix;
  34341. var nodes = data.nodes;
  34342. var type = data.type;
  34343. var instanceCameras = data.instanceCameras;
  34344. var instanceControllers = data.instanceControllers;
  34345. var instanceLights = data.instanceLights;
  34346. var instanceGeometries = data.instanceGeometries;
  34347. var instanceNodes = data.instanceNodes;
  34348. // nodes
  34349. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  34350. objects.push( getNode( nodes[ i ] ) );
  34351. }
  34352. // instance cameras
  34353. for ( var i = 0, l = instanceCameras.length; i < l; i ++ ) {
  34354. var instanceCamera = getCamera( instanceCameras[ i ] );
  34355. if ( instanceCamera !== null ) {
  34356. objects.push( instanceCamera.clone() );
  34357. }
  34358. }
  34359. // instance controllers
  34360. for ( var i = 0, l = instanceControllers.length; i < l; i ++ ) {
  34361. var instance = instanceControllers[ i ];
  34362. var controller = getController( instance.id );
  34363. var geometries = getGeometry( controller.id );
  34364. var newObjects = buildObjects( geometries, instance.materials );
  34365. var skeletons = instance.skeletons;
  34366. var joints = controller.skin.joints;
  34367. var skeleton = buildSkeleton( skeletons, joints );
  34368. for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
  34369. var object = newObjects[ j ];
  34370. if ( object.isSkinnedMesh ) {
  34371. object.bind( skeleton, controller.skin.bindMatrix );
  34372. object.normalizeSkinWeights();
  34373. }
  34374. objects.push( object );
  34375. }
  34376. }
  34377. // instance lights
  34378. for ( var i = 0, l = instanceLights.length; i < l; i ++ ) {
  34379. var instanceLight = getLight( instanceLights[ i ] );
  34380. if ( instanceLight !== null ) {
  34381. objects.push( instanceLight.clone() );
  34382. }
  34383. }
  34384. // instance geometries
  34385. for ( var i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  34386. var instance = instanceGeometries[ i ];
  34387. // a single geometry instance in collada can lead to multiple object3Ds.
  34388. // this is the case when primitives are combined like triangles and lines
  34389. var geometries = getGeometry( instance.id );
  34390. var newObjects = buildObjects( geometries, instance.materials );
  34391. for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
  34392. objects.push( newObjects[ j ] );
  34393. }
  34394. }
  34395. // instance nodes
  34396. for ( var i = 0, l = instanceNodes.length; i < l; i ++ ) {
  34397. objects.push( getNode( instanceNodes[ i ] ).clone() );
  34398. }
  34399. var object;
  34400. if ( nodes.length === 0 && objects.length === 1 ) {
  34401. object = objects[ 0 ];
  34402. } else {
  34403. object = ( type === 'JOINT' ) ? new THREE.Bone() : new THREE.Group();
  34404. for ( var i = 0; i < objects.length; i ++ ) {
  34405. object.add( objects[ i ] );
  34406. }
  34407. }
  34408. if ( object.name === '' ) {
  34409. object.name = ( type === 'JOINT' ) ? data.sid : data.name;
  34410. }
  34411. object.matrix.copy( matrix );
  34412. object.matrix.decompose( object.position, object.quaternion, object.scale );
  34413. return object;
  34414. }
  34415. var fallbackMaterial = new THREE.MeshBasicMaterial( { color: 0xff00ff } );
  34416. function resolveMaterialBinding( keys, instanceMaterials ) {
  34417. var materials = [];
  34418. for ( var i = 0, l = keys.length; i < l; i ++ ) {
  34419. var id = instanceMaterials[ keys[ i ] ];
  34420. if ( id === undefined ) {
  34421. console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
  34422. materials.push( fallbackMaterial );
  34423. } else {
  34424. materials.push( getMaterial( id ) );
  34425. }
  34426. }
  34427. return materials;
  34428. }
  34429. function buildObjects( geometries, instanceMaterials ) {
  34430. var objects = [];
  34431. for ( var type in geometries ) {
  34432. var geometry = geometries[ type ];
  34433. var materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials );
  34434. // handle case if no materials are defined
  34435. if ( materials.length === 0 ) {
  34436. if ( type === 'lines' || type === 'linestrips' ) {
  34437. materials.push( new THREE.LineBasicMaterial() );
  34438. } else {
  34439. materials.push( new THREE.MeshPhongMaterial() );
  34440. }
  34441. }
  34442. // regard skinning
  34443. var skinning = ( geometry.data.attributes.skinIndex !== undefined );
  34444. if ( skinning ) {
  34445. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  34446. materials[ i ].skinning = true;
  34447. }
  34448. }
  34449. // choose between a single or multi materials (material array)
  34450. var material = ( materials.length === 1 ) ? materials[ 0 ] : materials;
  34451. // now create a specific 3D object
  34452. var object;
  34453. switch ( type ) {
  34454. case 'lines':
  34455. object = new THREE.LineSegments( geometry.data, material );
  34456. break;
  34457. case 'linestrips':
  34458. object = new THREE.Line( geometry.data, material );
  34459. break;
  34460. case 'triangles':
  34461. case 'polylist':
  34462. if ( skinning ) {
  34463. object = new THREE.SkinnedMesh( geometry.data, material );
  34464. } else {
  34465. object = new THREE.Mesh( geometry.data, material );
  34466. }
  34467. break;
  34468. }
  34469. objects.push( object );
  34470. }
  34471. return objects;
  34472. }
  34473. function hasNode( id ) {
  34474. return library.nodes[ id ] !== undefined;
  34475. }
  34476. function getNode( id ) {
  34477. return getBuild( library.nodes[ id ], buildNode );
  34478. }
  34479. // visual scenes
  34480. function parseVisualScene( xml ) {
  34481. var data = {
  34482. name: xml.getAttribute( 'name' ),
  34483. children: []
  34484. };
  34485. prepareNodes( xml );
  34486. var elements = getElementsByTagName( xml, 'node' );
  34487. for ( var i = 0; i < elements.length; i ++ ) {
  34488. data.children.push( parseNode( elements[ i ] ) );
  34489. }
  34490. library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
  34491. }
  34492. function buildVisualScene( data ) {
  34493. var group = new THREE.Group();
  34494. group.name = data.name;
  34495. var children = data.children;
  34496. for ( var i = 0; i < children.length; i ++ ) {
  34497. var child = children[ i ];
  34498. group.add( getNode( child.id ) );
  34499. }
  34500. return group;
  34501. }
  34502. function hasVisualScene( id ) {
  34503. return library.visualScenes[ id ] !== undefined;
  34504. }
  34505. function getVisualScene( id ) {
  34506. return getBuild( library.visualScenes[ id ], buildVisualScene );
  34507. }
  34508. // scenes
  34509. function parseScene( xml ) {
  34510. var instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  34511. return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
  34512. }
  34513. function setupAnimations() {
  34514. var clips = library.clips;
  34515. if ( isEmpty( clips ) === true ) {
  34516. if ( isEmpty( library.animations ) === false ) {
  34517. // if there are animations but no clips, we create a default clip for playback
  34518. var tracks = [];
  34519. for ( var id in library.animations ) {
  34520. var animationTracks = getAnimation( id );
  34521. for ( var i = 0, l = animationTracks.length; i < l; i ++ ) {
  34522. tracks.push( animationTracks[ i ] );
  34523. }
  34524. }
  34525. animations.push( new THREE.AnimationClip( 'default', - 1, tracks ) );
  34526. }
  34527. } else {
  34528. for ( var id in clips ) {
  34529. animations.push( getAnimationClip( id ) );
  34530. }
  34531. }
  34532. }
  34533. if ( text.length === 0 ) {
  34534. return { scene: new THREE.Scene() };
  34535. }
  34536. var xml = new DOMParser().parseFromString( text, 'application/xml' );
  34537. var collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
  34538. // metadata
  34539. var version = collada.getAttribute( 'version' );
  34540. console.log( 'THREE.ColladaLoader: File version', version );
  34541. var asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
  34542. var textureLoader = new THREE.TextureLoader( this.manager );
  34543. textureLoader.setPath( path ).setCrossOrigin( this.crossOrigin );
  34544. var tgaLoader;
  34545. if ( THREE.TGALoader ) {
  34546. tgaLoader = new THREE.TGALoader( this.manager );
  34547. tgaLoader.setPath( path );
  34548. }
  34549. //
  34550. var animations = [];
  34551. var kinematics = {};
  34552. var count = 0;
  34553. //
  34554. var library = {
  34555. animations: {},
  34556. clips: {},
  34557. controllers: {},
  34558. images: {},
  34559. effects: {},
  34560. materials: {},
  34561. cameras: {},
  34562. lights: {},
  34563. geometries: {},
  34564. nodes: {},
  34565. visualScenes: {},
  34566. kinematicsModels: {},
  34567. physicsModels: {},
  34568. kinematicsScenes: {}
  34569. };
  34570. parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
  34571. parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
  34572. parseLibrary( collada, 'library_controllers', 'controller', parseController );
  34573. parseLibrary( collada, 'library_images', 'image', parseImage );
  34574. parseLibrary( collada, 'library_effects', 'effect', parseEffect );
  34575. parseLibrary( collada, 'library_materials', 'material', parseMaterial );
  34576. parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
  34577. parseLibrary( collada, 'library_lights', 'light', parseLight );
  34578. parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
  34579. parseLibrary( collada, 'library_nodes', 'node', parseNode );
  34580. parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
  34581. parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
  34582. parseLibrary( collada, 'library_physics_models', 'physics_model', parsePhysicsModel );
  34583. parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
  34584. buildLibrary( library.animations, buildAnimation );
  34585. buildLibrary( library.clips, buildAnimationClip );
  34586. buildLibrary( library.controllers, buildController );
  34587. buildLibrary( library.images, buildImage );
  34588. buildLibrary( library.effects, buildEffect );
  34589. buildLibrary( library.materials, buildMaterial );
  34590. buildLibrary( library.cameras, buildCamera );
  34591. buildLibrary( library.lights, buildLight );
  34592. buildLibrary( library.geometries, buildGeometry );
  34593. buildLibrary( library.visualScenes, buildVisualScene );
  34594. setupAnimations();
  34595. setupKinematics();
  34596. var scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
  34597. if ( asset.upAxis === 'Z_UP' ) {
  34598. scene.quaternion.setFromEuler( new THREE.Euler( - Math.PI / 2, 0, 0 ) );
  34599. }
  34600. scene.scale.multiplyScalar( asset.unit );
  34601. return {
  34602. animations: animations,
  34603. kinematics: kinematics,
  34604. library: library,
  34605. scene: scene
  34606. };
  34607. }
  34608. };
  34609. },{}],42:[function(_dereq_,module,exports){
  34610. /**
  34611. * @author Rich Tibbett / https://github.com/richtr
  34612. * @author mrdoob / http://mrdoob.com/
  34613. * @author Tony Parisi / http://www.tonyparisi.com/
  34614. * @author Takahiro / https://github.com/takahirox
  34615. * @author Don McCurdy / https://www.donmccurdy.com
  34616. */
  34617. THREE.GLTFLoader = ( function () {
  34618. function GLTFLoader( manager ) {
  34619. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  34620. this.dracoLoader = null;
  34621. }
  34622. GLTFLoader.prototype = {
  34623. constructor: GLTFLoader,
  34624. crossOrigin: 'anonymous',
  34625. load: function ( url, onLoad, onProgress, onError ) {
  34626. var scope = this;
  34627. var path = this.path !== undefined ? this.path : THREE.LoaderUtils.extractUrlBase( url );
  34628. var loader = new THREE.FileLoader( scope.manager );
  34629. loader.setResponseType( 'arraybuffer' );
  34630. loader.load( url, function ( data ) {
  34631. try {
  34632. scope.parse( data, path, onLoad, onError );
  34633. } catch ( e ) {
  34634. if ( onError !== undefined ) {
  34635. onError( e );
  34636. } else {
  34637. throw e;
  34638. }
  34639. }
  34640. }, onProgress, onError );
  34641. },
  34642. setCrossOrigin: function ( value ) {
  34643. this.crossOrigin = value;
  34644. return this;
  34645. },
  34646. setPath: function ( value ) {
  34647. this.path = value;
  34648. return this;
  34649. },
  34650. setDRACOLoader: function ( dracoLoader ) {
  34651. this.dracoLoader = dracoLoader;
  34652. return this;
  34653. },
  34654. parse: function ( data, path, onLoad, onError ) {
  34655. var content;
  34656. var extensions = {};
  34657. if ( typeof data === 'string' ) {
  34658. content = data;
  34659. } else {
  34660. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  34661. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  34662. try {
  34663. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  34664. } catch ( error ) {
  34665. if ( onError ) onError( error );
  34666. return;
  34667. }
  34668. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  34669. } else {
  34670. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  34671. }
  34672. }
  34673. var json = JSON.parse( content );
  34674. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  34675. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  34676. return;
  34677. }
  34678. if ( json.extensionsUsed ) {
  34679. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  34680. var extensionName = json.extensionsUsed[ i ];
  34681. var extensionsRequired = json.extensionsRequired || [];
  34682. switch ( extensionName ) {
  34683. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  34684. extensions[ extensionName ] = new GLTFLightsExtension( json );
  34685. break;
  34686. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  34687. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension( json );
  34688. break;
  34689. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  34690. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  34691. break;
  34692. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  34693. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  34694. break;
  34695. case EXTENSIONS.MSFT_TEXTURE_DDS:
  34696. extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension();
  34697. break;
  34698. default:
  34699. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  34700. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  34701. }
  34702. }
  34703. }
  34704. }
  34705. var parser = new GLTFParser( json, extensions, {
  34706. path: path || this.path || '',
  34707. crossOrigin: this.crossOrigin,
  34708. manager: this.manager
  34709. } );
  34710. parser.parse( function ( scene, scenes, cameras, animations, json ) {
  34711. var glTF = {
  34712. scene: scene,
  34713. scenes: scenes,
  34714. cameras: cameras,
  34715. animations: animations,
  34716. asset: json.asset,
  34717. parser: parser,
  34718. userData: {}
  34719. };
  34720. addUnknownExtensionsToUserData( extensions, glTF, json );
  34721. onLoad( glTF );
  34722. }, onError );
  34723. }
  34724. };
  34725. /* GLTFREGISTRY */
  34726. function GLTFRegistry() {
  34727. var objects = {};
  34728. return {
  34729. get: function ( key ) {
  34730. return objects[ key ];
  34731. },
  34732. add: function ( key, object ) {
  34733. objects[ key ] = object;
  34734. },
  34735. remove: function ( key ) {
  34736. delete objects[ key ];
  34737. },
  34738. removeAll: function () {
  34739. objects = {};
  34740. }
  34741. };
  34742. }
  34743. /*********************************/
  34744. /********** EXTENSIONS ***********/
  34745. /*********************************/
  34746. var EXTENSIONS = {
  34747. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  34748. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  34749. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  34750. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  34751. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  34752. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  34753. };
  34754. /**
  34755. * DDS Texture Extension
  34756. *
  34757. * Specification:
  34758. * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  34759. *
  34760. */
  34761. function GLTFTextureDDSExtension() {
  34762. if ( ! THREE.DDSLoader ) {
  34763. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  34764. }
  34765. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  34766. this.ddsLoader = new THREE.DDSLoader();
  34767. }
  34768. /**
  34769. * Lights Extension
  34770. *
  34771. * Specification: PENDING
  34772. */
  34773. function GLTFLightsExtension( json ) {
  34774. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  34775. this.lights = [];
  34776. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  34777. var lightDefs = extension.lights || [];
  34778. for ( var i = 0; i < lightDefs.length; i ++ ) {
  34779. var lightDef = lightDefs[ i ];
  34780. var lightNode;
  34781. var color = new THREE.Color( 0xffffff );
  34782. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  34783. var range = lightDef.range !== undefined ? lightDef.range : 0;
  34784. switch ( lightDef.type ) {
  34785. case 'directional':
  34786. lightNode = new THREE.DirectionalLight( color );
  34787. lightNode.target.position.set( 0, 0, 1 );
  34788. lightNode.add( lightNode.target );
  34789. break;
  34790. case 'point':
  34791. lightNode = new THREE.PointLight( color );
  34792. lightNode.distance = range;
  34793. break;
  34794. case 'spot':
  34795. lightNode = new THREE.SpotLight( color );
  34796. lightNode.distance = range;
  34797. // Handle spotlight properties.
  34798. lightDef.spot = lightDef.spot || {};
  34799. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  34800. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  34801. lightNode.angle = lightDef.spot.outerConeAngle;
  34802. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  34803. lightNode.target.position.set( 0, 0, 1 );
  34804. lightNode.add( lightNode.target );
  34805. break;
  34806. default:
  34807. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  34808. }
  34809. lightNode.decay = 2;
  34810. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  34811. lightNode.name = lightDef.name || ( 'light_' + i );
  34812. this.lights.push( lightNode );
  34813. }
  34814. }
  34815. /**
  34816. * Unlit Materials Extension (pending)
  34817. *
  34818. * PR: https://github.com/KhronosGroup/glTF/pull/1163
  34819. */
  34820. function GLTFMaterialsUnlitExtension( json ) {
  34821. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  34822. }
  34823. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function ( material ) {
  34824. return THREE.MeshBasicMaterial;
  34825. };
  34826. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, material, parser ) {
  34827. var pending = [];
  34828. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  34829. materialParams.opacity = 1.0;
  34830. var metallicRoughness = material.pbrMetallicRoughness;
  34831. if ( metallicRoughness ) {
  34832. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  34833. var array = metallicRoughness.baseColorFactor;
  34834. materialParams.color.fromArray( array );
  34835. materialParams.opacity = array[ 3 ];
  34836. }
  34837. if ( metallicRoughness.baseColorTexture !== undefined ) {
  34838. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  34839. }
  34840. }
  34841. return Promise.all( pending );
  34842. };
  34843. /* BINARY EXTENSION */
  34844. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  34845. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  34846. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  34847. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  34848. function GLTFBinaryExtension( data ) {
  34849. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  34850. this.content = null;
  34851. this.body = null;
  34852. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  34853. this.header = {
  34854. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  34855. version: headerView.getUint32( 4, true ),
  34856. length: headerView.getUint32( 8, true )
  34857. };
  34858. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  34859. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  34860. } else if ( this.header.version < 2.0 ) {
  34861. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  34862. }
  34863. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  34864. var chunkIndex = 0;
  34865. while ( chunkIndex < chunkView.byteLength ) {
  34866. var chunkLength = chunkView.getUint32( chunkIndex, true );
  34867. chunkIndex += 4;
  34868. var chunkType = chunkView.getUint32( chunkIndex, true );
  34869. chunkIndex += 4;
  34870. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  34871. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  34872. this.content = THREE.LoaderUtils.decodeText( contentArray );
  34873. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  34874. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  34875. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  34876. }
  34877. // Clients must ignore chunks with unknown types.
  34878. chunkIndex += chunkLength;
  34879. }
  34880. if ( this.content === null ) {
  34881. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  34882. }
  34883. }
  34884. /**
  34885. * DRACO Mesh Compression Extension
  34886. *
  34887. * Specification: https://github.com/KhronosGroup/glTF/pull/874
  34888. */
  34889. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  34890. if ( ! dracoLoader ) {
  34891. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  34892. }
  34893. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  34894. this.json = json;
  34895. this.dracoLoader = dracoLoader;
  34896. }
  34897. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  34898. var json = this.json;
  34899. var dracoLoader = this.dracoLoader;
  34900. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  34901. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  34902. var threeAttributeMap = {};
  34903. var attributeNormalizedMap = {};
  34904. var attributeTypeMap = {};
  34905. for ( var attributeName in gltfAttributeMap ) {
  34906. if ( ! ( attributeName in ATTRIBUTES ) ) continue;
  34907. threeAttributeMap[ ATTRIBUTES[ attributeName ] ] = gltfAttributeMap[ attributeName ];
  34908. }
  34909. for ( attributeName in primitive.attributes ) {
  34910. if ( ATTRIBUTES[ attributeName ] !== undefined && gltfAttributeMap[ attributeName ] !== undefined ) {
  34911. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  34912. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  34913. attributeTypeMap[ ATTRIBUTES[ attributeName ] ] = componentType;
  34914. attributeNormalizedMap[ ATTRIBUTES[ attributeName ] ] = accessorDef.normalized === true;
  34915. }
  34916. }
  34917. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  34918. return new Promise( function ( resolve ) {
  34919. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  34920. for ( var attributeName in geometry.attributes ) {
  34921. var attribute = geometry.attributes[ attributeName ];
  34922. var normalized = attributeNormalizedMap[ attributeName ];
  34923. if ( normalized !== undefined ) attribute.normalized = normalized;
  34924. }
  34925. resolve( geometry );
  34926. }, threeAttributeMap, attributeTypeMap );
  34927. } );
  34928. } );
  34929. };
  34930. /**
  34931. * Specular-Glossiness Extension
  34932. *
  34933. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  34934. */
  34935. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  34936. return {
  34937. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  34938. specularGlossinessParams: [
  34939. 'color',
  34940. 'map',
  34941. 'lightMap',
  34942. 'lightMapIntensity',
  34943. 'aoMap',
  34944. 'aoMapIntensity',
  34945. 'emissive',
  34946. 'emissiveIntensity',
  34947. 'emissiveMap',
  34948. 'bumpMap',
  34949. 'bumpScale',
  34950. 'normalMap',
  34951. 'displacementMap',
  34952. 'displacementScale',
  34953. 'displacementBias',
  34954. 'specularMap',
  34955. 'specular',
  34956. 'glossinessMap',
  34957. 'glossiness',
  34958. 'alphaMap',
  34959. 'envMap',
  34960. 'envMapIntensity',
  34961. 'refractionRatio',
  34962. ],
  34963. getMaterialType: function () {
  34964. return THREE.ShaderMaterial;
  34965. },
  34966. extendParams: function ( params, material, parser ) {
  34967. var pbrSpecularGlossiness = material.extensions[ this.name ];
  34968. var shader = THREE.ShaderLib[ 'standard' ];
  34969. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  34970. var specularMapParsFragmentChunk = [
  34971. '#ifdef USE_SPECULARMAP',
  34972. ' uniform sampler2D specularMap;',
  34973. '#endif'
  34974. ].join( '\n' );
  34975. var glossinessMapParsFragmentChunk = [
  34976. '#ifdef USE_GLOSSINESSMAP',
  34977. ' uniform sampler2D glossinessMap;',
  34978. '#endif'
  34979. ].join( '\n' );
  34980. var specularMapFragmentChunk = [
  34981. 'vec3 specularFactor = specular;',
  34982. '#ifdef USE_SPECULARMAP',
  34983. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  34984. ' texelSpecular = sRGBToLinear( texelSpecular );',
  34985. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34986. ' specularFactor *= texelSpecular.rgb;',
  34987. '#endif'
  34988. ].join( '\n' );
  34989. var glossinessMapFragmentChunk = [
  34990. 'float glossinessFactor = glossiness;',
  34991. '#ifdef USE_GLOSSINESSMAP',
  34992. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  34993. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34994. ' glossinessFactor *= texelGlossiness.a;',
  34995. '#endif'
  34996. ].join( '\n' );
  34997. var lightPhysicalFragmentChunk = [
  34998. 'PhysicalMaterial material;',
  34999. 'material.diffuseColor = diffuseColor.rgb;',
  35000. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  35001. 'material.specularColor = specularFactor.rgb;',
  35002. ].join( '\n' );
  35003. var fragmentShader = shader.fragmentShader
  35004. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  35005. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  35006. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  35007. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  35008. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  35009. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  35010. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  35011. delete uniforms.roughness;
  35012. delete uniforms.metalness;
  35013. delete uniforms.roughnessMap;
  35014. delete uniforms.metalnessMap;
  35015. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  35016. uniforms.glossiness = { value: 0.5 };
  35017. uniforms.specularMap = { value: null };
  35018. uniforms.glossinessMap = { value: null };
  35019. params.vertexShader = shader.vertexShader;
  35020. params.fragmentShader = fragmentShader;
  35021. params.uniforms = uniforms;
  35022. params.defines = { 'STANDARD': '' };
  35023. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  35024. params.opacity = 1.0;
  35025. var pending = [];
  35026. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  35027. var array = pbrSpecularGlossiness.diffuseFactor;
  35028. params.color.fromArray( array );
  35029. params.opacity = array[ 3 ];
  35030. }
  35031. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  35032. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture.index ) );
  35033. }
  35034. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  35035. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  35036. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  35037. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  35038. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  35039. }
  35040. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  35041. var specGlossIndex = pbrSpecularGlossiness.specularGlossinessTexture.index;
  35042. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossIndex ) );
  35043. pending.push( parser.assignTexture( params, 'specularMap', specGlossIndex ) );
  35044. }
  35045. return Promise.all( pending );
  35046. },
  35047. createMaterial: function ( params ) {
  35048. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  35049. var material = new THREE.ShaderMaterial( {
  35050. defines: params.defines,
  35051. vertexShader: params.vertexShader,
  35052. fragmentShader: params.fragmentShader,
  35053. uniforms: params.uniforms,
  35054. fog: true,
  35055. lights: true,
  35056. opacity: params.opacity,
  35057. transparent: params.transparent
  35058. } );
  35059. material.isGLTFSpecularGlossinessMaterial = true;
  35060. material.color = params.color;
  35061. material.map = params.map === undefined ? null : params.map;
  35062. material.lightMap = null;
  35063. material.lightMapIntensity = 1.0;
  35064. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  35065. material.aoMapIntensity = 1.0;
  35066. material.emissive = params.emissive;
  35067. material.emissiveIntensity = 1.0;
  35068. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  35069. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  35070. material.bumpScale = 1;
  35071. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  35072. if ( params.normalScale ) material.normalScale = params.normalScale;
  35073. material.displacementMap = null;
  35074. material.displacementScale = 1;
  35075. material.displacementBias = 0;
  35076. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  35077. material.specular = params.specular;
  35078. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  35079. material.glossiness = params.glossiness;
  35080. material.alphaMap = null;
  35081. material.envMap = params.envMap === undefined ? null : params.envMap;
  35082. material.envMapIntensity = 1.0;
  35083. material.refractionRatio = 0.98;
  35084. material.extensions.derivatives = true;
  35085. return material;
  35086. },
  35087. /**
  35088. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  35089. * copy only properties it knows about or inherits, and misses many properties that would
  35090. * normally be defined by MeshStandardMaterial.
  35091. *
  35092. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  35093. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  35094. * AND also updating `.onBeforeRender` on the parent mesh.
  35095. *
  35096. * @param {THREE.ShaderMaterial} source
  35097. * @return {THREE.ShaderMaterial}
  35098. */
  35099. cloneMaterial: function ( source ) {
  35100. var target = source.clone();
  35101. target.isGLTFSpecularGlossinessMaterial = true;
  35102. var params = this.specularGlossinessParams;
  35103. for ( var i = 0, il = params.length; i < il; i ++ ) {
  35104. target[ params[ i ] ] = source[ params[ i ] ];
  35105. }
  35106. return target;
  35107. },
  35108. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  35109. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  35110. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  35111. return;
  35112. }
  35113. var uniforms = material.uniforms;
  35114. var defines = material.defines;
  35115. uniforms.opacity.value = material.opacity;
  35116. uniforms.diffuse.value.copy( material.color );
  35117. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  35118. uniforms.map.value = material.map;
  35119. uniforms.specularMap.value = material.specularMap;
  35120. uniforms.alphaMap.value = material.alphaMap;
  35121. uniforms.lightMap.value = material.lightMap;
  35122. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  35123. uniforms.aoMap.value = material.aoMap;
  35124. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  35125. // uv repeat and offset setting priorities
  35126. // 1. color map
  35127. // 2. specular map
  35128. // 3. normal map
  35129. // 4. bump map
  35130. // 5. alpha map
  35131. // 6. emissive map
  35132. var uvScaleMap;
  35133. if ( material.map ) {
  35134. uvScaleMap = material.map;
  35135. } else if ( material.specularMap ) {
  35136. uvScaleMap = material.specularMap;
  35137. } else if ( material.displacementMap ) {
  35138. uvScaleMap = material.displacementMap;
  35139. } else if ( material.normalMap ) {
  35140. uvScaleMap = material.normalMap;
  35141. } else if ( material.bumpMap ) {
  35142. uvScaleMap = material.bumpMap;
  35143. } else if ( material.glossinessMap ) {
  35144. uvScaleMap = material.glossinessMap;
  35145. } else if ( material.alphaMap ) {
  35146. uvScaleMap = material.alphaMap;
  35147. } else if ( material.emissiveMap ) {
  35148. uvScaleMap = material.emissiveMap;
  35149. }
  35150. if ( uvScaleMap !== undefined ) {
  35151. // backwards compatibility
  35152. if ( uvScaleMap.isWebGLRenderTarget ) {
  35153. uvScaleMap = uvScaleMap.texture;
  35154. }
  35155. if ( uvScaleMap.matrixAutoUpdate === true ) {
  35156. uvScaleMap.updateMatrix();
  35157. }
  35158. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  35159. }
  35160. uniforms.envMap.value = material.envMap;
  35161. uniforms.envMapIntensity.value = material.envMapIntensity;
  35162. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? - 1 : 1;
  35163. uniforms.refractionRatio.value = material.refractionRatio;
  35164. uniforms.specular.value.copy( material.specular );
  35165. uniforms.glossiness.value = material.glossiness;
  35166. uniforms.glossinessMap.value = material.glossinessMap;
  35167. uniforms.emissiveMap.value = material.emissiveMap;
  35168. uniforms.bumpMap.value = material.bumpMap;
  35169. uniforms.normalMap.value = material.normalMap;
  35170. uniforms.displacementMap.value = material.displacementMap;
  35171. uniforms.displacementScale.value = material.displacementScale;
  35172. uniforms.displacementBias.value = material.displacementBias;
  35173. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  35174. defines.USE_GLOSSINESSMAP = '';
  35175. // set USE_ROUGHNESSMAP to enable vUv
  35176. defines.USE_ROUGHNESSMAP = '';
  35177. }
  35178. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  35179. delete defines.USE_GLOSSINESSMAP;
  35180. delete defines.USE_ROUGHNESSMAP;
  35181. }
  35182. }
  35183. };
  35184. }
  35185. /*********************************/
  35186. /********** INTERPOLATION ********/
  35187. /*********************************/
  35188. // Spline Interpolation
  35189. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  35190. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  35191. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  35192. }
  35193. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  35194. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  35195. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  35196. var result = this.resultBuffer;
  35197. var values = this.sampleValues;
  35198. var stride = this.valueSize;
  35199. var stride2 = stride * 2;
  35200. var stride3 = stride * 3;
  35201. var td = t1 - t0;
  35202. var p = ( t - t0 ) / td;
  35203. var pp = p * p;
  35204. var ppp = pp * p;
  35205. var offset1 = i1 * stride3;
  35206. var offset0 = offset1 - stride3;
  35207. var s0 = 2 * ppp - 3 * pp + 1;
  35208. var s1 = ppp - 2 * pp + p;
  35209. var s2 = - 2 * ppp + 3 * pp;
  35210. var s3 = ppp - pp;
  35211. // Layout of keyframe output values for CUBICSPLINE animations:
  35212. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  35213. for ( var i = 0; i !== stride; i ++ ) {
  35214. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  35215. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  35216. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  35217. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  35218. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  35219. }
  35220. return result;
  35221. };
  35222. /*********************************/
  35223. /********** INTERNALS ************/
  35224. /*********************************/
  35225. /* CONSTANTS */
  35226. var WEBGL_CONSTANTS = {
  35227. FLOAT: 5126,
  35228. //FLOAT_MAT2: 35674,
  35229. FLOAT_MAT3: 35675,
  35230. FLOAT_MAT4: 35676,
  35231. FLOAT_VEC2: 35664,
  35232. FLOAT_VEC3: 35665,
  35233. FLOAT_VEC4: 35666,
  35234. LINEAR: 9729,
  35235. REPEAT: 10497,
  35236. SAMPLER_2D: 35678,
  35237. POINTS: 0,
  35238. LINES: 1,
  35239. LINE_LOOP: 2,
  35240. LINE_STRIP: 3,
  35241. TRIANGLES: 4,
  35242. TRIANGLE_STRIP: 5,
  35243. TRIANGLE_FAN: 6,
  35244. UNSIGNED_BYTE: 5121,
  35245. UNSIGNED_SHORT: 5123
  35246. };
  35247. var WEBGL_TYPE = {
  35248. 5126: Number,
  35249. //35674: THREE.Matrix2,
  35250. 35675: THREE.Matrix3,
  35251. 35676: THREE.Matrix4,
  35252. 35664: THREE.Vector2,
  35253. 35665: THREE.Vector3,
  35254. 35666: THREE.Vector4,
  35255. 35678: THREE.Texture
  35256. };
  35257. var WEBGL_COMPONENT_TYPES = {
  35258. 5120: Int8Array,
  35259. 5121: Uint8Array,
  35260. 5122: Int16Array,
  35261. 5123: Uint16Array,
  35262. 5125: Uint32Array,
  35263. 5126: Float32Array
  35264. };
  35265. var WEBGL_FILTERS = {
  35266. 9728: THREE.NearestFilter,
  35267. 9729: THREE.LinearFilter,
  35268. 9984: THREE.NearestMipMapNearestFilter,
  35269. 9985: THREE.LinearMipMapNearestFilter,
  35270. 9986: THREE.NearestMipMapLinearFilter,
  35271. 9987: THREE.LinearMipMapLinearFilter
  35272. };
  35273. var WEBGL_WRAPPINGS = {
  35274. 33071: THREE.ClampToEdgeWrapping,
  35275. 33648: THREE.MirroredRepeatWrapping,
  35276. 10497: THREE.RepeatWrapping
  35277. };
  35278. var WEBGL_SIDES = {
  35279. 1028: THREE.BackSide, // Culling front
  35280. 1029: THREE.FrontSide // Culling back
  35281. //1032: THREE.NoSide // Culling front and back, what to do?
  35282. };
  35283. var WEBGL_DEPTH_FUNCS = {
  35284. 512: THREE.NeverDepth,
  35285. 513: THREE.LessDepth,
  35286. 514: THREE.EqualDepth,
  35287. 515: THREE.LessEqualDepth,
  35288. 516: THREE.GreaterEqualDepth,
  35289. 517: THREE.NotEqualDepth,
  35290. 518: THREE.GreaterEqualDepth,
  35291. 519: THREE.AlwaysDepth
  35292. };
  35293. var WEBGL_BLEND_EQUATIONS = {
  35294. 32774: THREE.AddEquation,
  35295. 32778: THREE.SubtractEquation,
  35296. 32779: THREE.ReverseSubtractEquation
  35297. };
  35298. var WEBGL_BLEND_FUNCS = {
  35299. 0: THREE.ZeroFactor,
  35300. 1: THREE.OneFactor,
  35301. 768: THREE.SrcColorFactor,
  35302. 769: THREE.OneMinusSrcColorFactor,
  35303. 770: THREE.SrcAlphaFactor,
  35304. 771: THREE.OneMinusSrcAlphaFactor,
  35305. 772: THREE.DstAlphaFactor,
  35306. 773: THREE.OneMinusDstAlphaFactor,
  35307. 774: THREE.DstColorFactor,
  35308. 775: THREE.OneMinusDstColorFactor,
  35309. 776: THREE.SrcAlphaSaturateFactor
  35310. // The followings are not supported by Three.js yet
  35311. //32769: CONSTANT_COLOR,
  35312. //32770: ONE_MINUS_CONSTANT_COLOR,
  35313. //32771: CONSTANT_ALPHA,
  35314. //32772: ONE_MINUS_CONSTANT_COLOR
  35315. };
  35316. var WEBGL_TYPE_SIZES = {
  35317. 'SCALAR': 1,
  35318. 'VEC2': 2,
  35319. 'VEC3': 3,
  35320. 'VEC4': 4,
  35321. 'MAT2': 4,
  35322. 'MAT3': 9,
  35323. 'MAT4': 16
  35324. };
  35325. var ATTRIBUTES = {
  35326. POSITION: 'position',
  35327. NORMAL: 'normal',
  35328. TEXCOORD_0: 'uv',
  35329. TEXCOORD0: 'uv', // deprecated
  35330. TEXCOORD: 'uv', // deprecated
  35331. TEXCOORD_1: 'uv2',
  35332. COLOR_0: 'color',
  35333. COLOR0: 'color', // deprecated
  35334. COLOR: 'color', // deprecated
  35335. WEIGHTS_0: 'skinWeight',
  35336. WEIGHT: 'skinWeight', // deprecated
  35337. JOINTS_0: 'skinIndex',
  35338. JOINT: 'skinIndex' // deprecated
  35339. };
  35340. var PATH_PROPERTIES = {
  35341. scale: 'scale',
  35342. translation: 'position',
  35343. rotation: 'quaternion',
  35344. weights: 'morphTargetInfluences'
  35345. };
  35346. var INTERPOLATION = {
  35347. CUBICSPLINE: THREE.InterpolateSmooth, // We use custom interpolation GLTFCubicSplineInterpolation for CUBICSPLINE.
  35348. // KeyframeTrack.optimize() can't handle glTF Cubic Spline output values layout,
  35349. // using THREE.InterpolateSmooth for KeyframeTrack instantiation to prevent optimization.
  35350. // See KeyframeTrack.optimize() for the detail.
  35351. LINEAR: THREE.InterpolateLinear,
  35352. STEP: THREE.InterpolateDiscrete
  35353. };
  35354. var STATES_ENABLES = {
  35355. 2884: 'CULL_FACE',
  35356. 2929: 'DEPTH_TEST',
  35357. 3042: 'BLEND',
  35358. 3089: 'SCISSOR_TEST',
  35359. 32823: 'POLYGON_OFFSET_FILL',
  35360. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  35361. };
  35362. var ALPHA_MODES = {
  35363. OPAQUE: 'OPAQUE',
  35364. MASK: 'MASK',
  35365. BLEND: 'BLEND'
  35366. };
  35367. /* UTILITY FUNCTIONS */
  35368. function resolveURL( url, path ) {
  35369. // Invalid URL
  35370. if ( typeof url !== 'string' || url === '' ) return '';
  35371. // Absolute URL http://,https://,//
  35372. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35373. // Data URI
  35374. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35375. // Blob URL
  35376. if ( /^blob:.*$/i.test( url ) ) return url;
  35377. // Relative URL
  35378. return path + url;
  35379. }
  35380. /**
  35381. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  35382. */
  35383. function createDefaultMaterial() {
  35384. return new THREE.MeshStandardMaterial( {
  35385. color: 0xFFFFFF,
  35386. emissive: 0x000000,
  35387. metalness: 1,
  35388. roughness: 1,
  35389. transparent: false,
  35390. depthTest: true,
  35391. side: THREE.FrontSide
  35392. } );
  35393. }
  35394. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  35395. // Add unknown glTF extensions to an object's userData.
  35396. for ( var name in objectDef.extensions ) {
  35397. if ( knownExtensions[ name ] === undefined ) {
  35398. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  35399. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  35400. }
  35401. }
  35402. }
  35403. /**
  35404. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  35405. * @param {GLTF.definition} def
  35406. */
  35407. function assignExtrasToUserData( object, gltfDef ) {
  35408. if ( gltfDef.extras !== undefined ) {
  35409. if ( typeof gltfDef.extras === 'object' ) {
  35410. object.userData = gltfDef.extras;
  35411. } else {
  35412. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  35413. }
  35414. }
  35415. }
  35416. /**
  35417. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  35418. *
  35419. * @param {THREE.BufferGeometry} geometry
  35420. * @param {Array<GLTF.Target>} targets
  35421. * @param {Array<THREE.BufferAttribute>} accessors
  35422. */
  35423. function addMorphTargets( geometry, targets, accessors ) {
  35424. var hasMorphPosition = false;
  35425. var hasMorphNormal = false;
  35426. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  35427. var target = targets[ i ];
  35428. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  35429. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  35430. if ( hasMorphPosition && hasMorphNormal ) break;
  35431. }
  35432. if ( ! hasMorphPosition && ! hasMorphNormal ) return;
  35433. var morphPositions = [];
  35434. var morphNormals = [];
  35435. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  35436. var target = targets[ i ];
  35437. var attributeName = 'morphTarget' + i;
  35438. if ( hasMorphPosition ) {
  35439. // Three.js morph position is absolute value. The formula is
  35440. // basePosition
  35441. // + weight0 * ( morphPosition0 - basePosition )
  35442. // + weight1 * ( morphPosition1 - basePosition )
  35443. // ...
  35444. // while the glTF one is relative
  35445. // basePosition
  35446. // + weight0 * glTFmorphPosition0
  35447. // + weight1 * glTFmorphPosition1
  35448. // ...
  35449. // then we need to convert from relative to absolute here.
  35450. if ( target.POSITION !== undefined ) {
  35451. // Cloning not to pollute original accessor
  35452. var positionAttribute = cloneBufferAttribute( accessors[ target.POSITION ] );
  35453. positionAttribute.name = attributeName;
  35454. var position = geometry.attributes.position;
  35455. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  35456. positionAttribute.setXYZ(
  35457. j,
  35458. positionAttribute.getX( j ) + position.getX( j ),
  35459. positionAttribute.getY( j ) + position.getY( j ),
  35460. positionAttribute.getZ( j ) + position.getZ( j )
  35461. );
  35462. }
  35463. } else {
  35464. positionAttribute = geometry.attributes.position;
  35465. }
  35466. morphPositions.push( positionAttribute );
  35467. }
  35468. if ( hasMorphNormal ) {
  35469. // see target.POSITION's comment
  35470. var normalAttribute;
  35471. if ( target.NORMAL !== undefined ) {
  35472. var normalAttribute = cloneBufferAttribute( accessors[ target.NORMAL ] );
  35473. normalAttribute.name = attributeName;
  35474. var normal = geometry.attributes.normal;
  35475. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  35476. normalAttribute.setXYZ(
  35477. j,
  35478. normalAttribute.getX( j ) + normal.getX( j ),
  35479. normalAttribute.getY( j ) + normal.getY( j ),
  35480. normalAttribute.getZ( j ) + normal.getZ( j )
  35481. );
  35482. }
  35483. } else {
  35484. normalAttribute = geometry.attributes.normal;
  35485. }
  35486. morphNormals.push( normalAttribute );
  35487. }
  35488. }
  35489. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  35490. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  35491. }
  35492. /**
  35493. * @param {THREE.Mesh} mesh
  35494. * @param {GLTF.Mesh} meshDef
  35495. */
  35496. function updateMorphTargets( mesh, meshDef ) {
  35497. mesh.updateMorphTargets();
  35498. if ( meshDef.weights !== undefined ) {
  35499. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  35500. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  35501. }
  35502. }
  35503. // .extras has user-defined data, so check that .extras.targetNames is an array.
  35504. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  35505. var targetNames = meshDef.extras.targetNames;
  35506. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  35507. mesh.morphTargetDictionary = {};
  35508. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  35509. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  35510. }
  35511. } else {
  35512. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  35513. }
  35514. }
  35515. }
  35516. function isPrimitiveEqual( a, b ) {
  35517. if ( a.indices !== b.indices ) {
  35518. return false;
  35519. }
  35520. return isObjectEqual( a.attributes, b.attributes );
  35521. }
  35522. function isObjectEqual( a, b ) {
  35523. if ( Object.keys( a ).length !== Object.keys( b ).length ) return false;
  35524. for ( var key in a ) {
  35525. if ( a[ key ] !== b[ key ] ) return false;
  35526. }
  35527. return true;
  35528. }
  35529. function isArrayEqual( a, b ) {
  35530. if ( a.length !== b.length ) return false;
  35531. for ( var i = 0, il = a.length; i < il; i ++ ) {
  35532. if ( a[ i ] !== b[ i ] ) return false;
  35533. }
  35534. return true;
  35535. }
  35536. function getCachedGeometry( cache, newPrimitive ) {
  35537. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  35538. var cached = cache[ i ];
  35539. if ( isPrimitiveEqual( cached.primitive, newPrimitive ) ) return cached.promise;
  35540. }
  35541. return null;
  35542. }
  35543. function getCachedCombinedGeometry( cache, geometries ) {
  35544. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  35545. var cached = cache[ i ];
  35546. if ( isArrayEqual( geometries, cached.baseGeometries ) ) return cached.geometry;
  35547. }
  35548. return null;
  35549. }
  35550. function getCachedMultiPassGeometry( cache, geometry, primitives ) {
  35551. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  35552. var cached = cache[ i ];
  35553. if ( geometry === cached.baseGeometry && isArrayEqual( primitives, cached.primitives ) ) return cached.geometry;
  35554. }
  35555. return null;
  35556. }
  35557. function cloneBufferAttribute( attribute ) {
  35558. if ( attribute.isInterleavedBufferAttribute ) {
  35559. var count = attribute.count;
  35560. var itemSize = attribute.itemSize;
  35561. var array = attribute.array.slice( 0, count * itemSize );
  35562. for ( var i = 0; i < count; ++ i ) {
  35563. array[ i ] = attribute.getX( i );
  35564. if ( itemSize >= 2 ) array[ i + 1 ] = attribute.getY( i );
  35565. if ( itemSize >= 3 ) array[ i + 2 ] = attribute.getZ( i );
  35566. if ( itemSize >= 4 ) array[ i + 3 ] = attribute.getW( i );
  35567. }
  35568. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  35569. }
  35570. return attribute.clone();
  35571. }
  35572. /**
  35573. * Checks if we can build a single Mesh with MultiMaterial from multiple primitives.
  35574. * Returns true if all primitives use the same attributes/morphAttributes/mode
  35575. * and also have index. Otherwise returns false.
  35576. *
  35577. * @param {Array<GLTF.Primitive>} primitives
  35578. * @return {Boolean}
  35579. */
  35580. function isMultiPassGeometry( primitives ) {
  35581. if ( primitives.length < 2 ) return false;
  35582. var primitive0 = primitives[ 0 ];
  35583. var targets0 = primitive0.targets || [];
  35584. if ( primitive0.indices === undefined ) return false;
  35585. for ( var i = 1, il = primitives.length; i < il; i ++ ) {
  35586. var primitive = primitives[ i ];
  35587. if ( primitive0.mode !== primitive.mode ) return false;
  35588. if ( primitive.indices === undefined ) return false;
  35589. if ( ! isObjectEqual( primitive0.attributes, primitive.attributes ) ) return false;
  35590. var targets = primitive.targets || [];
  35591. if ( targets0.length !== targets.length ) return false;
  35592. for ( var j = 0, jl = targets0.length; j < jl; j ++ ) {
  35593. if ( ! isObjectEqual( targets0[ j ], targets[ j ] ) ) return false;
  35594. }
  35595. }
  35596. return true;
  35597. }
  35598. /* GLTF PARSER */
  35599. function GLTFParser( json, extensions, options ) {
  35600. this.json = json || {};
  35601. this.extensions = extensions || {};
  35602. this.options = options || {};
  35603. // loader object cache
  35604. this.cache = new GLTFRegistry();
  35605. // BufferGeometry caching
  35606. this.primitiveCache = [];
  35607. this.multiplePrimitivesCache = [];
  35608. this.multiPassGeometryCache = [];
  35609. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  35610. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  35611. this.fileLoader = new THREE.FileLoader( this.options.manager );
  35612. this.fileLoader.setResponseType( 'arraybuffer' );
  35613. }
  35614. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  35615. var json = this.json;
  35616. // Clear the loader cache
  35617. this.cache.removeAll();
  35618. // Mark the special nodes/meshes in json for efficient parse
  35619. this.markDefs();
  35620. // Fire the callback on complete
  35621. this.getMultiDependencies( [
  35622. 'scene',
  35623. 'animation',
  35624. 'camera'
  35625. ] ).then( function ( dependencies ) {
  35626. var scenes = dependencies.scenes || [];
  35627. var scene = scenes[ json.scene || 0 ];
  35628. var animations = dependencies.animations || [];
  35629. var cameras = dependencies.cameras || [];
  35630. onLoad( scene, scenes, cameras, animations, json );
  35631. } ).catch( onError );
  35632. };
  35633. /**
  35634. * Marks the special nodes/meshes in json for efficient parse.
  35635. */
  35636. GLTFParser.prototype.markDefs = function () {
  35637. var nodeDefs = this.json.nodes || [];
  35638. var skinDefs = this.json.skins || [];
  35639. var meshDefs = this.json.meshes || [];
  35640. var meshReferences = {};
  35641. var meshUses = {};
  35642. // Nothing in the node definition indicates whether it is a Bone or an
  35643. // Object3D. Use the skins' joint references to mark bones.
  35644. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  35645. var joints = skinDefs[ skinIndex ].joints;
  35646. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  35647. nodeDefs[ joints[ i ] ].isBone = true;
  35648. }
  35649. }
  35650. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  35651. // avoid having more than one THREE.Mesh with the same name, count
  35652. // references and rename instances below.
  35653. //
  35654. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  35655. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  35656. var nodeDef = nodeDefs[ nodeIndex ];
  35657. if ( nodeDef.mesh !== undefined ) {
  35658. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  35659. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  35660. }
  35661. meshReferences[ nodeDef.mesh ] ++;
  35662. // Nothing in the mesh definition indicates whether it is
  35663. // a SkinnedMesh or Mesh. Use the node's mesh reference
  35664. // to mark SkinnedMesh if node has skin.
  35665. if ( nodeDef.skin !== undefined ) {
  35666. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  35667. }
  35668. }
  35669. }
  35670. this.json.meshReferences = meshReferences;
  35671. this.json.meshUses = meshUses;
  35672. };
  35673. /**
  35674. * Requests the specified dependency asynchronously, with caching.
  35675. * @param {string} type
  35676. * @param {number} index
  35677. * @return {Promise<Object>}
  35678. */
  35679. GLTFParser.prototype.getDependency = function ( type, index ) {
  35680. var cacheKey = type + ':' + index;
  35681. var dependency = this.cache.get( cacheKey );
  35682. if ( ! dependency ) {
  35683. switch ( type ) {
  35684. case 'scene':
  35685. dependency = this.loadScene( index );
  35686. break;
  35687. case 'node':
  35688. dependency = this.loadNode( index );
  35689. break;
  35690. case 'mesh':
  35691. dependency = this.loadMesh( index );
  35692. break;
  35693. case 'accessor':
  35694. dependency = this.loadAccessor( index );
  35695. break;
  35696. case 'bufferView':
  35697. dependency = this.loadBufferView( index );
  35698. break;
  35699. case 'buffer':
  35700. dependency = this.loadBuffer( index );
  35701. break;
  35702. case 'material':
  35703. dependency = this.loadMaterial( index );
  35704. break;
  35705. case 'texture':
  35706. dependency = this.loadTexture( index );
  35707. break;
  35708. case 'skin':
  35709. dependency = this.loadSkin( index );
  35710. break;
  35711. case 'animation':
  35712. dependency = this.loadAnimation( index );
  35713. break;
  35714. case 'camera':
  35715. dependency = this.loadCamera( index );
  35716. break;
  35717. default:
  35718. throw new Error( 'Unknown type: ' + type );
  35719. }
  35720. this.cache.add( cacheKey, dependency );
  35721. }
  35722. return dependency;
  35723. };
  35724. /**
  35725. * Requests all dependencies of the specified type asynchronously, with caching.
  35726. * @param {string} type
  35727. * @return {Promise<Array<Object>>}
  35728. */
  35729. GLTFParser.prototype.getDependencies = function ( type ) {
  35730. var dependencies = this.cache.get( type );
  35731. if ( ! dependencies ) {
  35732. var parser = this;
  35733. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  35734. dependencies = Promise.all( defs.map( function ( def, index ) {
  35735. return parser.getDependency( type, index );
  35736. } ) );
  35737. this.cache.add( type, dependencies );
  35738. }
  35739. return dependencies;
  35740. };
  35741. /**
  35742. * Requests all multiple dependencies of the specified types asynchronously, with caching.
  35743. * @param {Array<string>} types
  35744. * @return {Promise<Object<Array<Object>>>}
  35745. */
  35746. GLTFParser.prototype.getMultiDependencies = function ( types ) {
  35747. var results = {};
  35748. var pendings = [];
  35749. for ( var i = 0, il = types.length; i < il; i ++ ) {
  35750. var type = types[ i ];
  35751. var value = this.getDependencies( type );
  35752. value = value.then( function ( key, value ) {
  35753. results[ key ] = value;
  35754. }.bind( this, type + ( type === 'mesh' ? 'es' : 's' ) ) );
  35755. pendings.push( value );
  35756. }
  35757. return Promise.all( pendings ).then( function () {
  35758. return results;
  35759. } );
  35760. };
  35761. /**
  35762. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35763. * @param {number} bufferIndex
  35764. * @return {Promise<ArrayBuffer>}
  35765. */
  35766. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  35767. var bufferDef = this.json.buffers[ bufferIndex ];
  35768. var loader = this.fileLoader;
  35769. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  35770. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  35771. }
  35772. // If present, GLB container is required to be the first buffer.
  35773. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  35774. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  35775. }
  35776. var options = this.options;
  35777. return new Promise( function ( resolve, reject ) {
  35778. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  35779. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  35780. } );
  35781. } );
  35782. };
  35783. /**
  35784. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35785. * @param {number} bufferViewIndex
  35786. * @return {Promise<ArrayBuffer>}
  35787. */
  35788. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  35789. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  35790. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  35791. var byteLength = bufferViewDef.byteLength || 0;
  35792. var byteOffset = bufferViewDef.byteOffset || 0;
  35793. return buffer.slice( byteOffset, byteOffset + byteLength );
  35794. } );
  35795. };
  35796. /**
  35797. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  35798. * @param {number} accessorIndex
  35799. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  35800. */
  35801. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  35802. var parser = this;
  35803. var json = this.json;
  35804. var accessorDef = this.json.accessors[ accessorIndex ];
  35805. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  35806. // Ignore empty accessors, which may be used to declare runtime
  35807. // information about attributes coming from another source (e.g. Draco
  35808. // compression extension).
  35809. return null;
  35810. }
  35811. var pendingBufferViews = [];
  35812. if ( accessorDef.bufferView !== undefined ) {
  35813. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  35814. } else {
  35815. pendingBufferViews.push( null );
  35816. }
  35817. if ( accessorDef.sparse !== undefined ) {
  35818. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  35819. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  35820. }
  35821. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  35822. var bufferView = bufferViews[ 0 ];
  35823. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  35824. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  35825. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  35826. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  35827. var itemBytes = elementBytes * itemSize;
  35828. var byteOffset = accessorDef.byteOffset || 0;
  35829. var byteStride = json.bufferViews[ accessorDef.bufferView ].byteStride;
  35830. var normalized = accessorDef.normalized === true;
  35831. var array, bufferAttribute;
  35832. // The buffer is not interleaved if the stride is the item size in bytes.
  35833. if ( byteStride && byteStride !== itemBytes ) {
  35834. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType;
  35835. var ib = parser.cache.get( ibCacheKey );
  35836. if ( ! ib ) {
  35837. // Use the full buffer if it's interleaved.
  35838. array = new TypedArray( bufferView );
  35839. // Integer parameters to IB/IBA are in array elements, not bytes.
  35840. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  35841. parser.cache.add( ibCacheKey, ib );
  35842. }
  35843. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, byteOffset / elementBytes, normalized );
  35844. } else {
  35845. if ( bufferView === null ) {
  35846. array = new TypedArray( accessorDef.count * itemSize );
  35847. } else {
  35848. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  35849. }
  35850. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  35851. }
  35852. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  35853. if ( accessorDef.sparse !== undefined ) {
  35854. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  35855. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  35856. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  35857. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  35858. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  35859. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  35860. if ( bufferView !== null ) {
  35861. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  35862. bufferAttribute.setArray( bufferAttribute.array.slice() );
  35863. }
  35864. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  35865. var index = sparseIndices[ i ];
  35866. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  35867. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  35868. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  35869. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  35870. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  35871. }
  35872. }
  35873. return bufferAttribute;
  35874. } );
  35875. };
  35876. /**
  35877. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  35878. * @param {number} textureIndex
  35879. * @return {Promise<THREE.Texture>}
  35880. */
  35881. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  35882. var parser = this;
  35883. var json = this.json;
  35884. var options = this.options;
  35885. var textureLoader = this.textureLoader;
  35886. var URL = window.URL || window.webkitURL;
  35887. var textureDef = json.textures[ textureIndex ];
  35888. var textureExtensions = textureDef.extensions || {};
  35889. var source;
  35890. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  35891. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  35892. } else {
  35893. source = json.images[ textureDef.source ];
  35894. }
  35895. var sourceURI = source.uri;
  35896. var isObjectURL = false;
  35897. if ( source.bufferView !== undefined ) {
  35898. // Load binary image data from bufferView, if provided.
  35899. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  35900. isObjectURL = true;
  35901. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  35902. sourceURI = URL.createObjectURL( blob );
  35903. return sourceURI;
  35904. } );
  35905. }
  35906. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  35907. // Load Texture resource.
  35908. var loader = THREE.Loader.Handlers.get( sourceURI );
  35909. if ( ! loader ) {
  35910. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  35911. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  35912. : textureLoader;
  35913. }
  35914. return new Promise( function ( resolve, reject ) {
  35915. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  35916. } );
  35917. } ).then( function ( texture ) {
  35918. // Clean up resources and configure Texture.
  35919. if ( isObjectURL === true ) {
  35920. URL.revokeObjectURL( sourceURI );
  35921. }
  35922. texture.flipY = false;
  35923. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  35924. var samplers = json.samplers || {};
  35925. var sampler = samplers[ textureDef.sampler ] || {};
  35926. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  35927. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  35928. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  35929. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  35930. return texture;
  35931. } );
  35932. };
  35933. /**
  35934. * Asynchronously assigns a texture to the given material parameters.
  35935. * @param {Object} materialParams
  35936. * @param {string} textureName
  35937. * @param {number} textureIndex
  35938. * @return {Promise}
  35939. */
  35940. GLTFParser.prototype.assignTexture = function ( materialParams, textureName, textureIndex ) {
  35941. return this.getDependency( 'texture', textureIndex ).then( function ( texture ) {
  35942. materialParams[ textureName ] = texture;
  35943. } );
  35944. };
  35945. /**
  35946. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  35947. * @param {number} materialIndex
  35948. * @return {Promise<THREE.Material>}
  35949. */
  35950. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  35951. var parser = this;
  35952. var json = this.json;
  35953. var extensions = this.extensions;
  35954. var materialDef = this.json.materials[ materialIndex ];
  35955. var materialType;
  35956. var materialParams = {};
  35957. var materialExtensions = materialDef.extensions || {};
  35958. var pending = [];
  35959. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  35960. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  35961. materialType = sgExtension.getMaterialType( materialDef );
  35962. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  35963. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  35964. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  35965. materialType = kmuExtension.getMaterialType( materialDef );
  35966. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  35967. } else {
  35968. // Specification:
  35969. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  35970. materialType = THREE.MeshStandardMaterial;
  35971. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  35972. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  35973. materialParams.opacity = 1.0;
  35974. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  35975. var array = metallicRoughness.baseColorFactor;
  35976. materialParams.color.fromArray( array );
  35977. materialParams.opacity = array[ 3 ];
  35978. }
  35979. if ( metallicRoughness.baseColorTexture !== undefined ) {
  35980. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  35981. }
  35982. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  35983. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  35984. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  35985. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  35986. pending.push( parser.assignTexture( materialParams, 'metalnessMap', textureIndex ) );
  35987. pending.push( parser.assignTexture( materialParams, 'roughnessMap', textureIndex ) );
  35988. }
  35989. }
  35990. if ( materialDef.doubleSided === true ) {
  35991. materialParams.side = THREE.DoubleSide;
  35992. }
  35993. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  35994. if ( alphaMode === ALPHA_MODES.BLEND ) {
  35995. materialParams.transparent = true;
  35996. } else {
  35997. materialParams.transparent = false;
  35998. if ( alphaMode === ALPHA_MODES.MASK ) {
  35999. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  36000. }
  36001. }
  36002. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  36003. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture.index ) );
  36004. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  36005. if ( materialDef.normalTexture.scale !== undefined ) {
  36006. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  36007. }
  36008. }
  36009. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  36010. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture.index ) );
  36011. if ( materialDef.occlusionTexture.strength !== undefined ) {
  36012. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  36013. }
  36014. }
  36015. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  36016. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  36017. }
  36018. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  36019. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture.index ) );
  36020. }
  36021. return Promise.all( pending ).then( function () {
  36022. var material;
  36023. if ( materialType === THREE.ShaderMaterial ) {
  36024. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  36025. } else {
  36026. material = new materialType( materialParams );
  36027. }
  36028. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  36029. // Normal map textures use OpenGL conventions:
  36030. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  36031. if ( material.normalScale ) {
  36032. material.normalScale.y = - material.normalScale.y;
  36033. }
  36034. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  36035. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  36036. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  36037. if ( material.specularMap ) material.specularMap.encoding = THREE.sRGBEncoding;
  36038. assignExtrasToUserData( material, materialDef );
  36039. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  36040. return material;
  36041. } );
  36042. };
  36043. /**
  36044. * @param {THREE.BufferGeometry} geometry
  36045. * @param {GLTF.Primitive} primitiveDef
  36046. * @param {Array<THREE.BufferAttribute>} accessors
  36047. */
  36048. function addPrimitiveAttributes( geometry, primitiveDef, accessors ) {
  36049. var attributes = primitiveDef.attributes;
  36050. for ( var gltfAttributeName in attributes ) {
  36051. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ];
  36052. var bufferAttribute = accessors[ attributes[ gltfAttributeName ] ];
  36053. // Skip attributes already provided by e.g. Draco extension.
  36054. if ( ! threeAttributeName ) continue;
  36055. if ( threeAttributeName in geometry.attributes ) continue;
  36056. geometry.addAttribute( threeAttributeName, bufferAttribute );
  36057. }
  36058. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  36059. geometry.setIndex( accessors[ primitiveDef.indices ] );
  36060. }
  36061. if ( primitiveDef.targets !== undefined ) {
  36062. addMorphTargets( geometry, primitiveDef.targets, accessors );
  36063. }
  36064. assignExtrasToUserData( geometry, primitiveDef );
  36065. }
  36066. /**
  36067. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  36068. *
  36069. * Creates BufferGeometries from primitives.
  36070. * If we can build a single BufferGeometry with .groups from multiple primitives, returns one BufferGeometry.
  36071. * Otherwise, returns BufferGeometries without .groups as many as primitives.
  36072. *
  36073. * @param {Array<Object>} primitives
  36074. * @return {Promise<Array<THREE.BufferGeometry>>}
  36075. */
  36076. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  36077. var parser = this;
  36078. var extensions = this.extensions;
  36079. var cache = this.primitiveCache;
  36080. var isMultiPass = isMultiPassGeometry( primitives );
  36081. var originalPrimitives;
  36082. if ( isMultiPass ) {
  36083. originalPrimitives = primitives; // save original primitives and use later
  36084. // We build a single BufferGeometry with .groups from multiple primitives
  36085. // because all primitives share the same attributes/morph/mode and have indices.
  36086. primitives = [ primitives[ 0 ] ];
  36087. // Sets .groups and combined indices to a geometry later in this method.
  36088. }
  36089. return this.getDependencies( 'accessor' ).then( function ( accessors ) {
  36090. var pending = [];
  36091. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  36092. var primitive = primitives[ i ];
  36093. // See if we've already created this geometry
  36094. var cached = getCachedGeometry( cache, primitive );
  36095. if ( cached ) {
  36096. // Use the cached geometry if it exists
  36097. pending.push( cached );
  36098. } else if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  36099. // Use DRACO geometry if available
  36100. var geometryPromise = extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  36101. .decodePrimitive( primitive, parser )
  36102. .then( function ( geometry ) {
  36103. addPrimitiveAttributes( geometry, primitive, accessors );
  36104. return geometry;
  36105. } );
  36106. cache.push( { primitive: primitive, promise: geometryPromise } );
  36107. pending.push( geometryPromise );
  36108. } else {
  36109. // Otherwise create a new geometry
  36110. var geometry = new THREE.BufferGeometry();
  36111. addPrimitiveAttributes( geometry, primitive, accessors );
  36112. var geometryPromise = Promise.resolve( geometry );
  36113. // Cache this geometry
  36114. cache.push( { primitive: primitive, promise: geometryPromise } );
  36115. pending.push( geometryPromise );
  36116. }
  36117. }
  36118. return Promise.all( pending ).then( function ( geometries ) {
  36119. if ( isMultiPass ) {
  36120. var baseGeometry = geometries[ 0 ];
  36121. // See if we've already created this combined geometry
  36122. var cache = parser.multiPassGeometryCache;
  36123. var cached = getCachedMultiPassGeometry( cache, baseGeometry, originalPrimitives );
  36124. if ( cached !== null ) return [ cached.geometry ];
  36125. // Cloning geometry because of index override.
  36126. // Attributes can be reused so cloning by myself here.
  36127. var geometry = new THREE.BufferGeometry();
  36128. geometry.name = baseGeometry.name;
  36129. geometry.userData = baseGeometry.userData;
  36130. for ( var key in baseGeometry.attributes ) geometry.addAttribute( key, baseGeometry.attributes[ key ] );
  36131. for ( var key in baseGeometry.morphAttributes ) geometry.morphAttributes[ key ] = baseGeometry.morphAttributes[ key ];
  36132. var indices = [];
  36133. var offset = 0;
  36134. for ( var i = 0, il = originalPrimitives.length; i < il; i ++ ) {
  36135. var accessor = accessors[ originalPrimitives[ i ].indices ];
  36136. for ( var j = 0, jl = accessor.count; j < jl; j ++ ) indices.push( accessor.array[ j ] );
  36137. geometry.addGroup( offset, accessor.count, i );
  36138. offset += accessor.count;
  36139. }
  36140. geometry.setIndex( indices );
  36141. cache.push( { geometry: geometry, baseGeometry: baseGeometry, primitives: originalPrimitives } );
  36142. return [ geometry ];
  36143. } else if ( geometries.length > 1 && THREE.BufferGeometryUtils !== undefined ) {
  36144. // Tries to merge geometries with BufferGeometryUtils if possible
  36145. for ( var i = 1, il = primitives.length; i < il; i ++ ) {
  36146. // can't merge if draw mode is different
  36147. if ( primitives[ 0 ].mode !== primitives[ i ].mode ) return geometries;
  36148. }
  36149. // See if we've already created this combined geometry
  36150. var cache = parser.multiplePrimitivesCache;
  36151. var cached = getCachedCombinedGeometry( cache, geometries );
  36152. if ( cached ) {
  36153. if ( cached.geometry !== null ) return [ cached.geometry ];
  36154. } else {
  36155. var geometry = THREE.BufferGeometryUtils.mergeBufferGeometries( geometries, true );
  36156. cache.push( { geometry: geometry, baseGeometries: geometries } );
  36157. if ( geometry !== null ) return [ geometry ];
  36158. }
  36159. }
  36160. return geometries;
  36161. } );
  36162. } );
  36163. };
  36164. /**
  36165. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  36166. * @param {number} meshIndex
  36167. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  36168. */
  36169. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  36170. var scope = this;
  36171. var json = this.json;
  36172. var extensions = this.extensions;
  36173. var meshDef = this.json.meshes[ meshIndex ];
  36174. return this.getMultiDependencies( [
  36175. 'accessor',
  36176. 'material'
  36177. ] ).then( function ( dependencies ) {
  36178. var primitives = meshDef.primitives;
  36179. var originalMaterials = [];
  36180. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  36181. originalMaterials[ i ] = primitives[ i ].material === undefined
  36182. ? createDefaultMaterial()
  36183. : dependencies.materials[ primitives[ i ].material ];
  36184. }
  36185. return scope.loadGeometries( primitives ).then( function ( geometries ) {
  36186. var isMultiMaterial = geometries.length === 1 && geometries[ 0 ].groups.length > 0;
  36187. var meshes = [];
  36188. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  36189. var geometry = geometries[ i ];
  36190. var primitive = primitives[ i ];
  36191. // 1. create Mesh
  36192. var mesh;
  36193. var material = isMultiMaterial ? originalMaterials : originalMaterials[ i ];
  36194. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  36195. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  36196. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  36197. primitive.mode === undefined ) {
  36198. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  36199. mesh = meshDef.isSkinnedMesh === true
  36200. ? new THREE.SkinnedMesh( geometry, material )
  36201. : new THREE.Mesh( geometry, material );
  36202. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  36203. mesh.drawMode = THREE.TriangleStripDrawMode;
  36204. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  36205. mesh.drawMode = THREE.TriangleFanDrawMode;
  36206. }
  36207. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  36208. mesh = new THREE.LineSegments( geometry, material );
  36209. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  36210. mesh = new THREE.Line( geometry, material );
  36211. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  36212. mesh = new THREE.LineLoop( geometry, material );
  36213. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  36214. mesh = new THREE.Points( geometry, material );
  36215. } else {
  36216. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  36217. }
  36218. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  36219. updateMorphTargets( mesh, meshDef );
  36220. }
  36221. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  36222. if ( geometries.length > 1 ) mesh.name += '_' + i;
  36223. assignExtrasToUserData( mesh, meshDef );
  36224. meshes.push( mesh );
  36225. // 2. update Material depending on Mesh and BufferGeometry
  36226. var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  36227. var useVertexColors = geometry.attributes.color !== undefined;
  36228. var useFlatShading = geometry.attributes.normal === undefined;
  36229. var useSkinning = mesh.isSkinnedMesh === true;
  36230. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  36231. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  36232. for ( var j = 0, jl = materials.length; j < jl; j ++ ) {
  36233. var material = materials[ j ];
  36234. if ( mesh.isPoints ) {
  36235. var cacheKey = 'PointsMaterial:' + material.uuid;
  36236. var pointsMaterial = scope.cache.get( cacheKey );
  36237. if ( ! pointsMaterial ) {
  36238. pointsMaterial = new THREE.PointsMaterial();
  36239. THREE.Material.prototype.copy.call( pointsMaterial, material );
  36240. pointsMaterial.color.copy( material.color );
  36241. pointsMaterial.map = material.map;
  36242. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  36243. scope.cache.add( cacheKey, pointsMaterial );
  36244. }
  36245. material = pointsMaterial;
  36246. } else if ( mesh.isLine ) {
  36247. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  36248. var lineMaterial = scope.cache.get( cacheKey );
  36249. if ( ! lineMaterial ) {
  36250. lineMaterial = new THREE.LineBasicMaterial();
  36251. THREE.Material.prototype.copy.call( lineMaterial, material );
  36252. lineMaterial.color.copy( material.color );
  36253. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  36254. scope.cache.add( cacheKey, lineMaterial );
  36255. }
  36256. material = lineMaterial;
  36257. }
  36258. // Clone the material if it will be modified
  36259. if ( useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  36260. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  36261. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  36262. if ( useSkinning ) cacheKey += 'skinning:';
  36263. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  36264. if ( useFlatShading ) cacheKey += 'flat-shading:';
  36265. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  36266. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  36267. var cachedMaterial = scope.cache.get( cacheKey );
  36268. if ( ! cachedMaterial ) {
  36269. cachedMaterial = material.isGLTFSpecularGlossinessMaterial
  36270. ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material )
  36271. : material.clone();
  36272. if ( useSkinning ) cachedMaterial.skinning = true;
  36273. if ( useVertexColors ) cachedMaterial.vertexColors = THREE.VertexColors;
  36274. if ( useFlatShading ) cachedMaterial.flatShading = true;
  36275. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  36276. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  36277. scope.cache.add( cacheKey, cachedMaterial );
  36278. }
  36279. material = cachedMaterial;
  36280. }
  36281. materials[ j ] = material;
  36282. // workarounds for mesh and geometry
  36283. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  36284. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  36285. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  36286. }
  36287. if ( material.isGLTFSpecularGlossinessMaterial ) {
  36288. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  36289. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  36290. }
  36291. }
  36292. mesh.material = isMultiMaterial ? materials : materials[ 0 ];
  36293. }
  36294. if ( meshes.length === 1 ) {
  36295. return meshes[ 0 ];
  36296. }
  36297. var group = new THREE.Group();
  36298. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  36299. group.add( meshes[ i ] );
  36300. }
  36301. return group;
  36302. } );
  36303. } );
  36304. };
  36305. /**
  36306. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  36307. * @param {number} cameraIndex
  36308. * @return {Promise<THREE.Camera>}
  36309. */
  36310. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  36311. var camera;
  36312. var cameraDef = this.json.cameras[ cameraIndex ];
  36313. var params = cameraDef[ cameraDef.type ];
  36314. if ( ! params ) {
  36315. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  36316. return;
  36317. }
  36318. if ( cameraDef.type === 'perspective' ) {
  36319. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  36320. } else if ( cameraDef.type === 'orthographic' ) {
  36321. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  36322. }
  36323. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  36324. assignExtrasToUserData( camera, cameraDef );
  36325. return Promise.resolve( camera );
  36326. };
  36327. /**
  36328. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  36329. * @param {number} skinIndex
  36330. * @return {Promise<Object>}
  36331. */
  36332. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  36333. var skinDef = this.json.skins[ skinIndex ];
  36334. var skinEntry = { joints: skinDef.joints };
  36335. if ( skinDef.inverseBindMatrices === undefined ) {
  36336. return Promise.resolve( skinEntry );
  36337. }
  36338. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  36339. skinEntry.inverseBindMatrices = accessor;
  36340. return skinEntry;
  36341. } );
  36342. };
  36343. /**
  36344. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  36345. * @param {number} animationIndex
  36346. * @return {Promise<THREE.AnimationClip>}
  36347. */
  36348. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  36349. var json = this.json;
  36350. var animationDef = this.json.animations[ animationIndex ];
  36351. return this.getMultiDependencies( [
  36352. 'accessor',
  36353. 'node'
  36354. ] ).then( function ( dependencies ) {
  36355. var tracks = [];
  36356. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  36357. var channel = animationDef.channels[ i ];
  36358. var sampler = animationDef.samplers[ channel.sampler ];
  36359. if ( sampler ) {
  36360. var target = channel.target;
  36361. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  36362. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  36363. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  36364. var inputAccessor = dependencies.accessors[ input ];
  36365. var outputAccessor = dependencies.accessors[ output ];
  36366. var node = dependencies.nodes[ name ];
  36367. if ( node ) {
  36368. node.updateMatrix();
  36369. node.matrixAutoUpdate = true;
  36370. var TypedKeyframeTrack;
  36371. switch ( PATH_PROPERTIES[ target.path ] ) {
  36372. case PATH_PROPERTIES.weights:
  36373. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  36374. break;
  36375. case PATH_PROPERTIES.rotation:
  36376. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  36377. break;
  36378. case PATH_PROPERTIES.position:
  36379. case PATH_PROPERTIES.scale:
  36380. default:
  36381. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  36382. break;
  36383. }
  36384. var targetName = node.name ? node.name : node.uuid;
  36385. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  36386. var targetNames = [];
  36387. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  36388. // node can be THREE.Group here but
  36389. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  36390. // the property of a mesh object under group.
  36391. node.traverse( function ( object ) {
  36392. if ( object.isMesh === true && object.morphTargetInfluences ) {
  36393. targetNames.push( object.name ? object.name : object.uuid );
  36394. }
  36395. } );
  36396. } else {
  36397. targetNames.push( targetName );
  36398. }
  36399. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  36400. // buffers before creating a truncated copy to keep. Because buffers may
  36401. // be reused by other tracks, make copies here.
  36402. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  36403. var track = new TypedKeyframeTrack(
  36404. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  36405. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  36406. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  36407. interpolation
  36408. );
  36409. // Here is the trick to enable custom interpolation.
  36410. // Overrides .createInterpolant in a factory method which creates custom interpolation.
  36411. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  36412. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  36413. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  36414. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  36415. // must be divided by three to get the interpolant's sampleSize argument.
  36416. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  36417. };
  36418. // Workaround, provide an alternate way to know if the interpolant type is cubis spline to track.
  36419. // track.getInterpolation() doesn't return valid value for custom interpolant.
  36420. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  36421. }
  36422. tracks.push( track );
  36423. }
  36424. }
  36425. }
  36426. }
  36427. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  36428. return new THREE.AnimationClip( name, undefined, tracks );
  36429. } );
  36430. };
  36431. /**
  36432. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  36433. * @param {number} nodeIndex
  36434. * @return {Promise<THREE.Object3D>}
  36435. */
  36436. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  36437. var json = this.json;
  36438. var extensions = this.extensions;
  36439. var meshReferences = this.json.meshReferences;
  36440. var meshUses = this.json.meshUses;
  36441. var nodeDef = this.json.nodes[ nodeIndex ];
  36442. return this.getMultiDependencies( [
  36443. 'mesh',
  36444. 'skin',
  36445. 'camera',
  36446. 'light'
  36447. ] ).then( function ( dependencies ) {
  36448. var node;
  36449. // .isBone isn't in glTF spec. See .markDefs
  36450. if ( nodeDef.isBone === true ) {
  36451. node = new THREE.Bone();
  36452. } else if ( nodeDef.mesh !== undefined ) {
  36453. var mesh = dependencies.meshes[ nodeDef.mesh ];
  36454. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  36455. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  36456. node = mesh.clone();
  36457. node.name += '_instance_' + instanceNum;
  36458. // onBeforeRender copy for Specular-Glossiness
  36459. node.onBeforeRender = mesh.onBeforeRender;
  36460. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  36461. node.children[ i ].name += '_instance_' + instanceNum;
  36462. node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender;
  36463. }
  36464. } else {
  36465. node = mesh;
  36466. }
  36467. } else if ( nodeDef.camera !== undefined ) {
  36468. node = dependencies.cameras[ nodeDef.camera ];
  36469. } else if ( nodeDef.extensions
  36470. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  36471. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  36472. var lights = extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].lights;
  36473. node = lights[ nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light ];
  36474. } else {
  36475. node = new THREE.Object3D();
  36476. }
  36477. if ( nodeDef.name !== undefined ) {
  36478. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  36479. }
  36480. assignExtrasToUserData( node, nodeDef );
  36481. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  36482. if ( nodeDef.matrix !== undefined ) {
  36483. var matrix = new THREE.Matrix4();
  36484. matrix.fromArray( nodeDef.matrix );
  36485. node.applyMatrix( matrix );
  36486. } else {
  36487. if ( nodeDef.translation !== undefined ) {
  36488. node.position.fromArray( nodeDef.translation );
  36489. }
  36490. if ( nodeDef.rotation !== undefined ) {
  36491. node.quaternion.fromArray( nodeDef.rotation );
  36492. }
  36493. if ( nodeDef.scale !== undefined ) {
  36494. node.scale.fromArray( nodeDef.scale );
  36495. }
  36496. }
  36497. return node;
  36498. } );
  36499. };
  36500. /**
  36501. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  36502. * @param {number} sceneIndex
  36503. * @return {Promise<THREE.Scene>}
  36504. */
  36505. GLTFParser.prototype.loadScene = function () {
  36506. // scene node hierachy builder
  36507. function buildNodeHierachy( nodeId, parentObject, json, allNodes, skins ) {
  36508. var node = allNodes[ nodeId ];
  36509. var nodeDef = json.nodes[ nodeId ];
  36510. // build skeleton here as well
  36511. if ( nodeDef.skin !== undefined ) {
  36512. var meshes = node.isGroup === true ? node.children : [ node ];
  36513. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  36514. var mesh = meshes[ i ];
  36515. var skinEntry = skins[ nodeDef.skin ];
  36516. var bones = [];
  36517. var boneInverses = [];
  36518. for ( var j = 0, jl = skinEntry.joints.length; j < jl; j ++ ) {
  36519. var jointId = skinEntry.joints[ j ];
  36520. var jointNode = allNodes[ jointId ];
  36521. if ( jointNode ) {
  36522. bones.push( jointNode );
  36523. var mat = new THREE.Matrix4();
  36524. if ( skinEntry.inverseBindMatrices !== undefined ) {
  36525. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  36526. }
  36527. boneInverses.push( mat );
  36528. } else {
  36529. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', jointId );
  36530. }
  36531. }
  36532. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  36533. }
  36534. }
  36535. // build node hierachy
  36536. parentObject.add( node );
  36537. if ( nodeDef.children ) {
  36538. var children = nodeDef.children;
  36539. for ( var i = 0, il = children.length; i < il; i ++ ) {
  36540. var child = children[ i ];
  36541. buildNodeHierachy( child, node, json, allNodes, skins );
  36542. }
  36543. }
  36544. }
  36545. return function loadScene( sceneIndex ) {
  36546. var json = this.json;
  36547. var extensions = this.extensions;
  36548. var sceneDef = this.json.scenes[ sceneIndex ];
  36549. return this.getMultiDependencies( [
  36550. 'node',
  36551. 'skin'
  36552. ] ).then( function ( dependencies ) {
  36553. var scene = new THREE.Scene();
  36554. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  36555. assignExtrasToUserData( scene, sceneDef );
  36556. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  36557. var nodeIds = sceneDef.nodes || [];
  36558. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  36559. buildNodeHierachy( nodeIds[ i ], scene, json, dependencies.nodes, dependencies.skins );
  36560. }
  36561. return scene;
  36562. } );
  36563. };
  36564. }();
  36565. return GLTFLoader;
  36566. } )();
  36567. },{}],43:[function(_dereq_,module,exports){
  36568. /**
  36569. * Loads a Wavefront .mtl file specifying materials
  36570. *
  36571. * @author angelxuanchang
  36572. */
  36573. THREE.MTLLoader = function ( manager ) {
  36574. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  36575. };
  36576. THREE.MTLLoader.prototype = {
  36577. constructor: THREE.MTLLoader,
  36578. /**
  36579. * Loads and parses a MTL asset from a URL.
  36580. *
  36581. * @param {String} url - URL to the MTL file.
  36582. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  36583. * @param {Function} [onProgress] - Callback for download progress.
  36584. * @param {Function} [onError] - Callback for download errors.
  36585. *
  36586. * @see setPath setTexturePath
  36587. *
  36588. * @note In order for relative texture references to resolve correctly
  36589. * you must call setPath and/or setTexturePath explicitly prior to load.
  36590. */
  36591. load: function ( url, onLoad, onProgress, onError ) {
  36592. var scope = this;
  36593. var loader = new THREE.FileLoader( this.manager );
  36594. loader.setPath( this.path );
  36595. loader.load( url, function ( text ) {
  36596. onLoad( scope.parse( text ) );
  36597. }, onProgress, onError );
  36598. },
  36599. /**
  36600. * Set base path for resolving references.
  36601. * If set this path will be prepended to each loaded and found reference.
  36602. *
  36603. * @see setTexturePath
  36604. * @param {String} path
  36605. * @return {THREE.MTLLoader}
  36606. *
  36607. * @example
  36608. * mtlLoader.setPath( 'assets/obj/' );
  36609. * mtlLoader.load( 'my.mtl', ... );
  36610. */
  36611. setPath: function ( path ) {
  36612. this.path = path;
  36613. return this;
  36614. },
  36615. /**
  36616. * Set base path for resolving texture references.
  36617. * If set this path will be prepended found texture reference.
  36618. * If not set and setPath is, it will be used as texture base path.
  36619. *
  36620. * @see setPath
  36621. * @param {String} path
  36622. * @return {THREE.MTLLoader}
  36623. *
  36624. * @example
  36625. * mtlLoader.setPath( 'assets/obj/' );
  36626. * mtlLoader.setTexturePath( 'assets/textures/' );
  36627. * mtlLoader.load( 'my.mtl', ... );
  36628. */
  36629. setTexturePath: function ( path ) {
  36630. this.texturePath = path;
  36631. return this;
  36632. },
  36633. setBaseUrl: function ( path ) {
  36634. console.warn( 'THREE.MTLLoader: .setBaseUrl() is deprecated. Use .setTexturePath( path ) for texture path or .setPath( path ) for general base path instead.' );
  36635. return this.setTexturePath( path );
  36636. },
  36637. setCrossOrigin: function ( value ) {
  36638. this.crossOrigin = value;
  36639. return this;
  36640. },
  36641. setMaterialOptions: function ( value ) {
  36642. this.materialOptions = value;
  36643. return this;
  36644. },
  36645. /**
  36646. * Parses a MTL file.
  36647. *
  36648. * @param {String} text - Content of MTL file
  36649. * @return {THREE.MTLLoader.MaterialCreator}
  36650. *
  36651. * @see setPath setTexturePath
  36652. *
  36653. * @note In order for relative texture references to resolve correctly
  36654. * you must call setPath and/or setTexturePath explicitly prior to parse.
  36655. */
  36656. parse: function ( text ) {
  36657. var lines = text.split( '\n' );
  36658. var info = {};
  36659. var delimiter_pattern = /\s+/;
  36660. var materialsInfo = {};
  36661. for ( var i = 0; i < lines.length; i ++ ) {
  36662. var line = lines[ i ];
  36663. line = line.trim();
  36664. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  36665. // Blank line or comment ignore
  36666. continue;
  36667. }
  36668. var pos = line.indexOf( ' ' );
  36669. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  36670. key = key.toLowerCase();
  36671. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  36672. value = value.trim();
  36673. if ( key === 'newmtl' ) {
  36674. // New material
  36675. info = { name: value };
  36676. materialsInfo[ value ] = info;
  36677. } else if ( info ) {
  36678. if ( key === 'ka' || key === 'kd' || key === 'ks' ) {
  36679. var ss = value.split( delimiter_pattern, 3 );
  36680. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  36681. } else {
  36682. info[ key ] = value;
  36683. }
  36684. }
  36685. }
  36686. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.texturePath || this.path, this.materialOptions );
  36687. materialCreator.setCrossOrigin( this.crossOrigin );
  36688. materialCreator.setManager( this.manager );
  36689. materialCreator.setMaterials( materialsInfo );
  36690. return materialCreator;
  36691. }
  36692. };
  36693. /**
  36694. * Create a new THREE-MTLLoader.MaterialCreator
  36695. * @param baseUrl - Url relative to which textures are loaded
  36696. * @param options - Set of options on how to construct the materials
  36697. * side: Which side to apply the material
  36698. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  36699. * wrap: What type of wrapping to apply for textures
  36700. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  36701. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  36702. * Default: false, assumed to be already normalized
  36703. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  36704. * Default: false
  36705. * @constructor
  36706. */
  36707. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  36708. this.baseUrl = baseUrl || '';
  36709. this.options = options;
  36710. this.materialsInfo = {};
  36711. this.materials = {};
  36712. this.materialsArray = [];
  36713. this.nameLookup = {};
  36714. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  36715. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  36716. };
  36717. THREE.MTLLoader.MaterialCreator.prototype = {
  36718. constructor: THREE.MTLLoader.MaterialCreator,
  36719. crossOrigin: 'anonymous',
  36720. setCrossOrigin: function ( value ) {
  36721. this.crossOrigin = value;
  36722. return this;
  36723. },
  36724. setManager: function ( value ) {
  36725. this.manager = value;
  36726. },
  36727. setMaterials: function ( materialsInfo ) {
  36728. this.materialsInfo = this.convert( materialsInfo );
  36729. this.materials = {};
  36730. this.materialsArray = [];
  36731. this.nameLookup = {};
  36732. },
  36733. convert: function ( materialsInfo ) {
  36734. if ( ! this.options ) return materialsInfo;
  36735. var converted = {};
  36736. for ( var mn in materialsInfo ) {
  36737. // Convert materials info into normalized form based on options
  36738. var mat = materialsInfo[ mn ];
  36739. var covmat = {};
  36740. converted[ mn ] = covmat;
  36741. for ( var prop in mat ) {
  36742. var save = true;
  36743. var value = mat[ prop ];
  36744. var lprop = prop.toLowerCase();
  36745. switch ( lprop ) {
  36746. case 'kd':
  36747. case 'ka':
  36748. case 'ks':
  36749. // Diffuse color (color under white light) using RGB values
  36750. if ( this.options && this.options.normalizeRGB ) {
  36751. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  36752. }
  36753. if ( this.options && this.options.ignoreZeroRGBs ) {
  36754. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  36755. // ignore
  36756. save = false;
  36757. }
  36758. }
  36759. break;
  36760. default:
  36761. break;
  36762. }
  36763. if ( save ) {
  36764. covmat[ lprop ] = value;
  36765. }
  36766. }
  36767. }
  36768. return converted;
  36769. },
  36770. preload: function () {
  36771. for ( var mn in this.materialsInfo ) {
  36772. this.create( mn );
  36773. }
  36774. },
  36775. getIndex: function ( materialName ) {
  36776. return this.nameLookup[ materialName ];
  36777. },
  36778. getAsArray: function () {
  36779. var index = 0;
  36780. for ( var mn in this.materialsInfo ) {
  36781. this.materialsArray[ index ] = this.create( mn );
  36782. this.nameLookup[ mn ] = index;
  36783. index ++;
  36784. }
  36785. return this.materialsArray;
  36786. },
  36787. create: function ( materialName ) {
  36788. if ( this.materials[ materialName ] === undefined ) {
  36789. this.createMaterial_( materialName );
  36790. }
  36791. return this.materials[ materialName ];
  36792. },
  36793. createMaterial_: function ( materialName ) {
  36794. // Create material
  36795. var scope = this;
  36796. var mat = this.materialsInfo[ materialName ];
  36797. var params = {
  36798. name: materialName,
  36799. side: this.side
  36800. };
  36801. function resolveURL( baseUrl, url ) {
  36802. if ( typeof url !== 'string' || url === '' )
  36803. return '';
  36804. // Absolute URL
  36805. if ( /^https?:\/\//i.test( url ) ) return url;
  36806. return baseUrl + url;
  36807. }
  36808. function setMapForType( mapType, value ) {
  36809. if ( params[ mapType ] ) return; // Keep the first encountered texture
  36810. var texParams = scope.getTextureParams( value, params );
  36811. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  36812. map.repeat.copy( texParams.scale );
  36813. map.offset.copy( texParams.offset );
  36814. map.wrapS = scope.wrap;
  36815. map.wrapT = scope.wrap;
  36816. params[ mapType ] = map;
  36817. }
  36818. for ( var prop in mat ) {
  36819. var value = mat[ prop ];
  36820. var n;
  36821. if ( value === '' ) continue;
  36822. switch ( prop.toLowerCase() ) {
  36823. // Ns is material specular exponent
  36824. case 'kd':
  36825. // Diffuse color (color under white light) using RGB values
  36826. params.color = new THREE.Color().fromArray( value );
  36827. break;
  36828. case 'ks':
  36829. // Specular color (color when light is reflected from shiny surface) using RGB values
  36830. params.specular = new THREE.Color().fromArray( value );
  36831. break;
  36832. case 'map_kd':
  36833. // Diffuse texture map
  36834. setMapForType( "map", value );
  36835. break;
  36836. case 'map_ks':
  36837. // Specular map
  36838. setMapForType( "specularMap", value );
  36839. break;
  36840. case 'norm':
  36841. setMapForType( "normalMap", value );
  36842. break;
  36843. case 'map_bump':
  36844. case 'bump':
  36845. // Bump texture map
  36846. setMapForType( "bumpMap", value );
  36847. break;
  36848. case 'ns':
  36849. // The specular exponent (defines the focus of the specular highlight)
  36850. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  36851. params.shininess = parseFloat( value );
  36852. break;
  36853. case 'd':
  36854. n = parseFloat( value );
  36855. if ( n < 1 ) {
  36856. params.opacity = n;
  36857. params.transparent = true;
  36858. }
  36859. break;
  36860. case 'tr':
  36861. n = parseFloat( value );
  36862. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  36863. if ( n > 0 ) {
  36864. params.opacity = 1 - n;
  36865. params.transparent = true;
  36866. }
  36867. break;
  36868. default:
  36869. break;
  36870. }
  36871. }
  36872. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  36873. return this.materials[ materialName ];
  36874. },
  36875. getTextureParams: function ( value, matParams ) {
  36876. var texParams = {
  36877. scale: new THREE.Vector2( 1, 1 ),
  36878. offset: new THREE.Vector2( 0, 0 )
  36879. };
  36880. var items = value.split( /\s+/ );
  36881. var pos;
  36882. pos = items.indexOf( '-bm' );
  36883. if ( pos >= 0 ) {
  36884. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  36885. items.splice( pos, 2 );
  36886. }
  36887. pos = items.indexOf( '-s' );
  36888. if ( pos >= 0 ) {
  36889. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36890. items.splice( pos, 4 ); // we expect 3 parameters here!
  36891. }
  36892. pos = items.indexOf( '-o' );
  36893. if ( pos >= 0 ) {
  36894. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36895. items.splice( pos, 4 ); // we expect 3 parameters here!
  36896. }
  36897. texParams.url = items.join( ' ' ).trim();
  36898. return texParams;
  36899. },
  36900. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  36901. var texture;
  36902. var loader = THREE.Loader.Handlers.get( url );
  36903. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  36904. if ( loader === null ) {
  36905. loader = new THREE.TextureLoader( manager );
  36906. }
  36907. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  36908. texture = loader.load( url, onLoad, onProgress, onError );
  36909. if ( mapping !== undefined ) texture.mapping = mapping;
  36910. return texture;
  36911. }
  36912. };
  36913. },{}],44:[function(_dereq_,module,exports){
  36914. /**
  36915. * @author mrdoob / http://mrdoob.com/
  36916. */
  36917. THREE.OBJLoader = ( function () {
  36918. // o object_name | g group_name
  36919. var object_pattern = /^[og]\s*(.+)?/;
  36920. // mtllib file_reference
  36921. var material_library_pattern = /^mtllib /;
  36922. // usemtl material_name
  36923. var material_use_pattern = /^usemtl /;
  36924. function ParserState() {
  36925. var state = {
  36926. objects: [],
  36927. object: {},
  36928. vertices: [],
  36929. normals: [],
  36930. colors: [],
  36931. uvs: [],
  36932. materialLibraries: [],
  36933. startObject: function ( name, fromDeclaration ) {
  36934. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  36935. // file. We need to use it for the first parsed g/o to keep things in sync.
  36936. if ( this.object && this.object.fromDeclaration === false ) {
  36937. this.object.name = name;
  36938. this.object.fromDeclaration = ( fromDeclaration !== false );
  36939. return;
  36940. }
  36941. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  36942. if ( this.object && typeof this.object._finalize === 'function' ) {
  36943. this.object._finalize( true );
  36944. }
  36945. this.object = {
  36946. name: name || '',
  36947. fromDeclaration: ( fromDeclaration !== false ),
  36948. geometry: {
  36949. vertices: [],
  36950. normals: [],
  36951. colors: [],
  36952. uvs: []
  36953. },
  36954. materials: [],
  36955. smooth: true,
  36956. startMaterial: function ( name, libraries ) {
  36957. var previous = this._finalize( false );
  36958. // New usemtl declaration overwrites an inherited material, except if faces were declared
  36959. // after the material, then it must be preserved for proper MultiMaterial continuation.
  36960. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  36961. this.materials.splice( previous.index, 1 );
  36962. }
  36963. var material = {
  36964. index: this.materials.length,
  36965. name: name || '',
  36966. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  36967. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  36968. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  36969. groupEnd: - 1,
  36970. groupCount: - 1,
  36971. inherited: false,
  36972. clone: function ( index ) {
  36973. var cloned = {
  36974. index: ( typeof index === 'number' ? index : this.index ),
  36975. name: this.name,
  36976. mtllib: this.mtllib,
  36977. smooth: this.smooth,
  36978. groupStart: 0,
  36979. groupEnd: - 1,
  36980. groupCount: - 1,
  36981. inherited: false
  36982. };
  36983. cloned.clone = this.clone.bind( cloned );
  36984. return cloned;
  36985. }
  36986. };
  36987. this.materials.push( material );
  36988. return material;
  36989. },
  36990. currentMaterial: function () {
  36991. if ( this.materials.length > 0 ) {
  36992. return this.materials[ this.materials.length - 1 ];
  36993. }
  36994. return undefined;
  36995. },
  36996. _finalize: function ( end ) {
  36997. var lastMultiMaterial = this.currentMaterial();
  36998. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  36999. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  37000. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  37001. lastMultiMaterial.inherited = false;
  37002. }
  37003. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  37004. if ( end && this.materials.length > 1 ) {
  37005. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  37006. if ( this.materials[ mi ].groupCount <= 0 ) {
  37007. this.materials.splice( mi, 1 );
  37008. }
  37009. }
  37010. }
  37011. // Guarantee at least one empty material, this makes the creation later more straight forward.
  37012. if ( end && this.materials.length === 0 ) {
  37013. this.materials.push( {
  37014. name: '',
  37015. smooth: this.smooth
  37016. } );
  37017. }
  37018. return lastMultiMaterial;
  37019. }
  37020. };
  37021. // Inherit previous objects material.
  37022. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  37023. // If a usemtl declaration is encountered while this new object is being parsed, it will
  37024. // overwrite the inherited material. Exception being that there was already face declarations
  37025. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  37026. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  37027. var declared = previousMaterial.clone( 0 );
  37028. declared.inherited = true;
  37029. this.object.materials.push( declared );
  37030. }
  37031. this.objects.push( this.object );
  37032. },
  37033. finalize: function () {
  37034. if ( this.object && typeof this.object._finalize === 'function' ) {
  37035. this.object._finalize( true );
  37036. }
  37037. },
  37038. parseVertexIndex: function ( value, len ) {
  37039. var index = parseInt( value, 10 );
  37040. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  37041. },
  37042. parseNormalIndex: function ( value, len ) {
  37043. var index = parseInt( value, 10 );
  37044. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  37045. },
  37046. parseUVIndex: function ( value, len ) {
  37047. var index = parseInt( value, 10 );
  37048. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  37049. },
  37050. addVertex: function ( a, b, c ) {
  37051. var src = this.vertices;
  37052. var dst = this.object.geometry.vertices;
  37053. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  37054. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  37055. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  37056. },
  37057. addVertexPoint: function ( a ) {
  37058. var src = this.vertices;
  37059. var dst = this.object.geometry.vertices;
  37060. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  37061. },
  37062. addVertexLine: function ( a ) {
  37063. var src = this.vertices;
  37064. var dst = this.object.geometry.vertices;
  37065. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  37066. },
  37067. addNormal: function ( a, b, c ) {
  37068. var src = this.normals;
  37069. var dst = this.object.geometry.normals;
  37070. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  37071. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  37072. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  37073. },
  37074. addColor: function ( a, b, c ) {
  37075. var src = this.colors;
  37076. var dst = this.object.geometry.colors;
  37077. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  37078. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  37079. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  37080. },
  37081. addUV: function ( a, b, c ) {
  37082. var src = this.uvs;
  37083. var dst = this.object.geometry.uvs;
  37084. dst.push( src[ a + 0 ], src[ a + 1 ] );
  37085. dst.push( src[ b + 0 ], src[ b + 1 ] );
  37086. dst.push( src[ c + 0 ], src[ c + 1 ] );
  37087. },
  37088. addUVLine: function ( a ) {
  37089. var src = this.uvs;
  37090. var dst = this.object.geometry.uvs;
  37091. dst.push( src[ a + 0 ], src[ a + 1 ] );
  37092. },
  37093. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  37094. var vLen = this.vertices.length;
  37095. var ia = this.parseVertexIndex( a, vLen );
  37096. var ib = this.parseVertexIndex( b, vLen );
  37097. var ic = this.parseVertexIndex( c, vLen );
  37098. this.addVertex( ia, ib, ic );
  37099. if ( ua !== undefined && ua !== '' ) {
  37100. var uvLen = this.uvs.length;
  37101. ia = this.parseUVIndex( ua, uvLen );
  37102. ib = this.parseUVIndex( ub, uvLen );
  37103. ic = this.parseUVIndex( uc, uvLen );
  37104. this.addUV( ia, ib, ic );
  37105. }
  37106. if ( na !== undefined && na !== '' ) {
  37107. // Normals are many times the same. If so, skip function call and parseInt.
  37108. var nLen = this.normals.length;
  37109. ia = this.parseNormalIndex( na, nLen );
  37110. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  37111. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  37112. this.addNormal( ia, ib, ic );
  37113. }
  37114. if ( this.colors.length > 0 ) {
  37115. this.addColor( ia, ib, ic );
  37116. }
  37117. },
  37118. addPointGeometry: function ( vertices ) {
  37119. this.object.geometry.type = 'Points';
  37120. var vLen = this.vertices.length;
  37121. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  37122. this.addVertexPoint( this.parseVertexIndex( vertices[ vi ], vLen ) );
  37123. }
  37124. },
  37125. addLineGeometry: function ( vertices, uvs ) {
  37126. this.object.geometry.type = 'Line';
  37127. var vLen = this.vertices.length;
  37128. var uvLen = this.uvs.length;
  37129. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  37130. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  37131. }
  37132. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  37133. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  37134. }
  37135. }
  37136. };
  37137. state.startObject( '', false );
  37138. return state;
  37139. }
  37140. //
  37141. function OBJLoader( manager ) {
  37142. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  37143. this.materials = null;
  37144. }
  37145. OBJLoader.prototype = {
  37146. constructor: OBJLoader,
  37147. load: function ( url, onLoad, onProgress, onError ) {
  37148. var scope = this;
  37149. var loader = new THREE.FileLoader( scope.manager );
  37150. loader.setPath( this.path );
  37151. loader.load( url, function ( text ) {
  37152. onLoad( scope.parse( text ) );
  37153. }, onProgress, onError );
  37154. },
  37155. setPath: function ( value ) {
  37156. this.path = value;
  37157. return this;
  37158. },
  37159. setMaterials: function ( materials ) {
  37160. this.materials = materials;
  37161. return this;
  37162. },
  37163. parse: function ( text ) {
  37164. console.time( 'OBJLoader' );
  37165. var state = new ParserState();
  37166. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  37167. // This is faster than String.split with regex that splits on both
  37168. text = text.replace( /\r\n/g, '\n' );
  37169. }
  37170. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  37171. // join lines separated by a line continuation character (\)
  37172. text = text.replace( /\\\n/g, '' );
  37173. }
  37174. var lines = text.split( '\n' );
  37175. var line = '', lineFirstChar = '';
  37176. var lineLength = 0;
  37177. var result = [];
  37178. // Faster to just trim left side of the line. Use if available.
  37179. var trimLeft = ( typeof ''.trimLeft === 'function' );
  37180. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  37181. line = lines[ i ];
  37182. line = trimLeft ? line.trimLeft() : line.trim();
  37183. lineLength = line.length;
  37184. if ( lineLength === 0 ) continue;
  37185. lineFirstChar = line.charAt( 0 );
  37186. // @todo invoke passed in handler if any
  37187. if ( lineFirstChar === '#' ) continue;
  37188. if ( lineFirstChar === 'v' ) {
  37189. var data = line.split( /\s+/ );
  37190. switch ( data[ 0 ] ) {
  37191. case 'v':
  37192. state.vertices.push(
  37193. parseFloat( data[ 1 ] ),
  37194. parseFloat( data[ 2 ] ),
  37195. parseFloat( data[ 3 ] )
  37196. );
  37197. if ( data.length === 8 ) {
  37198. state.colors.push(
  37199. parseFloat( data[ 4 ] ),
  37200. parseFloat( data[ 5 ] ),
  37201. parseFloat( data[ 6 ] )
  37202. );
  37203. }
  37204. break;
  37205. case 'vn':
  37206. state.normals.push(
  37207. parseFloat( data[ 1 ] ),
  37208. parseFloat( data[ 2 ] ),
  37209. parseFloat( data[ 3 ] )
  37210. );
  37211. break;
  37212. case 'vt':
  37213. state.uvs.push(
  37214. parseFloat( data[ 1 ] ),
  37215. parseFloat( data[ 2 ] )
  37216. );
  37217. break;
  37218. }
  37219. } else if ( lineFirstChar === 'f' ) {
  37220. var lineData = line.substr( 1 ).trim();
  37221. var vertexData = lineData.split( /\s+/ );
  37222. var faceVertices = [];
  37223. // Parse the face vertex data into an easy to work with format
  37224. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  37225. var vertex = vertexData[ j ];
  37226. if ( vertex.length > 0 ) {
  37227. var vertexParts = vertex.split( '/' );
  37228. faceVertices.push( vertexParts );
  37229. }
  37230. }
  37231. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  37232. var v1 = faceVertices[ 0 ];
  37233. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  37234. var v2 = faceVertices[ j ];
  37235. var v3 = faceVertices[ j + 1 ];
  37236. state.addFace(
  37237. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  37238. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  37239. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  37240. );
  37241. }
  37242. } else if ( lineFirstChar === 'l' ) {
  37243. var lineParts = line.substring( 1 ).trim().split( " " );
  37244. var lineVertices = [], lineUVs = [];
  37245. if ( line.indexOf( "/" ) === - 1 ) {
  37246. lineVertices = lineParts;
  37247. } else {
  37248. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  37249. var parts = lineParts[ li ].split( "/" );
  37250. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  37251. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  37252. }
  37253. }
  37254. state.addLineGeometry( lineVertices, lineUVs );
  37255. } else if ( lineFirstChar === 'p' ) {
  37256. var lineData = line.substr( 1 ).trim();
  37257. var pointData = lineData.split( " " );
  37258. state.addPointGeometry( pointData );
  37259. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  37260. // o object_name
  37261. // or
  37262. // g group_name
  37263. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  37264. // var name = result[ 0 ].substr( 1 ).trim();
  37265. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  37266. state.startObject( name );
  37267. } else if ( material_use_pattern.test( line ) ) {
  37268. // material
  37269. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  37270. } else if ( material_library_pattern.test( line ) ) {
  37271. // mtl file
  37272. state.materialLibraries.push( line.substring( 7 ).trim() );
  37273. } else if ( lineFirstChar === 's' ) {
  37274. result = line.split( ' ' );
  37275. // smooth shading
  37276. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  37277. // but does not define a usemtl for each face set.
  37278. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  37279. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  37280. // where explicit usemtl defines geometry groups.
  37281. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  37282. /*
  37283. * http://paulbourke.net/dataformats/obj/
  37284. * or
  37285. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  37286. *
  37287. * From chapter "Grouping" Syntax explanation "s group_number":
  37288. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  37289. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  37290. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  37291. * than 0."
  37292. */
  37293. if ( result.length > 1 ) {
  37294. var value = result[ 1 ].trim().toLowerCase();
  37295. state.object.smooth = ( value !== '0' && value !== 'off' );
  37296. } else {
  37297. // ZBrush can produce "s" lines #11707
  37298. state.object.smooth = true;
  37299. }
  37300. var material = state.object.currentMaterial();
  37301. if ( material ) material.smooth = state.object.smooth;
  37302. } else {
  37303. // Handle null terminated files without exception
  37304. if ( line === '\0' ) continue;
  37305. throw new Error( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  37306. }
  37307. }
  37308. state.finalize();
  37309. var container = new THREE.Group();
  37310. container.materialLibraries = [].concat( state.materialLibraries );
  37311. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  37312. var object = state.objects[ i ];
  37313. var geometry = object.geometry;
  37314. var materials = object.materials;
  37315. var isLine = ( geometry.type === 'Line' );
  37316. var isPoints = ( geometry.type === 'Points' );
  37317. var hasVertexColors = false;
  37318. // Skip o/g line declarations that did not follow with any faces
  37319. if ( geometry.vertices.length === 0 ) continue;
  37320. var buffergeometry = new THREE.BufferGeometry();
  37321. buffergeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  37322. if ( geometry.normals.length > 0 ) {
  37323. buffergeometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  37324. } else {
  37325. buffergeometry.computeVertexNormals();
  37326. }
  37327. if ( geometry.colors.length > 0 ) {
  37328. hasVertexColors = true;
  37329. buffergeometry.addAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  37330. }
  37331. if ( geometry.uvs.length > 0 ) {
  37332. buffergeometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  37333. }
  37334. // Create materials
  37335. var createdMaterials = [];
  37336. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  37337. var sourceMaterial = materials[ mi ];
  37338. var material = undefined;
  37339. if ( this.materials !== null ) {
  37340. material = this.materials.create( sourceMaterial.name );
  37341. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  37342. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  37343. var materialLine = new THREE.LineBasicMaterial();
  37344. materialLine.copy( material );
  37345. materialLine.lights = false; // TOFIX
  37346. material = materialLine;
  37347. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  37348. var materialPoints = new THREE.PointsMaterial( { size: 10, sizeAttenuation: false } );
  37349. materialLine.copy( material );
  37350. material = materialPoints;
  37351. }
  37352. }
  37353. if ( ! material ) {
  37354. if ( isLine ) {
  37355. material = new THREE.LineBasicMaterial();
  37356. } else if ( isPoints ) {
  37357. material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  37358. } else {
  37359. material = new THREE.MeshPhongMaterial();
  37360. }
  37361. material.name = sourceMaterial.name;
  37362. }
  37363. material.flatShading = sourceMaterial.smooth ? false : true;
  37364. material.vertexColors = hasVertexColors ? THREE.VertexColors : THREE.NoColors;
  37365. createdMaterials.push( material );
  37366. }
  37367. // Create mesh
  37368. var mesh;
  37369. if ( createdMaterials.length > 1 ) {
  37370. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  37371. var sourceMaterial = materials[ mi ];
  37372. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  37373. }
  37374. if ( isLine ) {
  37375. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  37376. } else if ( isPoints ) {
  37377. mesh = new THREE.Points( buffergeometry, createdMaterials );
  37378. } else {
  37379. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  37380. }
  37381. } else {
  37382. if ( isLine ) {
  37383. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  37384. } else if ( isPoints ) {
  37385. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  37386. } else {
  37387. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  37388. }
  37389. }
  37390. mesh.name = object.name;
  37391. container.add( mesh );
  37392. }
  37393. console.timeEnd( 'OBJLoader' );
  37394. return container;
  37395. }
  37396. };
  37397. return OBJLoader;
  37398. } )();
  37399. },{}],45:[function(_dereq_,module,exports){
  37400. exports = module.exports = trim;
  37401. function trim(str){
  37402. return str.replace(/^\s*|\s*$/g, '');
  37403. }
  37404. exports.left = function(str){
  37405. return str.replace(/^\s*/, '');
  37406. };
  37407. exports.right = function(str){
  37408. return str.replace(/\s*$/, '');
  37409. };
  37410. },{}],46:[function(_dereq_,module,exports){
  37411. (function (global){
  37412. /**
  37413. * @license
  37414. * webvr-polyfill
  37415. * Copyright (c) 2015-2017 Google
  37416. * Licensed under the Apache License, Version 2.0 (the "License");
  37417. * you may not use this file except in compliance with the License.
  37418. * You may obtain a copy of the License at
  37419. *
  37420. * http://www.apache.org/licenses/LICENSE-2.0
  37421. *
  37422. * Unless required by applicable law or agreed to in writing, software
  37423. * distributed under the License is distributed on an "AS IS" BASIS,
  37424. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37425. * See the License for the specific language governing permissions and
  37426. * limitations under the License.
  37427. */
  37428. /**
  37429. * @license
  37430. * cardboard-vr-display
  37431. * Copyright (c) 2015-2017 Google
  37432. * Licensed under the Apache License, Version 2.0 (the "License");
  37433. * you may not use this file except in compliance with the License.
  37434. * You may obtain a copy of the License at
  37435. *
  37436. * http://www.apache.org/licenses/LICENSE-2.0
  37437. *
  37438. * Unless required by applicable law or agreed to in writing, software
  37439. * distributed under the License is distributed on an "AS IS" BASIS,
  37440. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37441. * See the License for the specific language governing permissions and
  37442. * limitations under the License.
  37443. */
  37444. /**
  37445. * @license
  37446. * webvr-polyfill-dpdb
  37447. * Copyright (c) 2017 Google
  37448. * Licensed under the Apache License, Version 2.0 (the "License");
  37449. * you may not use this file except in compliance with the License.
  37450. * You may obtain a copy of the License at
  37451. *
  37452. * http://www.apache.org/licenses/LICENSE-2.0
  37453. *
  37454. * Unless required by applicable law or agreed to in writing, software
  37455. * distributed under the License is distributed on an "AS IS" BASIS,
  37456. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37457. * See the License for the specific language governing permissions and
  37458. * limitations under the License.
  37459. */
  37460. /**
  37461. * @license
  37462. * wglu-preserve-state
  37463. * Copyright (c) 2016, Brandon Jones.
  37464. *
  37465. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37466. * of this software and associated documentation files (the "Software"), to deal
  37467. * in the Software without restriction, including without limitation the rights
  37468. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37469. * copies of the Software, and to permit persons to whom the Software is
  37470. * furnished to do so, subject to the following conditions:
  37471. *
  37472. * The above copyright notice and this permission notice shall be included in
  37473. * all copies or substantial portions of the Software.
  37474. *
  37475. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37476. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37477. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37478. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37479. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37480. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37481. * THE SOFTWARE.
  37482. */
  37483. /**
  37484. * @license
  37485. * nosleep.js
  37486. * Copyright (c) 2017, Rich Tibbett
  37487. *
  37488. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37489. * of this software and associated documentation files (the "Software"), to deal
  37490. * in the Software without restriction, including without limitation the rights
  37491. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37492. * copies of the Software, and to permit persons to whom the Software is
  37493. * furnished to do so, subject to the following conditions:
  37494. *
  37495. * The above copyright notice and this permission notice shall be included in
  37496. * all copies or substantial portions of the Software.
  37497. *
  37498. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37499. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37500. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37501. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37502. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37503. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37504. * THE SOFTWARE.
  37505. */
  37506. (function (global, factory) {
  37507. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  37508. typeof define === 'function' && define.amd ? define(factory) :
  37509. (global.WebVRPolyfill = factory());
  37510. }(this, (function () { 'use strict';
  37511. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  37512. function unwrapExports (x) {
  37513. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  37514. }
  37515. function createCommonjsModule(fn, module) {
  37516. return module = { exports: {} }, fn(module, module.exports), module.exports;
  37517. }
  37518. var race = function race(promises) {
  37519. if (Promise.race) {
  37520. return Promise.race(promises);
  37521. }
  37522. return new Promise(function (resolve, reject) {
  37523. for (var i = 0; i < promises.length; i++) {
  37524. promises[i].then(resolve, reject);
  37525. }
  37526. });
  37527. };
  37528. var isMobile = function isMobile() {
  37529. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  37530. );
  37531. };
  37532. var copyArray = function copyArray(source, dest) {
  37533. for (var i = 0, n = source.length; i < n; i++) {
  37534. dest[i] = source[i];
  37535. }
  37536. };
  37537. var extend = function extend(dest, src) {
  37538. for (var key in src) {
  37539. if (src.hasOwnProperty(key)) {
  37540. dest[key] = src[key];
  37541. }
  37542. }
  37543. return dest;
  37544. };
  37545. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  37546. /**
  37547. * @license
  37548. * cardboard-vr-display
  37549. * Copyright (c) 2015-2017 Google
  37550. * Licensed under the Apache License, Version 2.0 (the "License");
  37551. * you may not use this file except in compliance with the License.
  37552. * You may obtain a copy of the License at
  37553. *
  37554. * http://www.apache.org/licenses/LICENSE-2.0
  37555. *
  37556. * Unless required by applicable law or agreed to in writing, software
  37557. * distributed under the License is distributed on an "AS IS" BASIS,
  37558. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37559. * See the License for the specific language governing permissions and
  37560. * limitations under the License.
  37561. */
  37562. /**
  37563. * @license
  37564. * gl-preserve-state
  37565. * Copyright (c) 2016, Brandon Jones.
  37566. *
  37567. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37568. * of this software and associated documentation files (the "Software"), to deal
  37569. * in the Software without restriction, including without limitation the rights
  37570. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37571. * copies of the Software, and to permit persons to whom the Software is
  37572. * furnished to do so, subject to the following conditions:
  37573. *
  37574. * The above copyright notice and this permission notice shall be included in
  37575. * all copies or substantial portions of the Software.
  37576. *
  37577. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37578. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37579. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37580. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37581. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37582. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37583. * THE SOFTWARE.
  37584. */
  37585. /**
  37586. * @license
  37587. * webvr-polyfill-dpdb
  37588. * Copyright (c) 2015-2017 Google
  37589. * Licensed under the Apache License, Version 2.0 (the "License");
  37590. * you may not use this file except in compliance with the License.
  37591. * You may obtain a copy of the License at
  37592. *
  37593. * http://www.apache.org/licenses/LICENSE-2.0
  37594. *
  37595. * Unless required by applicable law or agreed to in writing, software
  37596. * distributed under the License is distributed on an "AS IS" BASIS,
  37597. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37598. * See the License for the specific language governing permissions and
  37599. * limitations under the License.
  37600. */
  37601. /**
  37602. * @license
  37603. * nosleep.js
  37604. * Copyright (c) 2017, Rich Tibbett
  37605. *
  37606. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37607. * of this software and associated documentation files (the "Software"), to deal
  37608. * in the Software without restriction, including without limitation the rights
  37609. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37610. * copies of the Software, and to permit persons to whom the Software is
  37611. * furnished to do so, subject to the following conditions:
  37612. *
  37613. * The above copyright notice and this permission notice shall be included in
  37614. * all copies or substantial portions of the Software.
  37615. *
  37616. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37617. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37618. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37619. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37620. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37621. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37622. * THE SOFTWARE.
  37623. */
  37624. (function (global, factory) {
  37625. module.exports = factory();
  37626. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  37627. if (!(instance instanceof Constructor)) {
  37628. throw new TypeError("Cannot call a class as a function");
  37629. }
  37630. };
  37631. var createClass = function () {
  37632. function defineProperties(target, props) {
  37633. for (var i = 0; i < props.length; i++) {
  37634. var descriptor = props[i];
  37635. descriptor.enumerable = descriptor.enumerable || false;
  37636. descriptor.configurable = true;
  37637. if ("value" in descriptor) descriptor.writable = true;
  37638. Object.defineProperty(target, descriptor.key, descriptor);
  37639. }
  37640. }
  37641. return function (Constructor, protoProps, staticProps) {
  37642. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  37643. if (staticProps) defineProperties(Constructor, staticProps);
  37644. return Constructor;
  37645. };
  37646. }();
  37647. var slicedToArray = function () {
  37648. function sliceIterator(arr, i) {
  37649. var _arr = [];
  37650. var _n = true;
  37651. var _d = false;
  37652. var _e = undefined;
  37653. try {
  37654. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  37655. _arr.push(_s.value);
  37656. if (i && _arr.length === i) break;
  37657. }
  37658. } catch (err) {
  37659. _d = true;
  37660. _e = err;
  37661. } finally {
  37662. try {
  37663. if (!_n && _i["return"]) _i["return"]();
  37664. } finally {
  37665. if (_d) throw _e;
  37666. }
  37667. }
  37668. return _arr;
  37669. }
  37670. return function (arr, i) {
  37671. if (Array.isArray(arr)) {
  37672. return arr;
  37673. } else if (Symbol.iterator in Object(arr)) {
  37674. return sliceIterator(arr, i);
  37675. } else {
  37676. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  37677. }
  37678. };
  37679. }();
  37680. var MIN_TIMESTEP = 0.001;
  37681. var MAX_TIMESTEP = 1;
  37682. var base64 = function base64(mimeType, _base) {
  37683. return 'data:' + mimeType + ';base64,' + _base;
  37684. };
  37685. var lerp = function lerp(a, b, t) {
  37686. return a + (b - a) * t;
  37687. };
  37688. var isIOS = function () {
  37689. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  37690. return function () {
  37691. return isIOS;
  37692. };
  37693. }();
  37694. var isWebViewAndroid = function () {
  37695. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  37696. return function () {
  37697. return isWebViewAndroid;
  37698. };
  37699. }();
  37700. var isSafari = function () {
  37701. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  37702. return function () {
  37703. return isSafari;
  37704. };
  37705. }();
  37706. var isFirefoxAndroid = function () {
  37707. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  37708. return function () {
  37709. return isFirefoxAndroid;
  37710. };
  37711. }();
  37712. var getChromeVersion = function () {
  37713. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  37714. var value = match ? parseInt(match[1], 10) : null;
  37715. return function () {
  37716. return value;
  37717. };
  37718. }();
  37719. var isChromeWithoutDeviceMotion = function () {
  37720. var value = false;
  37721. if (getChromeVersion() === 65) {
  37722. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  37723. if (match) {
  37724. var _match$1$split = match[1].split('.'),
  37725. _match$1$split2 = slicedToArray(_match$1$split, 4),
  37726. major = _match$1$split2[0],
  37727. minor = _match$1$split2[1],
  37728. branch = _match$1$split2[2],
  37729. build = _match$1$split2[3];
  37730. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  37731. }
  37732. }
  37733. return function () {
  37734. return value;
  37735. };
  37736. }();
  37737. var isR7 = function () {
  37738. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  37739. return function () {
  37740. return isR7;
  37741. };
  37742. }();
  37743. var isLandscapeMode = function isLandscapeMode() {
  37744. var rtn = window.orientation == 90 || window.orientation == -90;
  37745. return isR7() ? !rtn : rtn;
  37746. };
  37747. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  37748. if (isNaN(timestampDeltaS)) {
  37749. return false;
  37750. }
  37751. if (timestampDeltaS <= MIN_TIMESTEP) {
  37752. return false;
  37753. }
  37754. if (timestampDeltaS > MAX_TIMESTEP) {
  37755. return false;
  37756. }
  37757. return true;
  37758. };
  37759. var getScreenWidth = function getScreenWidth() {
  37760. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  37761. };
  37762. var getScreenHeight = function getScreenHeight() {
  37763. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  37764. };
  37765. var requestFullscreen = function requestFullscreen(element) {
  37766. if (isWebViewAndroid()) {
  37767. return false;
  37768. }
  37769. if (element.requestFullscreen) {
  37770. element.requestFullscreen();
  37771. } else if (element.webkitRequestFullscreen) {
  37772. element.webkitRequestFullscreen();
  37773. } else if (element.mozRequestFullScreen) {
  37774. element.mozRequestFullScreen();
  37775. } else if (element.msRequestFullscreen) {
  37776. element.msRequestFullscreen();
  37777. } else {
  37778. return false;
  37779. }
  37780. return true;
  37781. };
  37782. var exitFullscreen = function exitFullscreen() {
  37783. if (document.exitFullscreen) {
  37784. document.exitFullscreen();
  37785. } else if (document.webkitExitFullscreen) {
  37786. document.webkitExitFullscreen();
  37787. } else if (document.mozCancelFullScreen) {
  37788. document.mozCancelFullScreen();
  37789. } else if (document.msExitFullscreen) {
  37790. document.msExitFullscreen();
  37791. } else {
  37792. return false;
  37793. }
  37794. return true;
  37795. };
  37796. var getFullscreenElement = function getFullscreenElement() {
  37797. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  37798. };
  37799. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  37800. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  37801. gl.shaderSource(vertexShader, vertexSource);
  37802. gl.compileShader(vertexShader);
  37803. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  37804. gl.shaderSource(fragmentShader, fragmentSource);
  37805. gl.compileShader(fragmentShader);
  37806. var program = gl.createProgram();
  37807. gl.attachShader(program, vertexShader);
  37808. gl.attachShader(program, fragmentShader);
  37809. for (var attribName in attribLocationMap) {
  37810. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  37811. }gl.linkProgram(program);
  37812. gl.deleteShader(vertexShader);
  37813. gl.deleteShader(fragmentShader);
  37814. return program;
  37815. };
  37816. var getProgramUniforms = function getProgramUniforms(gl, program) {
  37817. var uniforms = {};
  37818. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  37819. var uniformName = '';
  37820. for (var i = 0; i < uniformCount; i++) {
  37821. var uniformInfo = gl.getActiveUniform(program, i);
  37822. uniformName = uniformInfo.name.replace('[0]', '');
  37823. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  37824. }
  37825. return uniforms;
  37826. };
  37827. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  37828. var lr = 1 / (left - right),
  37829. bt = 1 / (bottom - top),
  37830. nf = 1 / (near - far);
  37831. out[0] = -2 * lr;
  37832. out[1] = 0;
  37833. out[2] = 0;
  37834. out[3] = 0;
  37835. out[4] = 0;
  37836. out[5] = -2 * bt;
  37837. out[6] = 0;
  37838. out[7] = 0;
  37839. out[8] = 0;
  37840. out[9] = 0;
  37841. out[10] = 2 * nf;
  37842. out[11] = 0;
  37843. out[12] = (left + right) * lr;
  37844. out[13] = (top + bottom) * bt;
  37845. out[14] = (far + near) * nf;
  37846. out[15] = 1;
  37847. return out;
  37848. };
  37849. var isMobile = function isMobile() {
  37850. var check = false;
  37851. (function (a) {
  37852. 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;
  37853. })(navigator.userAgent || navigator.vendor || window.opera);
  37854. return check;
  37855. };
  37856. var extend = function extend(dest, src) {
  37857. for (var key in src) {
  37858. if (src.hasOwnProperty(key)) {
  37859. dest[key] = src[key];
  37860. }
  37861. }
  37862. return dest;
  37863. };
  37864. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  37865. if (isIOS()) {
  37866. var width = canvas.style.width;
  37867. var height = canvas.style.height;
  37868. canvas.style.width = parseInt(width) + 1 + 'px';
  37869. canvas.style.height = parseInt(height) + 'px';
  37870. setTimeout(function () {
  37871. canvas.style.width = width;
  37872. canvas.style.height = height;
  37873. }, 100);
  37874. }
  37875. window.canvas = canvas;
  37876. };
  37877. var frameDataFromPose = function () {
  37878. var piOver180 = Math.PI / 180.0;
  37879. var rad45 = Math.PI * 0.25;
  37880. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  37881. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  37882. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  37883. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  37884. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  37885. xScale = 2.0 / (leftTan + rightTan),
  37886. yScale = 2.0 / (upTan + downTan);
  37887. out[0] = xScale;
  37888. out[1] = 0.0;
  37889. out[2] = 0.0;
  37890. out[3] = 0.0;
  37891. out[4] = 0.0;
  37892. out[5] = yScale;
  37893. out[6] = 0.0;
  37894. out[7] = 0.0;
  37895. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  37896. out[9] = (upTan - downTan) * yScale * 0.5;
  37897. out[10] = far / (near - far);
  37898. out[11] = -1.0;
  37899. out[12] = 0.0;
  37900. out[13] = 0.0;
  37901. out[14] = far * near / (near - far);
  37902. out[15] = 0.0;
  37903. return out;
  37904. }
  37905. function mat4_fromRotationTranslation(out, q, v) {
  37906. var x = q[0],
  37907. y = q[1],
  37908. z = q[2],
  37909. w = q[3],
  37910. x2 = x + x,
  37911. y2 = y + y,
  37912. z2 = z + z,
  37913. xx = x * x2,
  37914. xy = x * y2,
  37915. xz = x * z2,
  37916. yy = y * y2,
  37917. yz = y * z2,
  37918. zz = z * z2,
  37919. wx = w * x2,
  37920. wy = w * y2,
  37921. wz = w * z2;
  37922. out[0] = 1 - (yy + zz);
  37923. out[1] = xy + wz;
  37924. out[2] = xz - wy;
  37925. out[3] = 0;
  37926. out[4] = xy - wz;
  37927. out[5] = 1 - (xx + zz);
  37928. out[6] = yz + wx;
  37929. out[7] = 0;
  37930. out[8] = xz + wy;
  37931. out[9] = yz - wx;
  37932. out[10] = 1 - (xx + yy);
  37933. out[11] = 0;
  37934. out[12] = v[0];
  37935. out[13] = v[1];
  37936. out[14] = v[2];
  37937. out[15] = 1;
  37938. return out;
  37939. }
  37940. function mat4_translate(out, a, v) {
  37941. var x = v[0],
  37942. y = v[1],
  37943. z = v[2],
  37944. a00,
  37945. a01,
  37946. a02,
  37947. a03,
  37948. a10,
  37949. a11,
  37950. a12,
  37951. a13,
  37952. a20,
  37953. a21,
  37954. a22,
  37955. a23;
  37956. if (a === out) {
  37957. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  37958. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  37959. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  37960. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  37961. } else {
  37962. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  37963. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  37964. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  37965. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  37966. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  37967. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  37968. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  37969. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  37970. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  37971. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  37972. }
  37973. return out;
  37974. }
  37975. function mat4_invert(out, a) {
  37976. var a00 = a[0],
  37977. a01 = a[1],
  37978. a02 = a[2],
  37979. a03 = a[3],
  37980. a10 = a[4],
  37981. a11 = a[5],
  37982. a12 = a[6],
  37983. a13 = a[7],
  37984. a20 = a[8],
  37985. a21 = a[9],
  37986. a22 = a[10],
  37987. a23 = a[11],
  37988. a30 = a[12],
  37989. a31 = a[13],
  37990. a32 = a[14],
  37991. a33 = a[15],
  37992. b00 = a00 * a11 - a01 * a10,
  37993. b01 = a00 * a12 - a02 * a10,
  37994. b02 = a00 * a13 - a03 * a10,
  37995. b03 = a01 * a12 - a02 * a11,
  37996. b04 = a01 * a13 - a03 * a11,
  37997. b05 = a02 * a13 - a03 * a12,
  37998. b06 = a20 * a31 - a21 * a30,
  37999. b07 = a20 * a32 - a22 * a30,
  38000. b08 = a20 * a33 - a23 * a30,
  38001. b09 = a21 * a32 - a22 * a31,
  38002. b10 = a21 * a33 - a23 * a31,
  38003. b11 = a22 * a33 - a23 * a32,
  38004. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  38005. if (!det) {
  38006. return null;
  38007. }
  38008. det = 1.0 / det;
  38009. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  38010. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  38011. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  38012. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  38013. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  38014. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  38015. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  38016. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  38017. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  38018. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  38019. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  38020. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  38021. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  38022. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  38023. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  38024. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  38025. return out;
  38026. }
  38027. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  38028. var defaultPosition = new Float32Array([0, 0, 0]);
  38029. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  38030. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  38031. var orientation = pose.orientation || defaultOrientation;
  38032. var position = pose.position || defaultPosition;
  38033. mat4_fromRotationTranslation(view, orientation, position);
  38034. if (offset) mat4_translate(view, view, offset);
  38035. mat4_invert(view, view);
  38036. }
  38037. return function (frameData, pose, vrDisplay) {
  38038. if (!frameData || !pose) return false;
  38039. frameData.pose = pose;
  38040. frameData.timestamp = pose.timestamp;
  38041. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  38042. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  38043. return true;
  38044. };
  38045. }();
  38046. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  38047. var isFramed = window.self !== window.top;
  38048. var refOrigin = getOriginFromUrl(document.referrer);
  38049. var thisOrigin = getOriginFromUrl(window.location.href);
  38050. return isFramed && refOrigin !== thisOrigin;
  38051. };
  38052. var getOriginFromUrl = function getOriginFromUrl(url) {
  38053. var domainIdx;
  38054. var protoSepIdx = url.indexOf("://");
  38055. if (protoSepIdx !== -1) {
  38056. domainIdx = protoSepIdx + 3;
  38057. } else {
  38058. domainIdx = 0;
  38059. }
  38060. var domainEndIdx = url.indexOf('/', domainIdx);
  38061. if (domainEndIdx === -1) {
  38062. domainEndIdx = url.length;
  38063. }
  38064. return url.substring(0, domainEndIdx);
  38065. };
  38066. var getQuaternionAngle = function getQuaternionAngle(quat) {
  38067. if (quat.w > 1) {
  38068. console.warn('getQuaternionAngle: w > 1');
  38069. return 0;
  38070. }
  38071. var angle = 2 * Math.acos(quat.w);
  38072. return angle;
  38073. };
  38074. var warnOnce = function () {
  38075. var observedWarnings = {};
  38076. return function (key, message) {
  38077. if (observedWarnings[key] === undefined) {
  38078. console.warn('webvr-polyfill: ' + message);
  38079. observedWarnings[key] = true;
  38080. }
  38081. };
  38082. }();
  38083. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  38084. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  38085. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  38086. };
  38087. function WGLUPreserveGLState(gl, bindings, callback) {
  38088. if (!bindings) {
  38089. callback(gl);
  38090. return;
  38091. }
  38092. var boundValues = [];
  38093. var activeTexture = null;
  38094. for (var i = 0; i < bindings.length; ++i) {
  38095. var binding = bindings[i];
  38096. switch (binding) {
  38097. case gl.TEXTURE_BINDING_2D:
  38098. case gl.TEXTURE_BINDING_CUBE_MAP:
  38099. var textureUnit = bindings[++i];
  38100. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  38101. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  38102. boundValues.push(null, null);
  38103. break;
  38104. }
  38105. if (!activeTexture) {
  38106. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  38107. }
  38108. gl.activeTexture(textureUnit);
  38109. boundValues.push(gl.getParameter(binding), null);
  38110. break;
  38111. case gl.ACTIVE_TEXTURE:
  38112. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  38113. boundValues.push(null);
  38114. break;
  38115. default:
  38116. boundValues.push(gl.getParameter(binding));
  38117. break;
  38118. }
  38119. }
  38120. callback(gl);
  38121. for (var i = 0; i < bindings.length; ++i) {
  38122. var binding = bindings[i];
  38123. var boundValue = boundValues[i];
  38124. switch (binding) {
  38125. case gl.ACTIVE_TEXTURE:
  38126. break;
  38127. case gl.ARRAY_BUFFER_BINDING:
  38128. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  38129. break;
  38130. case gl.COLOR_CLEAR_VALUE:
  38131. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38132. break;
  38133. case gl.COLOR_WRITEMASK:
  38134. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38135. break;
  38136. case gl.CURRENT_PROGRAM:
  38137. gl.useProgram(boundValue);
  38138. break;
  38139. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  38140. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  38141. break;
  38142. case gl.FRAMEBUFFER_BINDING:
  38143. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  38144. break;
  38145. case gl.RENDERBUFFER_BINDING:
  38146. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  38147. break;
  38148. case gl.TEXTURE_BINDING_2D:
  38149. var textureUnit = bindings[++i];
  38150. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38151. break;
  38152. gl.activeTexture(textureUnit);
  38153. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  38154. break;
  38155. case gl.TEXTURE_BINDING_CUBE_MAP:
  38156. var textureUnit = bindings[++i];
  38157. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38158. break;
  38159. gl.activeTexture(textureUnit);
  38160. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  38161. break;
  38162. case gl.VIEWPORT:
  38163. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38164. break;
  38165. case gl.BLEND:
  38166. case gl.CULL_FACE:
  38167. case gl.DEPTH_TEST:
  38168. case gl.SCISSOR_TEST:
  38169. case gl.STENCIL_TEST:
  38170. if (boundValue) {
  38171. gl.enable(binding);
  38172. } else {
  38173. gl.disable(binding);
  38174. }
  38175. break;
  38176. default:
  38177. console.log("No GL restore behavior for 0x" + binding.toString(16));
  38178. break;
  38179. }
  38180. if (activeTexture) {
  38181. gl.activeTexture(activeTexture);
  38182. }
  38183. }
  38184. }
  38185. var glPreserveState = WGLUPreserveGLState;
  38186. 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');
  38187. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  38188. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  38189. this.gl = gl;
  38190. this.cardboardUI = cardboardUI;
  38191. this.bufferScale = bufferScale;
  38192. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  38193. this.ctxAttribs = gl.getContextAttributes();
  38194. this.meshWidth = 20;
  38195. this.meshHeight = 20;
  38196. this.bufferWidth = gl.drawingBufferWidth;
  38197. this.bufferHeight = gl.drawingBufferHeight;
  38198. this.realBindFramebuffer = gl.bindFramebuffer;
  38199. this.realEnable = gl.enable;
  38200. this.realDisable = gl.disable;
  38201. this.realColorMask = gl.colorMask;
  38202. this.realClearColor = gl.clearColor;
  38203. this.realViewport = gl.viewport;
  38204. if (!isIOS()) {
  38205. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  38206. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  38207. }
  38208. this.isPatched = false;
  38209. this.lastBoundFramebuffer = null;
  38210. this.cullFace = false;
  38211. this.depthTest = false;
  38212. this.blend = false;
  38213. this.scissorTest = false;
  38214. this.stencilTest = false;
  38215. this.viewport = [0, 0, 0, 0];
  38216. this.colorMask = [true, true, true, true];
  38217. this.clearColor = [0, 0, 0, 0];
  38218. this.attribs = {
  38219. position: 0,
  38220. texCoord: 1
  38221. };
  38222. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  38223. this.uniforms = getProgramUniforms(gl, this.program);
  38224. this.viewportOffsetScale = new Float32Array(8);
  38225. this.setTextureBounds();
  38226. this.vertexBuffer = gl.createBuffer();
  38227. this.indexBuffer = gl.createBuffer();
  38228. this.indexCount = 0;
  38229. this.renderTarget = gl.createTexture();
  38230. this.framebuffer = gl.createFramebuffer();
  38231. this.depthStencilBuffer = null;
  38232. this.depthBuffer = null;
  38233. this.stencilBuffer = null;
  38234. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  38235. this.depthStencilBuffer = gl.createRenderbuffer();
  38236. } else if (this.ctxAttribs.depth) {
  38237. this.depthBuffer = gl.createRenderbuffer();
  38238. } else if (this.ctxAttribs.stencil) {
  38239. this.stencilBuffer = gl.createRenderbuffer();
  38240. }
  38241. this.patch();
  38242. this.onResize();
  38243. }
  38244. CardboardDistorter.prototype.destroy = function () {
  38245. var gl = this.gl;
  38246. this.unpatch();
  38247. gl.deleteProgram(this.program);
  38248. gl.deleteBuffer(this.vertexBuffer);
  38249. gl.deleteBuffer(this.indexBuffer);
  38250. gl.deleteTexture(this.renderTarget);
  38251. gl.deleteFramebuffer(this.framebuffer);
  38252. if (this.depthStencilBuffer) {
  38253. gl.deleteRenderbuffer(this.depthStencilBuffer);
  38254. }
  38255. if (this.depthBuffer) {
  38256. gl.deleteRenderbuffer(this.depthBuffer);
  38257. }
  38258. if (this.stencilBuffer) {
  38259. gl.deleteRenderbuffer(this.stencilBuffer);
  38260. }
  38261. if (this.cardboardUI) {
  38262. this.cardboardUI.destroy();
  38263. }
  38264. };
  38265. CardboardDistorter.prototype.onResize = function () {
  38266. var gl = this.gl;
  38267. var self = this;
  38268. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  38269. glPreserveState(gl, glState, function (gl) {
  38270. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  38271. if (self.scissorTest) {
  38272. self.realDisable.call(gl, gl.SCISSOR_TEST);
  38273. }
  38274. self.realColorMask.call(gl, true, true, true, true);
  38275. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  38276. self.realClearColor.call(gl, 0, 0, 0, 1);
  38277. gl.clear(gl.COLOR_BUFFER_BIT);
  38278. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  38279. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  38280. 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);
  38281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  38282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  38283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  38284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  38285. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  38286. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  38287. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  38288. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  38289. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  38290. } else if (self.ctxAttribs.depth) {
  38291. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  38292. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  38293. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  38294. } else if (self.ctxAttribs.stencil) {
  38295. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  38296. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  38297. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  38298. }
  38299. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  38300. console.error('Framebuffer incomplete!');
  38301. }
  38302. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  38303. if (self.scissorTest) {
  38304. self.realEnable.call(gl, gl.SCISSOR_TEST);
  38305. }
  38306. self.realColorMask.apply(gl, self.colorMask);
  38307. self.realViewport.apply(gl, self.viewport);
  38308. self.realClearColor.apply(gl, self.clearColor);
  38309. });
  38310. if (this.cardboardUI) {
  38311. this.cardboardUI.onResize();
  38312. }
  38313. };
  38314. CardboardDistorter.prototype.patch = function () {
  38315. if (this.isPatched) {
  38316. return;
  38317. }
  38318. var self = this;
  38319. var canvas = this.gl.canvas;
  38320. var gl = this.gl;
  38321. if (!isIOS()) {
  38322. canvas.width = getScreenWidth() * this.bufferScale;
  38323. canvas.height = getScreenHeight() * this.bufferScale;
  38324. Object.defineProperty(canvas, 'width', {
  38325. configurable: true,
  38326. enumerable: true,
  38327. get: function get() {
  38328. return self.bufferWidth;
  38329. },
  38330. set: function set(value) {
  38331. self.bufferWidth = value;
  38332. self.realCanvasWidth.set.call(canvas, value);
  38333. self.onResize();
  38334. }
  38335. });
  38336. Object.defineProperty(canvas, 'height', {
  38337. configurable: true,
  38338. enumerable: true,
  38339. get: function get() {
  38340. return self.bufferHeight;
  38341. },
  38342. set: function set(value) {
  38343. self.bufferHeight = value;
  38344. self.realCanvasHeight.set.call(canvas, value);
  38345. self.onResize();
  38346. }
  38347. });
  38348. }
  38349. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  38350. if (this.lastBoundFramebuffer == null) {
  38351. this.lastBoundFramebuffer = this.framebuffer;
  38352. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  38353. }
  38354. this.gl.bindFramebuffer = function (target, framebuffer) {
  38355. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  38356. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  38357. };
  38358. this.cullFace = gl.getParameter(gl.CULL_FACE);
  38359. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  38360. this.blend = gl.getParameter(gl.BLEND);
  38361. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  38362. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  38363. gl.enable = function (pname) {
  38364. switch (pname) {
  38365. case gl.CULL_FACE:
  38366. self.cullFace = true;break;
  38367. case gl.DEPTH_TEST:
  38368. self.depthTest = true;break;
  38369. case gl.BLEND:
  38370. self.blend = true;break;
  38371. case gl.SCISSOR_TEST:
  38372. self.scissorTest = true;break;
  38373. case gl.STENCIL_TEST:
  38374. self.stencilTest = true;break;
  38375. }
  38376. self.realEnable.call(gl, pname);
  38377. };
  38378. gl.disable = function (pname) {
  38379. switch (pname) {
  38380. case gl.CULL_FACE:
  38381. self.cullFace = false;break;
  38382. case gl.DEPTH_TEST:
  38383. self.depthTest = false;break;
  38384. case gl.BLEND:
  38385. self.blend = false;break;
  38386. case gl.SCISSOR_TEST:
  38387. self.scissorTest = false;break;
  38388. case gl.STENCIL_TEST:
  38389. self.stencilTest = false;break;
  38390. }
  38391. self.realDisable.call(gl, pname);
  38392. };
  38393. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  38394. gl.colorMask = function (r, g, b, a) {
  38395. self.colorMask[0] = r;
  38396. self.colorMask[1] = g;
  38397. self.colorMask[2] = b;
  38398. self.colorMask[3] = a;
  38399. self.realColorMask.call(gl, r, g, b, a);
  38400. };
  38401. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  38402. gl.clearColor = function (r, g, b, a) {
  38403. self.clearColor[0] = r;
  38404. self.clearColor[1] = g;
  38405. self.clearColor[2] = b;
  38406. self.clearColor[3] = a;
  38407. self.realClearColor.call(gl, r, g, b, a);
  38408. };
  38409. this.viewport = gl.getParameter(gl.VIEWPORT);
  38410. gl.viewport = function (x, y, w, h) {
  38411. self.viewport[0] = x;
  38412. self.viewport[1] = y;
  38413. self.viewport[2] = w;
  38414. self.viewport[3] = h;
  38415. self.realViewport.call(gl, x, y, w, h);
  38416. };
  38417. this.isPatched = true;
  38418. safariCssSizeWorkaround(canvas);
  38419. };
  38420. CardboardDistorter.prototype.unpatch = function () {
  38421. if (!this.isPatched) {
  38422. return;
  38423. }
  38424. var gl = this.gl;
  38425. var canvas = this.gl.canvas;
  38426. if (!isIOS()) {
  38427. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  38428. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  38429. }
  38430. canvas.width = this.bufferWidth;
  38431. canvas.height = this.bufferHeight;
  38432. gl.bindFramebuffer = this.realBindFramebuffer;
  38433. gl.enable = this.realEnable;
  38434. gl.disable = this.realDisable;
  38435. gl.colorMask = this.realColorMask;
  38436. gl.clearColor = this.realClearColor;
  38437. gl.viewport = this.realViewport;
  38438. if (this.lastBoundFramebuffer == this.framebuffer) {
  38439. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  38440. }
  38441. this.isPatched = false;
  38442. setTimeout(function () {
  38443. safariCssSizeWorkaround(canvas);
  38444. }, 1);
  38445. };
  38446. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  38447. if (!leftBounds) {
  38448. leftBounds = [0, 0, 0.5, 1];
  38449. }
  38450. if (!rightBounds) {
  38451. rightBounds = [0.5, 0, 0.5, 1];
  38452. }
  38453. this.viewportOffsetScale[0] = leftBounds[0];
  38454. this.viewportOffsetScale[1] = leftBounds[1];
  38455. this.viewportOffsetScale[2] = leftBounds[2];
  38456. this.viewportOffsetScale[3] = leftBounds[3];
  38457. this.viewportOffsetScale[4] = rightBounds[0];
  38458. this.viewportOffsetScale[5] = rightBounds[1];
  38459. this.viewportOffsetScale[6] = rightBounds[2];
  38460. this.viewportOffsetScale[7] = rightBounds[3];
  38461. };
  38462. CardboardDistorter.prototype.submitFrame = function () {
  38463. var gl = this.gl;
  38464. var self = this;
  38465. var glState = [];
  38466. if (!this.dirtySubmitFrameBindings) {
  38467. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  38468. }
  38469. glPreserveState(gl, glState, function (gl) {
  38470. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  38471. if (self.cullFace) {
  38472. self.realDisable.call(gl, gl.CULL_FACE);
  38473. }
  38474. if (self.depthTest) {
  38475. self.realDisable.call(gl, gl.DEPTH_TEST);
  38476. }
  38477. if (self.blend) {
  38478. self.realDisable.call(gl, gl.BLEND);
  38479. }
  38480. if (self.scissorTest) {
  38481. self.realDisable.call(gl, gl.SCISSOR_TEST);
  38482. }
  38483. if (self.stencilTest) {
  38484. self.realDisable.call(gl, gl.STENCIL_TEST);
  38485. }
  38486. self.realColorMask.call(gl, true, true, true, true);
  38487. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  38488. if (self.ctxAttribs.alpha || isIOS()) {
  38489. self.realClearColor.call(gl, 0, 0, 0, 1);
  38490. gl.clear(gl.COLOR_BUFFER_BIT);
  38491. }
  38492. gl.useProgram(self.program);
  38493. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  38494. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38495. gl.enableVertexAttribArray(self.attribs.position);
  38496. gl.enableVertexAttribArray(self.attribs.texCoord);
  38497. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  38498. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  38499. gl.activeTexture(gl.TEXTURE0);
  38500. gl.uniform1i(self.uniforms.diffuse, 0);
  38501. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  38502. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  38503. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  38504. if (self.cardboardUI) {
  38505. self.cardboardUI.renderNoState();
  38506. }
  38507. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  38508. if (!self.ctxAttribs.preserveDrawingBuffer) {
  38509. self.realClearColor.call(gl, 0, 0, 0, 0);
  38510. gl.clear(gl.COLOR_BUFFER_BIT);
  38511. }
  38512. if (!self.dirtySubmitFrameBindings) {
  38513. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  38514. }
  38515. if (self.cullFace) {
  38516. self.realEnable.call(gl, gl.CULL_FACE);
  38517. }
  38518. if (self.depthTest) {
  38519. self.realEnable.call(gl, gl.DEPTH_TEST);
  38520. }
  38521. if (self.blend) {
  38522. self.realEnable.call(gl, gl.BLEND);
  38523. }
  38524. if (self.scissorTest) {
  38525. self.realEnable.call(gl, gl.SCISSOR_TEST);
  38526. }
  38527. if (self.stencilTest) {
  38528. self.realEnable.call(gl, gl.STENCIL_TEST);
  38529. }
  38530. self.realColorMask.apply(gl, self.colorMask);
  38531. self.realViewport.apply(gl, self.viewport);
  38532. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  38533. self.realClearColor.apply(gl, self.clearColor);
  38534. }
  38535. });
  38536. if (isIOS()) {
  38537. var canvas = gl.canvas;
  38538. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  38539. self.bufferWidth = canvas.width;
  38540. self.bufferHeight = canvas.height;
  38541. self.onResize();
  38542. }
  38543. }
  38544. };
  38545. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  38546. var gl = this.gl;
  38547. var self = this;
  38548. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  38549. glPreserveState(gl, glState, function (gl) {
  38550. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  38551. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38552. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  38553. if (!self.indexCount) {
  38554. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  38555. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  38556. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  38557. self.indexCount = indices.length;
  38558. }
  38559. });
  38560. };
  38561. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  38562. var vertices = new Float32Array(2 * width * height * 5);
  38563. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  38564. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  38565. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  38566. var vidx = 0;
  38567. for (var e = 0; e < 2; e++) {
  38568. for (var j = 0; j < height; j++) {
  38569. for (var i = 0; i < width; i++, vidx++) {
  38570. var u = i / (width - 1);
  38571. var v = j / (height - 1);
  38572. var s = u;
  38573. var t = v;
  38574. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  38575. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  38576. var d = Math.sqrt(x * x + y * y);
  38577. var r = deviceInfo.distortion.distortInverse(d);
  38578. var p = x * r / d;
  38579. var q = y * r / d;
  38580. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  38581. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  38582. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  38583. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  38584. vertices[vidx * 5 + 0] = u;
  38585. vertices[vidx * 5 + 1] = v;
  38586. vertices[vidx * 5 + 2] = s;
  38587. vertices[vidx * 5 + 3] = t;
  38588. vertices[vidx * 5 + 4] = e;
  38589. }
  38590. }
  38591. var w = lensFrustum[2] - lensFrustum[0];
  38592. lensFrustum[0] = -(w + lensFrustum[0]);
  38593. lensFrustum[2] = w - lensFrustum[2];
  38594. w = noLensFrustum[2] - noLensFrustum[0];
  38595. noLensFrustum[0] = -(w + noLensFrustum[0]);
  38596. noLensFrustum[2] = w - noLensFrustum[2];
  38597. viewport.x = 1 - (viewport.x + viewport.width);
  38598. }
  38599. return vertices;
  38600. };
  38601. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  38602. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  38603. var halfwidth = width / 2;
  38604. var halfheight = height / 2;
  38605. var vidx = 0;
  38606. var iidx = 0;
  38607. for (var e = 0; e < 2; e++) {
  38608. for (var j = 0; j < height; j++) {
  38609. for (var i = 0; i < width; i++, vidx++) {
  38610. if (i == 0 || j == 0) continue;
  38611. if (i <= halfwidth == j <= halfheight) {
  38612. indices[iidx++] = vidx;
  38613. indices[iidx++] = vidx - width - 1;
  38614. indices[iidx++] = vidx - width;
  38615. indices[iidx++] = vidx - width - 1;
  38616. indices[iidx++] = vidx;
  38617. indices[iidx++] = vidx - 1;
  38618. } else {
  38619. indices[iidx++] = vidx - 1;
  38620. indices[iidx++] = vidx - width;
  38621. indices[iidx++] = vidx;
  38622. indices[iidx++] = vidx - width;
  38623. indices[iidx++] = vidx - 1;
  38624. indices[iidx++] = vidx - width - 1;
  38625. }
  38626. }
  38627. }
  38628. }
  38629. return indices;
  38630. };
  38631. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  38632. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  38633. if (descriptor.get === undefined || descriptor.set === undefined) {
  38634. descriptor.configurable = true;
  38635. descriptor.enumerable = true;
  38636. descriptor.get = function () {
  38637. return this.getAttribute(attrName);
  38638. };
  38639. descriptor.set = function (val) {
  38640. this.setAttribute(attrName, val);
  38641. };
  38642. }
  38643. return descriptor;
  38644. };
  38645. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  38646. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  38647. var DEG2RAD = Math.PI / 180.0;
  38648. var kAnglePerGearSection = 60;
  38649. var kOuterRimEndAngle = 12;
  38650. var kInnerRimBeginAngle = 20;
  38651. var kOuterRadius = 1;
  38652. var kMiddleRadius = 0.75;
  38653. var kInnerRadius = 0.3125;
  38654. var kCenterLineThicknessDp = 4;
  38655. var kButtonWidthDp = 28;
  38656. var kTouchSlopFactor = 1.5;
  38657. function CardboardUI(gl) {
  38658. this.gl = gl;
  38659. this.attribs = {
  38660. position: 0
  38661. };
  38662. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  38663. this.uniforms = getProgramUniforms(gl, this.program);
  38664. this.vertexBuffer = gl.createBuffer();
  38665. this.gearOffset = 0;
  38666. this.gearVertexCount = 0;
  38667. this.arrowOffset = 0;
  38668. this.arrowVertexCount = 0;
  38669. this.projMat = new Float32Array(16);
  38670. this.listener = null;
  38671. this.onResize();
  38672. }
  38673. CardboardUI.prototype.destroy = function () {
  38674. var gl = this.gl;
  38675. if (this.listener) {
  38676. gl.canvas.removeEventListener('click', this.listener, false);
  38677. }
  38678. gl.deleteProgram(this.program);
  38679. gl.deleteBuffer(this.vertexBuffer);
  38680. };
  38681. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  38682. var canvas = this.gl.canvas;
  38683. this.listener = function (event) {
  38684. var midline = canvas.clientWidth / 2;
  38685. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  38686. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  38687. optionsCallback(event);
  38688. }
  38689. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  38690. backCallback(event);
  38691. }
  38692. };
  38693. canvas.addEventListener('click', this.listener, false);
  38694. };
  38695. CardboardUI.prototype.onResize = function () {
  38696. var gl = this.gl;
  38697. var self = this;
  38698. var glState = [gl.ARRAY_BUFFER_BINDING];
  38699. glPreserveState(gl, glState, function (gl) {
  38700. var vertices = [];
  38701. var midline = gl.drawingBufferWidth / 2;
  38702. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  38703. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  38704. var dps = scalingRatio * window.devicePixelRatio;
  38705. var lineWidth = kCenterLineThicknessDp * dps / 2;
  38706. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  38707. var buttonScale = kButtonWidthDp * dps / 2;
  38708. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  38709. vertices.push(midline - lineWidth, buttonSize);
  38710. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  38711. vertices.push(midline + lineWidth, buttonSize);
  38712. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  38713. self.gearOffset = vertices.length / 2;
  38714. function addGearSegment(theta, r) {
  38715. var angle = (90 - theta) * DEG2RAD;
  38716. var x = Math.cos(angle);
  38717. var y = Math.sin(angle);
  38718. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  38719. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  38720. }
  38721. for (var i = 0; i <= 6; i++) {
  38722. var segmentTheta = i * kAnglePerGearSection;
  38723. addGearSegment(segmentTheta, kOuterRadius);
  38724. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  38725. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  38726. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  38727. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  38728. }
  38729. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  38730. self.arrowOffset = vertices.length / 2;
  38731. function addArrowVertex(x, y) {
  38732. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  38733. }
  38734. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  38735. addArrowVertex(0, buttonScale);
  38736. addArrowVertex(buttonScale, 0);
  38737. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  38738. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  38739. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  38740. addArrowVertex(0, buttonScale);
  38741. addArrowVertex(buttonScale, buttonScale * 2);
  38742. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  38743. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  38744. addArrowVertex(0, buttonScale);
  38745. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  38746. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  38747. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  38748. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  38749. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  38750. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38751. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  38752. });
  38753. };
  38754. CardboardUI.prototype.render = function () {
  38755. var gl = this.gl;
  38756. var self = this;
  38757. 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];
  38758. glPreserveState(gl, glState, function (gl) {
  38759. gl.disable(gl.CULL_FACE);
  38760. gl.disable(gl.DEPTH_TEST);
  38761. gl.disable(gl.BLEND);
  38762. gl.disable(gl.SCISSOR_TEST);
  38763. gl.disable(gl.STENCIL_TEST);
  38764. gl.colorMask(true, true, true, true);
  38765. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  38766. self.renderNoState();
  38767. });
  38768. };
  38769. CardboardUI.prototype.renderNoState = function () {
  38770. var gl = this.gl;
  38771. gl.useProgram(this.program);
  38772. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  38773. gl.enableVertexAttribArray(this.attribs.position);
  38774. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  38775. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  38776. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  38777. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  38778. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  38779. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  38780. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  38781. };
  38782. function Distortion(coefficients) {
  38783. this.coefficients = coefficients;
  38784. }
  38785. Distortion.prototype.distortInverse = function (radius) {
  38786. var r0 = 0;
  38787. var r1 = 1;
  38788. var dr0 = radius - this.distort(r0);
  38789. while (Math.abs(r1 - r0) > 0.0001 ) {
  38790. var dr1 = radius - this.distort(r1);
  38791. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  38792. r0 = r1;
  38793. r1 = r2;
  38794. dr0 = dr1;
  38795. }
  38796. return r1;
  38797. };
  38798. Distortion.prototype.distort = function (radius) {
  38799. var r2 = radius * radius;
  38800. var ret = 0;
  38801. for (var i = 0; i < this.coefficients.length; i++) {
  38802. ret = r2 * (ret + this.coefficients[i]);
  38803. }
  38804. return (ret + 1) * radius;
  38805. };
  38806. var degToRad = Math.PI / 180;
  38807. var radToDeg = 180 / Math.PI;
  38808. var Vector3 = function Vector3(x, y, z) {
  38809. this.x = x || 0;
  38810. this.y = y || 0;
  38811. this.z = z || 0;
  38812. };
  38813. Vector3.prototype = {
  38814. constructor: Vector3,
  38815. set: function set(x, y, z) {
  38816. this.x = x;
  38817. this.y = y;
  38818. this.z = z;
  38819. return this;
  38820. },
  38821. copy: function copy(v) {
  38822. this.x = v.x;
  38823. this.y = v.y;
  38824. this.z = v.z;
  38825. return this;
  38826. },
  38827. length: function length() {
  38828. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  38829. },
  38830. normalize: function normalize() {
  38831. var scalar = this.length();
  38832. if (scalar !== 0) {
  38833. var invScalar = 1 / scalar;
  38834. this.multiplyScalar(invScalar);
  38835. } else {
  38836. this.x = 0;
  38837. this.y = 0;
  38838. this.z = 0;
  38839. }
  38840. return this;
  38841. },
  38842. multiplyScalar: function multiplyScalar(scalar) {
  38843. this.x *= scalar;
  38844. this.y *= scalar;
  38845. this.z *= scalar;
  38846. },
  38847. applyQuaternion: function applyQuaternion(q) {
  38848. var x = this.x;
  38849. var y = this.y;
  38850. var z = this.z;
  38851. var qx = q.x;
  38852. var qy = q.y;
  38853. var qz = q.z;
  38854. var qw = q.w;
  38855. var ix = qw * x + qy * z - qz * y;
  38856. var iy = qw * y + qz * x - qx * z;
  38857. var iz = qw * z + qx * y - qy * x;
  38858. var iw = -qx * x - qy * y - qz * z;
  38859. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  38860. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  38861. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  38862. return this;
  38863. },
  38864. dot: function dot(v) {
  38865. return this.x * v.x + this.y * v.y + this.z * v.z;
  38866. },
  38867. crossVectors: function crossVectors(a, b) {
  38868. var ax = a.x,
  38869. ay = a.y,
  38870. az = a.z;
  38871. var bx = b.x,
  38872. by = b.y,
  38873. bz = b.z;
  38874. this.x = ay * bz - az * by;
  38875. this.y = az * bx - ax * bz;
  38876. this.z = ax * by - ay * bx;
  38877. return this;
  38878. }
  38879. };
  38880. var Quaternion = function Quaternion(x, y, z, w) {
  38881. this.x = x || 0;
  38882. this.y = y || 0;
  38883. this.z = z || 0;
  38884. this.w = w !== undefined ? w : 1;
  38885. };
  38886. Quaternion.prototype = {
  38887. constructor: Quaternion,
  38888. set: function set(x, y, z, w) {
  38889. this.x = x;
  38890. this.y = y;
  38891. this.z = z;
  38892. this.w = w;
  38893. return this;
  38894. },
  38895. copy: function copy(quaternion) {
  38896. this.x = quaternion.x;
  38897. this.y = quaternion.y;
  38898. this.z = quaternion.z;
  38899. this.w = quaternion.w;
  38900. return this;
  38901. },
  38902. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  38903. var c1 = Math.cos(x / 2);
  38904. var c2 = Math.cos(y / 2);
  38905. var c3 = Math.cos(z / 2);
  38906. var s1 = Math.sin(x / 2);
  38907. var s2 = Math.sin(y / 2);
  38908. var s3 = Math.sin(z / 2);
  38909. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  38910. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  38911. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  38912. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  38913. return this;
  38914. },
  38915. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  38916. var c1 = Math.cos(x / 2);
  38917. var c2 = Math.cos(y / 2);
  38918. var c3 = Math.cos(z / 2);
  38919. var s1 = Math.sin(x / 2);
  38920. var s2 = Math.sin(y / 2);
  38921. var s3 = Math.sin(z / 2);
  38922. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  38923. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  38924. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  38925. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  38926. return this;
  38927. },
  38928. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  38929. var halfAngle = angle / 2,
  38930. s = Math.sin(halfAngle);
  38931. this.x = axis.x * s;
  38932. this.y = axis.y * s;
  38933. this.z = axis.z * s;
  38934. this.w = Math.cos(halfAngle);
  38935. return this;
  38936. },
  38937. multiply: function multiply(q) {
  38938. return this.multiplyQuaternions(this, q);
  38939. },
  38940. multiplyQuaternions: function multiplyQuaternions(a, b) {
  38941. var qax = a.x,
  38942. qay = a.y,
  38943. qaz = a.z,
  38944. qaw = a.w;
  38945. var qbx = b.x,
  38946. qby = b.y,
  38947. qbz = b.z,
  38948. qbw = b.w;
  38949. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  38950. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  38951. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  38952. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  38953. return this;
  38954. },
  38955. inverse: function inverse() {
  38956. this.x *= -1;
  38957. this.y *= -1;
  38958. this.z *= -1;
  38959. this.normalize();
  38960. return this;
  38961. },
  38962. normalize: function normalize() {
  38963. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  38964. if (l === 0) {
  38965. this.x = 0;
  38966. this.y = 0;
  38967. this.z = 0;
  38968. this.w = 1;
  38969. } else {
  38970. l = 1 / l;
  38971. this.x = this.x * l;
  38972. this.y = this.y * l;
  38973. this.z = this.z * l;
  38974. this.w = this.w * l;
  38975. }
  38976. return this;
  38977. },
  38978. slerp: function slerp(qb, t) {
  38979. if (t === 0) return this;
  38980. if (t === 1) return this.copy(qb);
  38981. var x = this.x,
  38982. y = this.y,
  38983. z = this.z,
  38984. w = this.w;
  38985. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  38986. if (cosHalfTheta < 0) {
  38987. this.w = -qb.w;
  38988. this.x = -qb.x;
  38989. this.y = -qb.y;
  38990. this.z = -qb.z;
  38991. cosHalfTheta = -cosHalfTheta;
  38992. } else {
  38993. this.copy(qb);
  38994. }
  38995. if (cosHalfTheta >= 1.0) {
  38996. this.w = w;
  38997. this.x = x;
  38998. this.y = y;
  38999. this.z = z;
  39000. return this;
  39001. }
  39002. var halfTheta = Math.acos(cosHalfTheta);
  39003. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  39004. if (Math.abs(sinHalfTheta) < 0.001) {
  39005. this.w = 0.5 * (w + this.w);
  39006. this.x = 0.5 * (x + this.x);
  39007. this.y = 0.5 * (y + this.y);
  39008. this.z = 0.5 * (z + this.z);
  39009. return this;
  39010. }
  39011. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  39012. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  39013. this.w = w * ratioA + this.w * ratioB;
  39014. this.x = x * ratioA + this.x * ratioB;
  39015. this.y = y * ratioA + this.y * ratioB;
  39016. this.z = z * ratioA + this.z * ratioB;
  39017. return this;
  39018. },
  39019. setFromUnitVectors: function () {
  39020. var v1, r;
  39021. var EPS = 0.000001;
  39022. return function (vFrom, vTo) {
  39023. if (v1 === undefined) v1 = new Vector3();
  39024. r = vFrom.dot(vTo) + 1;
  39025. if (r < EPS) {
  39026. r = 0;
  39027. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  39028. v1.set(-vFrom.y, vFrom.x, 0);
  39029. } else {
  39030. v1.set(0, -vFrom.z, vFrom.y);
  39031. }
  39032. } else {
  39033. v1.crossVectors(vFrom, vTo);
  39034. }
  39035. this.x = v1.x;
  39036. this.y = v1.y;
  39037. this.z = v1.z;
  39038. this.w = r;
  39039. this.normalize();
  39040. return this;
  39041. };
  39042. }()
  39043. };
  39044. function Device(params) {
  39045. this.width = params.width || getScreenWidth();
  39046. this.height = params.height || getScreenHeight();
  39047. this.widthMeters = params.widthMeters;
  39048. this.heightMeters = params.heightMeters;
  39049. this.bevelMeters = params.bevelMeters;
  39050. }
  39051. var DEFAULT_ANDROID = new Device({
  39052. widthMeters: 0.110,
  39053. heightMeters: 0.062,
  39054. bevelMeters: 0.004
  39055. });
  39056. var DEFAULT_IOS = new Device({
  39057. widthMeters: 0.1038,
  39058. heightMeters: 0.0584,
  39059. bevelMeters: 0.004
  39060. });
  39061. var Viewers = {
  39062. CardboardV1: new CardboardViewer({
  39063. id: 'CardboardV1',
  39064. label: 'Cardboard I/O 2014',
  39065. fov: 40,
  39066. interLensDistance: 0.060,
  39067. baselineLensDistance: 0.035,
  39068. screenLensDistance: 0.042,
  39069. distortionCoefficients: [0.441, 0.156],
  39070. 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]
  39071. }),
  39072. CardboardV2: new CardboardViewer({
  39073. id: 'CardboardV2',
  39074. label: 'Cardboard I/O 2015',
  39075. fov: 60,
  39076. interLensDistance: 0.064,
  39077. baselineLensDistance: 0.035,
  39078. screenLensDistance: 0.039,
  39079. distortionCoefficients: [0.34, 0.55],
  39080. 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]
  39081. })
  39082. };
  39083. function DeviceInfo(deviceParams) {
  39084. this.viewer = Viewers.CardboardV2;
  39085. this.updateDeviceParams(deviceParams);
  39086. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  39087. }
  39088. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  39089. this.device = this.determineDevice_(deviceParams) || this.device;
  39090. };
  39091. DeviceInfo.prototype.getDevice = function () {
  39092. return this.device;
  39093. };
  39094. DeviceInfo.prototype.setViewer = function (viewer) {
  39095. this.viewer = viewer;
  39096. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  39097. };
  39098. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  39099. if (!deviceParams) {
  39100. if (isIOS()) {
  39101. console.warn('Using fallback iOS device measurements.');
  39102. return DEFAULT_IOS;
  39103. } else {
  39104. console.warn('Using fallback Android device measurements.');
  39105. return DEFAULT_ANDROID;
  39106. }
  39107. }
  39108. var METERS_PER_INCH = 0.0254;
  39109. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  39110. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  39111. var width = getScreenWidth();
  39112. var height = getScreenHeight();
  39113. return new Device({
  39114. widthMeters: metersPerPixelX * width,
  39115. heightMeters: metersPerPixelY * height,
  39116. bevelMeters: deviceParams.bevelMm * 0.001
  39117. });
  39118. };
  39119. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  39120. var viewer = this.viewer;
  39121. var device = this.device;
  39122. var distortion = this.distortion;
  39123. var eyeToScreenDistance = viewer.screenLensDistance;
  39124. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  39125. var innerDist = viewer.interLensDistance / 2;
  39126. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  39127. var topDist = device.heightMeters - bottomDist;
  39128. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  39129. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  39130. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  39131. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  39132. return {
  39133. leftDegrees: Math.min(outerAngle, viewer.fov),
  39134. rightDegrees: Math.min(innerAngle, viewer.fov),
  39135. downDegrees: Math.min(bottomAngle, viewer.fov),
  39136. upDegrees: Math.min(topAngle, viewer.fov)
  39137. };
  39138. };
  39139. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  39140. var viewer = this.viewer;
  39141. var device = this.device;
  39142. var distortion = this.distortion;
  39143. var fovLeft = Math.tan(-degToRad * viewer.fov);
  39144. var fovTop = Math.tan(degToRad * viewer.fov);
  39145. var fovRight = Math.tan(degToRad * viewer.fov);
  39146. var fovBottom = Math.tan(-degToRad * viewer.fov);
  39147. var halfWidth = device.widthMeters / 4;
  39148. var halfHeight = device.heightMeters / 2;
  39149. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  39150. var centerX = viewer.interLensDistance / 2 - halfWidth;
  39151. var centerY = -verticalLensOffset;
  39152. var centerZ = viewer.screenLensDistance;
  39153. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  39154. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  39155. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  39156. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  39157. var result = new Float32Array(4);
  39158. result[0] = Math.max(fovLeft, screenLeft);
  39159. result[1] = Math.min(fovTop, screenTop);
  39160. result[2] = Math.min(fovRight, screenRight);
  39161. result[3] = Math.max(fovBottom, screenBottom);
  39162. return result;
  39163. };
  39164. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  39165. var viewer = this.viewer;
  39166. var device = this.device;
  39167. var distortion = this.distortion;
  39168. var result = new Float32Array(4);
  39169. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  39170. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  39171. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  39172. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  39173. var halfWidth = device.widthMeters / 4;
  39174. var halfHeight = device.heightMeters / 2;
  39175. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  39176. var centerX = viewer.interLensDistance / 2 - halfWidth;
  39177. var centerY = -verticalLensOffset;
  39178. var centerZ = viewer.screenLensDistance;
  39179. var screenLeft = (centerX - halfWidth) / centerZ;
  39180. var screenTop = (centerY + halfHeight) / centerZ;
  39181. var screenRight = (centerX + halfWidth) / centerZ;
  39182. var screenBottom = (centerY - halfHeight) / centerZ;
  39183. result[0] = Math.max(fovLeft, screenLeft);
  39184. result[1] = Math.min(fovTop, screenTop);
  39185. result[2] = Math.min(fovRight, screenRight);
  39186. result[3] = Math.max(fovBottom, screenBottom);
  39187. return result;
  39188. };
  39189. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  39190. var viewer = this.viewer;
  39191. var device = this.device;
  39192. var dist = viewer.screenLensDistance;
  39193. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  39194. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  39195. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  39196. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  39197. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  39198. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  39199. return {
  39200. x: left,
  39201. y: bottom,
  39202. width: right - left,
  39203. height: top - bottom
  39204. };
  39205. };
  39206. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  39207. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  39208. };
  39209. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  39210. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  39211. return {
  39212. leftDegrees: fov.rightDegrees,
  39213. rightDegrees: fov.leftDegrees,
  39214. upDegrees: fov.upDegrees,
  39215. downDegrees: fov.downDegrees
  39216. };
  39217. };
  39218. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  39219. var p = this.getUndistortedParams_();
  39220. return {
  39221. leftDegrees: radToDeg * Math.atan(p.outerDist),
  39222. rightDegrees: radToDeg * Math.atan(p.innerDist),
  39223. downDegrees: radToDeg * Math.atan(p.bottomDist),
  39224. upDegrees: radToDeg * Math.atan(p.topDist)
  39225. };
  39226. };
  39227. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  39228. var p = this.getUndistortedParams_();
  39229. var viewer = this.viewer;
  39230. var device = this.device;
  39231. var eyeToScreenDistance = viewer.screenLensDistance;
  39232. var screenWidth = device.widthMeters / eyeToScreenDistance;
  39233. var screenHeight = device.heightMeters / eyeToScreenDistance;
  39234. var xPxPerTanAngle = device.width / screenWidth;
  39235. var yPxPerTanAngle = device.height / screenHeight;
  39236. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  39237. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  39238. return {
  39239. x: x,
  39240. y: y,
  39241. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  39242. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  39243. };
  39244. };
  39245. DeviceInfo.prototype.getUndistortedParams_ = function () {
  39246. var viewer = this.viewer;
  39247. var device = this.device;
  39248. var distortion = this.distortion;
  39249. var eyeToScreenDistance = viewer.screenLensDistance;
  39250. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  39251. var screenWidth = device.widthMeters / eyeToScreenDistance;
  39252. var screenHeight = device.heightMeters / eyeToScreenDistance;
  39253. var eyePosX = screenWidth / 2 - halfLensDistance;
  39254. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  39255. var maxFov = viewer.fov;
  39256. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  39257. var outerDist = Math.min(eyePosX, viewerMax);
  39258. var innerDist = Math.min(halfLensDistance, viewerMax);
  39259. var bottomDist = Math.min(eyePosY, viewerMax);
  39260. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  39261. return {
  39262. outerDist: outerDist,
  39263. innerDist: innerDist,
  39264. topDist: topDist,
  39265. bottomDist: bottomDist,
  39266. eyePosX: eyePosX,
  39267. eyePosY: eyePosY
  39268. };
  39269. };
  39270. function CardboardViewer(params) {
  39271. this.id = params.id;
  39272. this.label = params.label;
  39273. this.fov = params.fov;
  39274. this.interLensDistance = params.interLensDistance;
  39275. this.baselineLensDistance = params.baselineLensDistance;
  39276. this.screenLensDistance = params.screenLensDistance;
  39277. this.distortionCoefficients = params.distortionCoefficients;
  39278. this.inverseCoefficients = params.inverseCoefficients;
  39279. }
  39280. DeviceInfo.Viewers = Viewers;
  39281. var format = 1;
  39282. var last_updated = "2018-02-20T22:55:10Z";
  39283. 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 XL/*"},{"ua":"Pixel XL"}],"dpi":[537.9,533],"bw":3,"ac":1000},{"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":"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":"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}];
  39284. var DPDB_CACHE = {
  39285. format: format,
  39286. last_updated: last_updated,
  39287. devices: devices
  39288. };
  39289. function Dpdb(url, onDeviceParamsUpdated) {
  39290. this.dpdb = DPDB_CACHE;
  39291. this.recalculateDeviceParams_();
  39292. if (url) {
  39293. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  39294. var xhr = new XMLHttpRequest();
  39295. var obj = this;
  39296. xhr.open('GET', url, true);
  39297. xhr.addEventListener('load', function () {
  39298. obj.loading = false;
  39299. if (xhr.status >= 200 && xhr.status <= 299) {
  39300. obj.dpdb = JSON.parse(xhr.response);
  39301. obj.recalculateDeviceParams_();
  39302. } else {
  39303. console.error('Error loading online DPDB!');
  39304. }
  39305. });
  39306. xhr.send();
  39307. }
  39308. }
  39309. Dpdb.prototype.getDeviceParams = function () {
  39310. return this.deviceParams;
  39311. };
  39312. Dpdb.prototype.recalculateDeviceParams_ = function () {
  39313. var newDeviceParams = this.calcDeviceParams_();
  39314. if (newDeviceParams) {
  39315. this.deviceParams = newDeviceParams;
  39316. if (this.onDeviceParamsUpdated) {
  39317. this.onDeviceParamsUpdated(this.deviceParams);
  39318. }
  39319. } else {
  39320. console.error('Failed to recalculate device parameters.');
  39321. }
  39322. };
  39323. Dpdb.prototype.calcDeviceParams_ = function () {
  39324. var db = this.dpdb;
  39325. if (!db) {
  39326. console.error('DPDB not available.');
  39327. return null;
  39328. }
  39329. if (db.format != 1) {
  39330. console.error('DPDB has unexpected format version.');
  39331. return null;
  39332. }
  39333. if (!db.devices || !db.devices.length) {
  39334. console.error('DPDB does not have a devices section.');
  39335. return null;
  39336. }
  39337. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  39338. var width = getScreenWidth();
  39339. var height = getScreenHeight();
  39340. if (!db.devices) {
  39341. console.error('DPDB has no devices section.');
  39342. return null;
  39343. }
  39344. for (var i = 0; i < db.devices.length; i++) {
  39345. var device = db.devices[i];
  39346. if (!device.rules) {
  39347. console.warn('Device[' + i + '] has no rules section.');
  39348. continue;
  39349. }
  39350. if (device.type != 'ios' && device.type != 'android') {
  39351. console.warn('Device[' + i + '] has invalid type.');
  39352. continue;
  39353. }
  39354. if (isIOS() != (device.type == 'ios')) continue;
  39355. var matched = false;
  39356. for (var j = 0; j < device.rules.length; j++) {
  39357. var rule = device.rules[j];
  39358. if (this.matchRule_(rule, userAgent, width, height)) {
  39359. matched = true;
  39360. break;
  39361. }
  39362. }
  39363. if (!matched) continue;
  39364. var xdpi = device.dpi[0] || device.dpi;
  39365. var ydpi = device.dpi[1] || device.dpi;
  39366. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  39367. }
  39368. console.warn('No DPDB device match.');
  39369. return null;
  39370. };
  39371. Dpdb.prototype.matchRule_ = function (rule, ua, screenWidth, screenHeight) {
  39372. if (!rule.ua && !rule.res) return false;
  39373. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  39374. if (rule.res) {
  39375. if (!rule.res[0] || !rule.res[1]) return false;
  39376. var resX = rule.res[0];
  39377. var resY = rule.res[1];
  39378. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  39379. return false;
  39380. }
  39381. }
  39382. return true;
  39383. };
  39384. function DeviceParams(params) {
  39385. this.xdpi = params.xdpi;
  39386. this.ydpi = params.ydpi;
  39387. this.bevelMm = params.bevelMm;
  39388. }
  39389. function SensorSample(sample, timestampS) {
  39390. this.set(sample, timestampS);
  39391. }
  39392. SensorSample.prototype.set = function (sample, timestampS) {
  39393. this.sample = sample;
  39394. this.timestampS = timestampS;
  39395. };
  39396. SensorSample.prototype.copy = function (sensorSample) {
  39397. this.set(sensorSample.sample, sensorSample.timestampS);
  39398. };
  39399. function ComplementaryFilter(kFilter, isDebug) {
  39400. this.kFilter = kFilter;
  39401. this.isDebug = isDebug;
  39402. this.currentAccelMeasurement = new SensorSample();
  39403. this.currentGyroMeasurement = new SensorSample();
  39404. this.previousGyroMeasurement = new SensorSample();
  39405. if (isIOS()) {
  39406. this.filterQ = new Quaternion(-1, 0, 0, 1);
  39407. } else {
  39408. this.filterQ = new Quaternion(1, 0, 0, 1);
  39409. }
  39410. this.previousFilterQ = new Quaternion();
  39411. this.previousFilterQ.copy(this.filterQ);
  39412. this.accelQ = new Quaternion();
  39413. this.isOrientationInitialized = false;
  39414. this.estimatedGravity = new Vector3();
  39415. this.measuredGravity = new Vector3();
  39416. this.gyroIntegralQ = new Quaternion();
  39417. }
  39418. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  39419. this.currentAccelMeasurement.set(vector, timestampS);
  39420. };
  39421. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  39422. this.currentGyroMeasurement.set(vector, timestampS);
  39423. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  39424. if (isTimestampDeltaValid(deltaT)) {
  39425. this.run_();
  39426. }
  39427. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  39428. };
  39429. ComplementaryFilter.prototype.run_ = function () {
  39430. if (!this.isOrientationInitialized) {
  39431. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  39432. this.previousFilterQ.copy(this.accelQ);
  39433. this.isOrientationInitialized = true;
  39434. return;
  39435. }
  39436. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  39437. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  39438. this.gyroIntegralQ.multiply(gyroDeltaQ);
  39439. this.filterQ.copy(this.previousFilterQ);
  39440. this.filterQ.multiply(gyroDeltaQ);
  39441. var invFilterQ = new Quaternion();
  39442. invFilterQ.copy(this.filterQ);
  39443. invFilterQ.inverse();
  39444. this.estimatedGravity.set(0, 0, -1);
  39445. this.estimatedGravity.applyQuaternion(invFilterQ);
  39446. this.estimatedGravity.normalize();
  39447. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  39448. this.measuredGravity.normalize();
  39449. var deltaQ = new Quaternion();
  39450. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  39451. deltaQ.inverse();
  39452. if (this.isDebug) {
  39453. 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));
  39454. }
  39455. var targetQ = new Quaternion();
  39456. targetQ.copy(this.filterQ);
  39457. targetQ.multiply(deltaQ);
  39458. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  39459. this.previousFilterQ.copy(this.filterQ);
  39460. };
  39461. ComplementaryFilter.prototype.getOrientation = function () {
  39462. return this.filterQ;
  39463. };
  39464. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  39465. var normAccel = new Vector3();
  39466. normAccel.copy(accel);
  39467. normAccel.normalize();
  39468. var quat = new Quaternion();
  39469. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  39470. quat.inverse();
  39471. return quat;
  39472. };
  39473. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  39474. var quat = new Quaternion();
  39475. var axis = new Vector3();
  39476. axis.copy(gyro);
  39477. axis.normalize();
  39478. quat.setFromAxisAngle(axis, gyro.length() * dt);
  39479. return quat;
  39480. };
  39481. function PosePredictor(predictionTimeS, isDebug) {
  39482. this.predictionTimeS = predictionTimeS;
  39483. this.isDebug = isDebug;
  39484. this.previousQ = new Quaternion();
  39485. this.previousTimestampS = null;
  39486. this.deltaQ = new Quaternion();
  39487. this.outQ = new Quaternion();
  39488. }
  39489. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  39490. if (!this.previousTimestampS) {
  39491. this.previousQ.copy(currentQ);
  39492. this.previousTimestampS = timestampS;
  39493. return currentQ;
  39494. }
  39495. var axis = new Vector3();
  39496. axis.copy(gyro);
  39497. axis.normalize();
  39498. var angularSpeed = gyro.length();
  39499. if (angularSpeed < degToRad * 20) {
  39500. if (this.isDebug) {
  39501. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  39502. }
  39503. this.outQ.copy(currentQ);
  39504. this.previousQ.copy(currentQ);
  39505. return this.outQ;
  39506. }
  39507. var predictAngle = angularSpeed * this.predictionTimeS;
  39508. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  39509. this.outQ.copy(this.previousQ);
  39510. this.outQ.multiply(this.deltaQ);
  39511. this.previousQ.copy(currentQ);
  39512. this.previousTimestampS = timestampS;
  39513. return this.outQ;
  39514. };
  39515. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  39516. this.yawOnly = yawOnly;
  39517. this.accelerometer = new Vector3();
  39518. this.gyroscope = new Vector3();
  39519. this.filter = new ComplementaryFilter(kFilter, isDebug);
  39520. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  39521. this.isFirefoxAndroid = isFirefoxAndroid();
  39522. this.isIOS = isIOS();
  39523. var chromeVersion = getChromeVersion();
  39524. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  39525. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion();
  39526. this.filterToWorldQ = new Quaternion();
  39527. if (isIOS()) {
  39528. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  39529. } else {
  39530. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  39531. }
  39532. this.inverseWorldToScreenQ = new Quaternion();
  39533. this.worldToScreenQ = new Quaternion();
  39534. this.originalPoseAdjustQ = new Quaternion();
  39535. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  39536. this.setScreenTransform_();
  39537. if (isLandscapeMode()) {
  39538. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  39539. }
  39540. this.resetQ = new Quaternion();
  39541. this.orientationOut_ = new Float32Array(4);
  39542. this.start();
  39543. }
  39544. FusionPoseSensor.prototype.getPosition = function () {
  39545. return null;
  39546. };
  39547. FusionPoseSensor.prototype.getOrientation = function () {
  39548. var orientation = void 0;
  39549. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  39550. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  39551. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  39552. var y = new Quaternion();
  39553. if (window.orientation === -90) {
  39554. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  39555. } else {
  39556. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  39557. }
  39558. return z.multiply(y);
  39559. }();
  39560. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  39561. var q = new Quaternion();
  39562. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  39563. return q;
  39564. }();
  39565. orientation = this._deviceOrientationQ;
  39566. var out = new Quaternion();
  39567. out.copy(orientation);
  39568. out.multiply(this.deviceOrientationFilterToWorldQ);
  39569. out.multiply(this.resetQ);
  39570. out.multiply(this.worldToScreenQ);
  39571. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  39572. if (this.yawOnly) {
  39573. out.x = 0;
  39574. out.z = 0;
  39575. out.normalize();
  39576. }
  39577. this.orientationOut_[0] = out.x;
  39578. this.orientationOut_[1] = out.y;
  39579. this.orientationOut_[2] = out.z;
  39580. this.orientationOut_[3] = out.w;
  39581. return this.orientationOut_;
  39582. } else {
  39583. var filterOrientation = this.filter.getOrientation();
  39584. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  39585. }
  39586. var out = new Quaternion();
  39587. out.copy(this.filterToWorldQ);
  39588. out.multiply(this.resetQ);
  39589. out.multiply(orientation);
  39590. out.multiply(this.worldToScreenQ);
  39591. if (this.yawOnly) {
  39592. out.x = 0;
  39593. out.z = 0;
  39594. out.normalize();
  39595. }
  39596. this.orientationOut_[0] = out.x;
  39597. this.orientationOut_[1] = out.y;
  39598. this.orientationOut_[2] = out.z;
  39599. this.orientationOut_[3] = out.w;
  39600. return this.orientationOut_;
  39601. };
  39602. FusionPoseSensor.prototype.resetPose = function () {
  39603. this.resetQ.copy(this.filter.getOrientation());
  39604. this.resetQ.x = 0;
  39605. this.resetQ.y = 0;
  39606. this.resetQ.z *= -1;
  39607. this.resetQ.normalize();
  39608. if (isLandscapeMode()) {
  39609. this.resetQ.multiply(this.inverseWorldToScreenQ);
  39610. }
  39611. this.resetQ.multiply(this.originalPoseAdjustQ);
  39612. };
  39613. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  39614. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  39615. var alpha = e.alpha,
  39616. beta = e.beta,
  39617. gamma = e.gamma;
  39618. alpha = (alpha || 0) * Math.PI / 180;
  39619. beta = (beta || 0) * Math.PI / 180;
  39620. gamma = (gamma || 0) * Math.PI / 180;
  39621. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  39622. };
  39623. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  39624. this.updateDeviceMotion_(deviceMotion);
  39625. };
  39626. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  39627. var accGravity = deviceMotion.accelerationIncludingGravity;
  39628. var rotRate = deviceMotion.rotationRate;
  39629. var timestampS = deviceMotion.timeStamp / 1000;
  39630. var deltaS = timestampS - this.previousTimestampS;
  39631. if (deltaS < 0) {
  39632. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  39633. this.previousTimestampS = timestampS;
  39634. return;
  39635. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  39636. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  39637. this.previousTimestampS = timestampS;
  39638. return;
  39639. }
  39640. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  39641. if (isR7()) {
  39642. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  39643. } else {
  39644. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  39645. }
  39646. if (!this.isDeviceMotionInRadians) {
  39647. this.gyroscope.multiplyScalar(Math.PI / 180);
  39648. }
  39649. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  39650. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  39651. this.previousTimestampS = timestampS;
  39652. };
  39653. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  39654. this.setScreenTransform_();
  39655. };
  39656. FusionPoseSensor.prototype.onMessage_ = function (event) {
  39657. var message = event.data;
  39658. if (!message || !message.type) {
  39659. return;
  39660. }
  39661. var type = message.type.toLowerCase();
  39662. if (type !== 'devicemotion') {
  39663. return;
  39664. }
  39665. this.updateDeviceMotion_(message.deviceMotionEvent);
  39666. };
  39667. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  39668. this.worldToScreenQ.set(0, 0, 0, 1);
  39669. switch (window.orientation) {
  39670. case 0:
  39671. break;
  39672. case 90:
  39673. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  39674. break;
  39675. case -90:
  39676. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  39677. break;
  39678. case 180:
  39679. break;
  39680. }
  39681. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  39682. this.inverseWorldToScreenQ.inverse();
  39683. };
  39684. FusionPoseSensor.prototype.start = function () {
  39685. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  39686. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  39687. this.onMessageCallback_ = this.onMessage_.bind(this);
  39688. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  39689. if (isIOS() && isInsideCrossOriginIFrame()) {
  39690. window.addEventListener('message', this.onMessageCallback_);
  39691. }
  39692. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  39693. if (this.isWithoutDeviceMotion) {
  39694. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  39695. } else {
  39696. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  39697. }
  39698. };
  39699. FusionPoseSensor.prototype.stop = function () {
  39700. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  39701. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  39702. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  39703. window.removeEventListener('message', this.onMessageCallback_);
  39704. };
  39705. var SENSOR_FREQUENCY = 60;
  39706. var X_AXIS = new Vector3(1, 0, 0);
  39707. var Z_AXIS = new Vector3(0, 0, 1);
  39708. var orientation = {};
  39709. if (screen.orientation) {
  39710. orientation = screen.orientation;
  39711. } else if (screen.msOrientation) {
  39712. orientation = screen.msOrientation;
  39713. } else {
  39714. Object.defineProperty(orientation, 'angle', {
  39715. get: function get$$1() {
  39716. return window.orientation || 0;
  39717. }
  39718. });
  39719. }
  39720. var SENSOR_TO_VR = new Quaternion();
  39721. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  39722. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  39723. var PoseSensor = function () {
  39724. function PoseSensor(config) {
  39725. classCallCheck(this, PoseSensor);
  39726. this.config = config;
  39727. this.sensor = null;
  39728. this.fusionSensor = null;
  39729. this._out = new Float32Array(4);
  39730. this.api = null;
  39731. this.errors = [];
  39732. this._sensorQ = new Quaternion();
  39733. this._worldToScreenQ = new Quaternion();
  39734. this._outQ = new Quaternion();
  39735. this._onSensorRead = this._onSensorRead.bind(this);
  39736. this._onSensorError = this._onSensorError.bind(this);
  39737. this._onOrientationChange = this._onOrientationChange.bind(this);
  39738. this._onOrientationChange();
  39739. this.init();
  39740. }
  39741. createClass(PoseSensor, [{
  39742. key: 'init',
  39743. value: function init() {
  39744. var sensor = null;
  39745. try {
  39746. sensor = new RelativeOrientationSensor({ frequency: SENSOR_FREQUENCY });
  39747. sensor.addEventListener('error', this._onSensorError);
  39748. } catch (error) {
  39749. this.errors.push(error);
  39750. if (error.name === 'SecurityError') {
  39751. console.error('Cannot construct sensors due to the Feature Policy');
  39752. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  39753. this.useDeviceMotion();
  39754. } else if (error.name === 'ReferenceError') {
  39755. this.useDeviceMotion();
  39756. } else {
  39757. console.error(error);
  39758. }
  39759. }
  39760. if (sensor) {
  39761. this.api = 'sensor';
  39762. this.sensor = sensor;
  39763. this.sensor.addEventListener('reading', this._onSensorRead);
  39764. this.sensor.start();
  39765. }
  39766. window.addEventListener('orientationchange', this._onOrientationChange);
  39767. }
  39768. }, {
  39769. key: 'useDeviceMotion',
  39770. value: function useDeviceMotion() {
  39771. this.api = 'devicemotion';
  39772. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  39773. }
  39774. }, {
  39775. key: 'getOrientation',
  39776. value: function getOrientation() {
  39777. if (this.fusionSensor) {
  39778. return this.fusionSensor.getOrientation();
  39779. }
  39780. if (!this.sensor || !this.sensor.quaternion) {
  39781. this._out[0] = this._out[1] = this._out[2] = 0;
  39782. this._out[3] = 1;
  39783. return this._out;
  39784. }
  39785. var q = this.sensor.quaternion;
  39786. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  39787. var out = this._outQ;
  39788. out.copy(SENSOR_TO_VR);
  39789. out.multiply(this._sensorQ);
  39790. out.multiply(this._worldToScreenQ);
  39791. if (this.config.YAW_ONLY) {
  39792. out.x = out.z = 0;
  39793. out.normalize();
  39794. }
  39795. this._out[0] = out.x;
  39796. this._out[1] = out.y;
  39797. this._out[2] = out.z;
  39798. this._out[3] = out.w;
  39799. return this._out;
  39800. }
  39801. }, {
  39802. key: '_onSensorError',
  39803. value: function _onSensorError(event) {
  39804. this.errors.push(event.error);
  39805. if (event.error.name === 'NotAllowedError') {
  39806. console.error('Permission to access sensor was denied');
  39807. } else if (event.error.name === 'NotReadableError') {
  39808. console.error('Sensor could not be read');
  39809. } else {
  39810. console.error(event.error);
  39811. }
  39812. }
  39813. }, {
  39814. key: '_onSensorRead',
  39815. value: function _onSensorRead() {}
  39816. }, {
  39817. key: '_onOrientationChange',
  39818. value: function _onOrientationChange() {
  39819. var angle = -orientation.angle * Math.PI / 180;
  39820. this._worldToScreenQ.setFromAxisAngle(Z_AXIS, angle);
  39821. }
  39822. }]);
  39823. return PoseSensor;
  39824. }();
  39825. var rotateInstructionsAsset = 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjE5OHB4IiBoZWlnaHQ9IjI0MHB4IiB2aWV3Qm94PSIwIDAgMTk4IDI0MCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4bWxuczpza2V0Y2g9Imh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaC9ucyI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDMuMy4zICgxMjA4MSkgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8dGl0bGU+dHJhbnNpdGlvbjwvdGl0bGU+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHNrZXRjaDp0eXBlPSJNU1BhZ2UiPgogICAgICAgIDxnIGlkPSJ0cmFuc2l0aW9uIiBza2V0Y2g6dHlwZT0iTVNBcnRib2FyZEdyb3VwIj4KICAgICAgICAgICAgPGcgaWQ9IkltcG9ydGVkLUxheWVycy1Db3B5LTQtKy1JbXBvcnRlZC1MYXllcnMtQ29weS0rLUltcG9ydGVkLUxheWVycy1Db3B5LTItQ29weSIgc2tldGNoOnR5cGU9Ik1TTGF5ZXJHcm91cCI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iSW1wb3J0ZWQtTGF5ZXJzLUNvcHktNCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMC4wMDAwMDAsIDEwNy4wMDAwMDApIiBza2V0Y2g6dHlwZT0iTVNTaGFwZUdyb3VwIj4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTQ5LjYyNSwyLjUyNyBDMTQ5LjYyNSwyLjUyNyAxNTUuODA1LDYuMDk2IDE1Ni4zNjIsNi40MTggTDE1Ni4zNjIsNy4zMDQgQzE1Ni4zNjIsNy40ODEgMTU2LjM3NSw3LjY2NCAxNTYuNCw3Ljg1MyBDMTU2LjQxLDcuOTM0IDE1Ni40Miw4LjAxNSAxNTYuNDI3LDguMDk1IEMxNTYuNTY3LDkuNTEgMTU3LjQwMSwxMS4wOTMgMTU4LjUzMiwxMi4wOTQgTDE2NC4yNTIsMTcuMTU2IEwxNjQuMzMzLDE3LjA2NiBDMTY0LjMzMywxNy4wNjYgMTY4LjcxNSwxNC41MzYgMTY5LjU2OCwxNC4wNDIgQzE3MS4wMjUsMTQuODgzIDE5NS41MzgsMjkuMDM1IDE5NS41MzgsMjkuMDM1IEwxOTUuNTM4LDgzLjAzNiBDMTk1LjUzOCw4My44MDcgMTk1LjE1Miw4NC4yNTMgMTk0LjU5LDg0LjI1MyBDMTk0LjM1Nyw4NC4yNTMgMTk0LjA5NSw4NC4xNzcgMTkzLjgxOCw4NC4wMTcgTDE2OS44NTEsNzAuMTc5IEwxNjkuODM3LDcwLjIwMyBMMTQyLjUxNSw4NS45NzggTDE0MS42NjUsODQuNjU1IEMxMzYuOTM0LDgzLjEyNiAxMzEuOTE3LDgxLjkxNSAxMjYuNzE0LDgxLjA0NSBDMTI2LjcwOSw4MS4wNiAxMjYuNzA3LDgxLjA2OSAxMjYuNzA3LDgxLjA2OSBMMTIxLjY0LDk4LjAzIEwxMTMuNzQ5LDEwMi41ODYgTDExMy43MTIsMTAyLjUyMyBMMTEzLjcxMiwxMzAuMTEzIEMxMTMuNzEyLDEzMC44ODUgMTEzLjMyNiwxMzEuMzMgMTEyLjc2NCwxMzEuMzMgQzExMi41MzIsMTMxLjMzIDExMi4yNjksMTMxLjI1NCAxMTEuOTkyLDEzMS4wOTQgTDY5LjUxOSwxMDYuNTcyIEM2OC41NjksMTA2LjAyMyA2Ny43OTksMTA0LjY5NSA2Ny43OTksMTAzLjYwNSBMNjcuNzk5LDEwMi41NyBMNjcuNzc4LDEwMi42MTcgQzY3LjI3LDEwMi4zOTMgNjYuNjQ4LDEwMi4yNDkgNjUuOTYyLDEwMi4yMTggQzY1Ljg3NSwxMDIuMjE0IDY1Ljc4OCwxMDIuMjEyIDY1LjcwMSwxMDIuMjEyIEM2NS42MDYsMTAyLjIxMiA2NS41MTEsMTAyLjIxNSA2NS40MTYsMTAyLjIxOSBDNjUuMTk1LDEwMi4yMjkgNjQuOTc0LDEwMi4yMzUgNjQuNzU0LDEwMi4yMzUgQzY0LjMzMSwxMDIuMjM1IDYzLjkxMSwxMDIuMjE2IDYzLjQ5OCwxMDIuMTc4IEM2MS44NDMsMTAyLjAyNSA2MC4yOTgsMTAxLjU3OCA1OS4wOTQsMTAwLjg4MiBMMTIuNTE4LDczLjk5MiBMMTIuNTIzLDc0LjAwNCBMMi4yNDUsNTUuMjU0IEMxLjI0NCw1My40MjcgMi4wMDQsNTEuMDM4IDMuOTQzLDQ5LjkxOCBMNTkuOTU0LDE3LjU3MyBDNjAuNjI2LDE3LjE4NSA2MS4zNSwxNy4wMDEgNjIuMDUzLDE3LjAwMSBDNjMuMzc5LDE3LjAwMSA2NC42MjUsMTcuNjYgNjUuMjgsMTguODU0IEw2NS4yODUsMTguODUxIEw2NS41MTIsMTkuMjY0IEw2NS41MDYsMTkuMjY4IEM2NS45MDksMjAuMDAzIDY2LjQwNSwyMC42OCA2Ni45ODMsMjEuMjg2IEw2Ny4yNiwyMS41NTYgQzY5LjE3NCwyMy40MDYgNzEuNzI4LDI0LjM1NyA3NC4zNzMsMjQuMzU3IEM3Ni4zMjIsMjQuMzU3IDc4LjMyMSwyMy44NCA4MC4xNDgsMjIuNzg1IEM4MC4xNjEsMjIuNzg1IDg3LjQ2NywxOC41NjYgODcuNDY3LDE4LjU2NiBDODguMTM5LDE4LjE3OCA4OC44NjMsMTcuOTk0IDg5LjU2NiwxNy45OTQgQzkwLjg5MiwxNy45OTQgOTIuMTM4LDE4LjY1MiA5Mi43OTIsMTkuODQ3IEw5Ni4wNDIsMjUuNzc1IEw5Ni4wNjQsMjUuNzU3IEwxMDIuODQ5LDI5LjY3NCBMMTAyLjc0NCwyOS40OTIgTDE0OS42MjUsMi41MjcgTTE0OS42MjUsMC44OTIgQzE0OS4zNDMsMC44OTIgMTQ5LjA2MiwwLjk2NSAxNDguODEsMS4xMSBMMTAyLjY0MSwyNy42NjYgTDk3LjIzMSwyNC41NDIgTDk0LjIyNiwxOS4wNjEgQzkzLjMxMywxNy4zOTQgOTEuNTI3LDE2LjM1OSA4OS41NjYsMTYuMzU4IEM4OC41NTUsMTYuMzU4IDg3LjU0NiwxNi42MzIgODYuNjQ5LDE3LjE1IEM4My44NzgsMTguNzUgNzkuNjg3LDIxLjE2OSA3OS4zNzQsMjEuMzQ1IEM3OS4zNTksMjEuMzUzIDc5LjM0NSwyMS4zNjEgNzkuMzMsMjEuMzY5IEM3Ny43OTgsMjIuMjU0IDc2LjA4NCwyMi43MjIgNzQuMzczLDIyLjcyMiBDNzIuMDgxLDIyLjcyMiA2OS45NTksMjEuODkgNjguMzk3LDIwLjM4IEw2OC4xNDUsMjAuMTM1IEM2Ny43MDYsMTkuNjcyIDY3LjMyMywxOS4xNTYgNjcuMDA2LDE4LjYwMSBDNjYuOTg4LDE4LjU1OSA2Ni45NjgsMTguNTE5IDY2Ljk0NiwxOC40NzkgTDY2LjcxOSwxOC4wNjUgQzY2LjY5LDE4LjAxMiA2Ni42NTgsMTcuOTYgNjYuNjI0LDE3LjkxMSBDNjUuNjg2LDE2LjMzNyA2My45NTEsMTUuMzY2IDYyLjA1MywxNS4zNjYgQzYxLjA0MiwxNS4zNjYgNjAuMDMzLDE1LjY0IDU5LjEzNiwxNi4xNTggTDMuMTI1LDQ4LjUwMiBDMC40MjYsNTAuMDYxIC0wLjYxMyw1My40NDIgMC44MTEsNTYuMDQgTDExLjA4OSw3NC43OSBDMTEuMjY2LDc1LjExMyAxMS41MzcsNzUuMzUzIDExLjg1LDc1LjQ5NCBMNTguMjc2LDEwMi4yOTggQzU5LjY3OSwxMDMuMTA4IDYxLjQzMywxMDMuNjMgNjMuMzQ4LDEwMy44MDYgQzYzLjgxMiwxMDMuODQ4IDY0LjI4NSwxMDMuODcgNjQuNzU0LDEwMy44NyBDNjUsMTAzLjg3IDY1LjI0OSwxMDMuODY0IDY1LjQ5NCwxMDMuODUyIEM2NS41NjMsMTAzLjg0OSA2NS42MzIsMTAzLjg0NyA2NS43MDEsMTAzLjg0NyBDNjUuNzY0LDEwMy44NDcgNjUuODI4LDEwMy44NDkgNjUuODksMTAzLjg1MiBDNjUuOTg2LDEwMy44NTYgNjYuMDgsMTAzLjg2MyA2Ni4xNzMsMTAzLjg3NCBDNjYuMjgyLDEwNS40NjcgNjcuMzMyLDEwNy4xOTcgNjguNzAyLDEwNy45ODggTDExMS4xNzQsMTMyLjUxIEMxMTEuNjk4LDEzMi44MTIgMTEyLjIzMiwxMzIuOTY1IDExMi43NjQsMTMyLjk2NSBDMTE0LjI2MSwxMzIuOTY1IDExNS4zNDcsMTMxLjc2NSAxMTUuMzQ3LDEzMC4xMTMgTDExNS4zNDcsMTAzLjU1MSBMMTIyLjQ1OCw5OS40NDYgQzEyMi44MTksOTkuMjM3IDEyMy4wODcsOTguODk4IDEyMy4yMDcsOTguNDk4IEwxMjcuODY1LDgyLjkwNSBDMTMyLjI3OSw4My43MDIgMTM2LjU1Nyw4NC43NTMgMTQwLjYwNyw4Ni4wMzMgTDE0MS4xNCw4Ni44NjIgQzE0MS40NTEsODcuMzQ2IDE0MS45NzcsODcuNjEzIDE0Mi41MTYsODcuNjEzIEMxNDIuNzk0LDg3LjYxMyAxNDMuMDc2LDg3LjU0MiAxNDMuMzMzLDg3LjM5MyBMMTY5Ljg2NSw3Mi4wNzYgTDE5Myw4NS40MzMgQzE5My41MjMsODUuNzM1IDE5NC4wNTgsODUuODg4IDE5NC41OSw4NS44ODggQzE5Ni4wODcsODUuODg4IDE5Ny4xNzMsODQuNjg5IDE5Ny4xNzMsODMuMDM2IEwxOTcuMTczLDI5LjAzNSBDMTk3LjE3MywyOC40NTEgMTk2Ljg2MSwyNy45MTEgMTk2LjM1NSwyNy42MTkgQzE5Ni4zNTUsMjcuNjE5IDE3MS44NDMsMTMuNDY3IDE3MC4zODUsMTIuNjI2IEMxNzAuMTMyLDEyLjQ4IDE2OS44NSwxMi40MDcgMTY5LjU2OCwxMi40MDcgQzE2OS4yODUsMTIuNDA3IDE2OS4wMDIsMTIuNDgxIDE2OC43NDksMTIuNjI3IEMxNjguMTQzLDEyLjk3OCAxNjUuNzU2LDE0LjM1NyAxNjQuNDI0LDE1LjEyNSBMMTU5LjYxNSwxMC44NyBDMTU4Ljc5NiwxMC4xNDUgMTU4LjE1NCw4LjkzNyAxNTguMDU0LDcuOTM0IEMxNTguMDQ1LDcuODM3IDE1OC4wMzQsNy43MzkgMTU4LjAyMSw3LjY0IEMxNTguMDA1LDcuNTIzIDE1Ny45OTgsNy40MSAxNTcuOTk4LDcuMzA0IEwxNTcuOTk4LDYuNDE4IEMxNTcuOTk4LDUuODM0IDE1Ny42ODYsNS4yOTUgMTU3LjE4MSw1LjAwMiBDMTU2LjYyNCw0LjY4IDE1MC40NDIsMS4xMTEgMTUwLjQ0MiwxLjExMSBDMTUwLjE4OSwwLjk2NSAxNDkuOTA3LDAuODkyIDE0OS42MjUsMC44OTIiIGlkPSJGaWxsLTEiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNOTYuMDI3LDI1LjYzNiBMMTQyLjYwMyw1Mi41MjcgQzE0My44MDcsNTMuMjIyIDE0NC41ODIsNTQuMTE0IDE0NC44NDUsNTUuMDY4IEwxNDQuODM1LDU1LjA3NSBMNjMuNDYxLDEwMi4wNTcgTDYzLjQ2LDEwMi4wNTcgQzYxLjgwNiwxMDEuOTA1IDYwLjI2MSwxMDEuNDU3IDU5LjA1NywxMDAuNzYyIEwxMi40ODEsNzMuODcxIEw5Ni4wMjcsMjUuNjM2IiBpZD0iRmlsbC0yIiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTYzLjQ2MSwxMDIuMTc0IEM2My40NTMsMTAyLjE3NCA2My40NDYsMTAyLjE3NCA2My40MzksMTAyLjE3MiBDNjEuNzQ2LDEwMi4wMTYgNjAuMjExLDEwMS41NjMgNTguOTk4LDEwMC44NjMgTDEyLjQyMiw3My45NzMgQzEyLjM4Niw3My45NTIgMTIuMzY0LDczLjkxNCAxMi4zNjQsNzMuODcxIEMxMi4zNjQsNzMuODMgMTIuMzg2LDczLjc5MSAxMi40MjIsNzMuNzcgTDk1Ljk2OCwyNS41MzUgQzk2LjAwNCwyNS41MTQgOTYuMDQ5LDI1LjUxNCA5Ni4wODUsMjUuNTM1IEwxNDIuNjYxLDUyLjQyNiBDMTQzLjg4OCw1My4xMzQgMTQ0LjY4Miw1NC4wMzggMTQ0Ljk1Nyw1NS4wMzcgQzE0NC45Nyw1NS4wODMgMTQ0Ljk1Myw1NS4xMzMgMTQ0LjkxNSw1NS4xNjEgQzE0NC45MTEsNTUuMTY1IDE0NC44OTgsNTUuMTc0IDE0NC44OTQsNTUuMTc3IEw2My41MTksMTAyLjE1OCBDNjMuNTAxLDEwMi4xNjkgNjMuNDgxLDEwMi4xNzQgNjMuNDYxLDEwMi4xNzQgTDYzLjQ2MSwxMDIuMTc0IFogTTEyLjcxNCw3My44NzEgTDU5LjExNSwxMDAuNjYxIEM2MC4yOTMsMTAxLjM0MSA2MS43ODYsMTAxLjc4MiA2My40MzUsMTAxLjkzNyBMMTQ0LjcwNyw1NS4wMTUgQzE0NC40MjgsNTQuMTA4IDE0My42ODIsNTMuMjg1IDE0Mi41NDQsNTIuNjI4IEw5Ni4wMjcsMjUuNzcxIEwxMi43MTQsNzMuODcxIEwxMi43MTQsNzMuODcxIFoiIGlkPSJGaWxsLTMiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTQ4LjMyNyw1OC40NzEgQzE0OC4xNDUsNTguNDggMTQ3Ljk2Miw1OC40OCAxNDcuNzgxLDU4LjQ3MiBDMTQ1Ljg4Nyw1OC4zODkgMTQ0LjQ3OSw1Ny40MzQgMTQ0LjYzNiw1Ni4zNCBDMTQ0LjY4OSw1NS45NjcgMTQ0LjY2NCw1NS41OTcgMTQ0LjU2NCw1NS4yMzUgTDYzLjQ2MSwxMDIuMDU3IEM2NC4wODksMTAyLjExNSA2NC43MzMsMTAyLjEzIDY1LjM3OSwxMDIuMDk5IEM2NS41NjEsMTAyLjA5IDY1Ljc0MywxMDIuMDkgNjUuOTI1LDEwMi4wOTggQzY3LjgxOSwxMDIuMTgxIDY5LjIyNywxMDMuMTM2IDY5LjA3LDEwNC4yMyBMMTQ4LjMyNyw1OC40NzEiIGlkPSJGaWxsLTQiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNjkuMDcsMTA0LjM0NyBDNjkuMDQ4LDEwNC4zNDcgNjkuMDI1LDEwNC4zNCA2OS4wMDUsMTA0LjMyNyBDNjguOTY4LDEwNC4zMDEgNjguOTQ4LDEwNC4yNTcgNjguOTU1LDEwNC4yMTMgQzY5LDEwMy44OTYgNjguODk4LDEwMy41NzYgNjguNjU4LDEwMy4yODggQzY4LjE1MywxMDIuNjc4IDY3LjEwMywxMDIuMjY2IDY1LjkyLDEwMi4yMTQgQzY1Ljc0MiwxMDIuMjA2IDY1LjU2MywxMDIuMjA3IDY1LjM4NSwxMDIuMjE1IEM2NC43NDIsMTAyLjI0NiA2NC4wODcsMTAyLjIzMiA2My40NSwxMDIuMTc0IEM2My4zOTksMTAyLjE2OSA2My4zNTgsMTAyLjEzMiA2My4zNDcsMTAyLjA4MiBDNjMuMzM2LDEwMi4wMzMgNjMuMzU4LDEwMS45ODEgNjMuNDAyLDEwMS45NTYgTDE0NC41MDYsNTUuMTM0IEMxNDQuNTM3LDU1LjExNiAxNDQuNTc1LDU1LjExMyAxNDQuNjA5LDU1LjEyNyBDMTQ0LjY0Miw1NS4xNDEgMTQ0LjY2OCw1NS4xNyAxNDQuNjc3LDU1LjIwNCBDMTQ0Ljc4MSw1NS41ODUgMTQ0LjgwNiw1NS45NzIgMTQ0Ljc1MSw1Ni4zNTcgQzE0NC43MDYsNTYuNjczIDE0NC44MDgsNTYuOTk0IDE0NS4wNDcsNTcuMjgyIEMxNDUuNTUzLDU3Ljg5MiAxNDYuNjAyLDU4LjMwMyAxNDcuNzg2LDU4LjM1NSBDMTQ3Ljk2NCw1OC4zNjMgMTQ4LjE0Myw1OC4zNjMgMTQ4LjMyMSw1OC4zNTQgQzE0OC4zNzcsNTguMzUyIDE0OC40MjQsNTguMzg3IDE0OC40MzksNTguNDM4IEMxNDguNDU0LDU4LjQ5IDE0OC40MzIsNTguNTQ1IDE0OC4zODUsNTguNTcyIEw2OS4xMjksMTA0LjMzMSBDNjkuMTExLDEwNC4zNDIgNjkuMDksMTA0LjM0NyA2OS4wNywxMDQuMzQ3IEw2OS4wNywxMDQuMzQ3IFogTTY1LjY2NSwxMDEuOTc1IEM2NS43NTQsMTAxLjk3NSA2NS44NDIsMTAxLjk3NyA2NS45MywxMDEuOTgxIEM2Ny4xOTYsMTAyLjAzNyA2OC4yODMsMTAyLjQ2OSA2OC44MzgsMTAzLjEzOSBDNjkuMDY1LDEwMy40MTMgNjkuMTg4LDEwMy43MTQgNjkuMTk4LDEwNC4wMjEgTDE0Ny44ODMsNTguNTkyIEMxNDcuODQ3LDU4LjU5MiAxNDcuODExLDU4LjU5MSAxNDcuNzc2LDU4LjU4OSBDMTQ2LjUwOSw1OC41MzMgMTQ1LjQyMiw1OC4xIDE0NC44NjcsNTcuNDMxIEMxNDQuNTg1LDU3LjA5MSAxNDQuNDY1LDU2LjcwNyAxNDQuNTIsNTYuMzI0IEMxNDQuNTYzLDU2LjAyMSAxNDQuNTUyLDU1LjcxNiAxNDQuNDg4LDU1LjQxNCBMNjMuODQ2LDEwMS45NyBDNjQuMzUzLDEwMi4wMDIgNjQuODY3LDEwMi4wMDYgNjUuMzc0LDEwMS45ODIgQzY1LjQ3MSwxMDEuOTc3IDY1LjU2OCwxMDEuOTc1IDY1LjY2NSwxMDEuOTc1IEw2NS42NjUsMTAxLjk3NSBaIiBpZD0iRmlsbC01IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTIuMjA4LDU1LjEzNCBDMS4yMDcsNTMuMzA3IDEuOTY3LDUwLjkxNyAzLjkwNiw0OS43OTcgTDU5LjkxNywxNy40NTMgQzYxLjg1NiwxNi4zMzMgNjQuMjQxLDE2LjkwNyA2NS4yNDMsMTguNzM0IEw2NS40NzUsMTkuMTQ0IEM2NS44NzIsMTkuODgyIDY2LjM2OCwyMC41NiA2Ni45NDUsMjEuMTY1IEw2Ny4yMjMsMjEuNDM1IEM3MC41NDgsMjQuNjQ5IDc1LjgwNiwyNS4xNTEgODAuMTExLDIyLjY2NSBMODcuNDMsMTguNDQ1IEM4OS4zNywxNy4zMjYgOTEuNzU0LDE3Ljg5OSA5Mi43NTUsMTkuNzI3IEw5Ni4wMDUsMjUuNjU1IEwxMi40ODYsNzMuODg0IEwyLjIwOCw1NS4xMzQgWiIgaWQ9IkZpbGwtNiIgZmlsbD0iI0ZBRkFGQSI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMi40ODYsNzQuMDAxIEMxMi40NzYsNzQuMDAxIDEyLjQ2NSw3My45OTkgMTIuNDU1LDczLjk5NiBDMTIuNDI0LDczLjk4OCAxMi4zOTksNzMuOTY3IDEyLjM4NCw3My45NCBMMi4xMDYsNTUuMTkgQzEuMDc1LDUzLjMxIDEuODU3LDUwLjg0NSAzLjg0OCw0OS42OTYgTDU5Ljg1OCwxNy4zNTIgQzYwLjUyNSwxNi45NjcgNjEuMjcxLDE2Ljc2NCA2Mi4wMTYsMTYuNzY0IEM2My40MzEsMTYuNzY0IDY0LjY2NiwxNy40NjYgNjUuMzI3LDE4LjY0NiBDNjUuMzM3LDE4LjY1NCA2NS4zNDUsMTguNjYzIDY1LjM1MSwxOC42NzQgTDY1LjU3OCwxOS4wODggQzY1LjU4NCwxOS4xIDY1LjU4OSwxOS4xMTIgNjUuNTkxLDE5LjEyNiBDNjUuOTg1LDE5LjgzOCA2Ni40NjksMjAuNDk3IDY3LjAzLDIxLjA4NSBMNjcuMzA1LDIxLjM1MSBDNjkuMTUxLDIzLjEzNyA3MS42NDksMjQuMTIgNzQuMzM2LDI0LjEyIEM3Ni4zMTMsMjQuMTIgNzguMjksMjMuNTgyIDgwLjA1MywyMi41NjMgQzgwLjA2NCwyMi41NTcgODAuMDc2LDIyLjU1MyA4MC4wODgsMjIuNTUgTDg3LjM3MiwxOC4zNDQgQzg4LjAzOCwxNy45NTkgODguNzg0LDE3Ljc1NiA4OS41MjksMTcuNzU2IEM5MC45NTYsMTcuNzU2IDkyLjIwMSwxOC40NzIgOTIuODU4LDE5LjY3IEw5Ni4xMDcsMjUuNTk5IEM5Ni4xMzgsMjUuNjU0IDk2LjExOCwyNS43MjQgOTYuMDYzLDI1Ljc1NiBMMTIuNTQ1LDczLjk4NSBDMTIuNTI2LDczLjk5NiAxMi41MDYsNzQuMDAxIDEyLjQ4Niw3NC4wMDEgTDEyLjQ4Niw3NC4wMDEgWiBNNjIuMDE2LDE2Ljk5NyBDNjEuMzEyLDE2Ljk5NyA2MC42MDYsMTcuMTkgNTkuOTc1LDE3LjU1NCBMMy45NjUsNDkuODk5IEMyLjA4Myw1MC45ODUgMS4zNDEsNTMuMzA4IDIuMzEsNTUuMDc4IEwxMi41MzEsNzMuNzIzIEw5NS44NDgsMjUuNjExIEw5Mi42NTMsMTkuNzgyIEM5Mi4wMzgsMTguNjYgOTAuODcsMTcuOTkgODkuNTI5LDE3Ljk5IEM4OC44MjUsMTcuOTkgODguMTE5LDE4LjE4MiA4Ny40ODksMTguNTQ3IEw4MC4xNzIsMjIuNzcyIEM4MC4xNjEsMjIuNzc4IDgwLjE0OSwyMi43ODIgODAuMTM3LDIyLjc4NSBDNzguMzQ2LDIzLjgxMSA3Ni4zNDEsMjQuMzU0IDc0LjMzNiwyNC4zNTQgQzcxLjU4OCwyNC4zNTQgNjkuMDMzLDIzLjM0NyA2Ny4xNDIsMjEuNTE5IEw2Ni44NjQsMjEuMjQ5IEM2Ni4yNzcsMjAuNjM0IDY1Ljc3NCwxOS45NDcgNjUuMzY3LDE5LjIwMyBDNjUuMzYsMTkuMTkyIDY1LjM1NiwxOS4xNzkgNjUuMzU0LDE5LjE2NiBMNjUuMTYzLDE4LjgxOSBDNjUuMTU0LDE4LjgxMSA2NS4xNDYsMTguODAxIDY1LjE0LDE4Ljc5IEM2NC41MjUsMTcuNjY3IDYzLjM1NywxNi45OTcgNjIuMDE2LDE2Ljk5NyBMNjIuMDE2LDE2Ljk5NyBaIiBpZD0iRmlsbC03IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTQyLjQzNCw0OC44MDggTDQyLjQzNCw0OC44MDggQzM5LjkyNCw0OC44MDcgMzcuNzM3LDQ3LjU1IDM2LjU4Miw0NS40NDMgQzM0Ljc3MSw0Mi4xMzkgMzYuMTQ0LDM3LjgwOSAzOS42NDEsMzUuNzg5IEw1MS45MzIsMjguNjkxIEM1My4xMDMsMjguMDE1IDU0LjQxMywyNy42NTggNTUuNzIxLDI3LjY1OCBDNTguMjMxLDI3LjY1OCA2MC40MTgsMjguOTE2IDYxLjU3MywzMS4wMjMgQzYzLjM4NCwzNC4zMjcgNjIuMDEyLDM4LjY1NyA1OC41MTQsNDAuNjc3IEw0Ni4yMjMsNDcuNzc1IEM0NS4wNTMsNDguNDUgNDMuNzQyLDQ4LjgwOCA0Mi40MzQsNDguODA4IEw0Mi40MzQsNDguODA4IFogTTU1LjcyMSwyOC4xMjUgQzU0LjQ5NSwyOC4xMjUgNTMuMjY1LDI4LjQ2MSA1Mi4xNjYsMjkuMDk2IEwzOS44NzUsMzYuMTk0IEMzNi41OTYsMzguMDg3IDM1LjMwMiw0Mi4xMzYgMzYuOTkyLDQ1LjIxOCBDMzguMDYzLDQ3LjE3MyA0MC4wOTgsNDguMzQgNDIuNDM0LDQ4LjM0IEM0My42NjEsNDguMzQgNDQuODksNDguMDA1IDQ1Ljk5LDQ3LjM3IEw1OC4yODEsNDAuMjcyIEM2MS41NiwzOC4zNzkgNjIuODUzLDM0LjMzIDYxLjE2NCwzMS4yNDggQzYwLjA5MiwyOS4yOTMgNTguMDU4LDI4LjEyNSA1NS43MjEsMjguMTI1IEw1NS43MjEsMjguMTI1IFoiIGlkPSJGaWxsLTgiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTQ5LjU4OCwyLjQwNyBDMTQ5LjU4OCwyLjQwNyAxNTUuNzY4LDUuOTc1IDE1Ni4zMjUsNi4yOTcgTDE1Ni4zMjUsNy4xODQgQzE1Ni4zMjUsNy4zNiAxNTYuMzM4LDcuNTQ0IDE1Ni4zNjIsNy43MzMgQzE1Ni4zNzMsNy44MTQgMTU2LjM4Miw3Ljg5NCAxNTYuMzksNy45NzUgQzE1Ni41Myw5LjM5IDE1Ny4zNjMsMTAuOTczIDE1OC40OTUsMTEuOTc0IEwxNjUuODkxLDE4LjUxOSBDMTY2LjA2OCwxOC42NzUgMTY2LjI0OSwxOC44MTQgMTY2LjQzMiwxOC45MzQgQzE2OC4wMTEsMTkuOTc0IDE2OS4zODIsMTkuNCAxNjkuNDk0LDE3LjY1MiBDMTY5LjU0MywxNi44NjggMTY5LjU1MSwxNi4wNTcgMTY5LjUxNywxNS4yMjMgTDE2OS41MTQsMTUuMDYzIEwxNjkuNTE0LDEzLjkxMiBDMTcwLjc4LDE0LjY0MiAxOTUuNTAxLDI4LjkxNSAxOTUuNTAxLDI4LjkxNSBMMTk1LjUwMSw4Mi45MTUgQzE5NS41MDEsODQuMDA1IDE5NC43MzEsODQuNDQ1IDE5My43ODEsODMuODk3IEwxNTEuMzA4LDU5LjM3NCBDMTUwLjM1OCw1OC44MjYgMTQ5LjU4OCw1Ny40OTcgMTQ5LjU4OCw1Ni40MDggTDE0OS41ODgsMjIuMzc1IiBpZD0iRmlsbC05IiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE5NC41NTMsODQuMjUgQzE5NC4yOTYsODQuMjUgMTk0LjAxMyw4NC4xNjUgMTkzLjcyMiw4My45OTcgTDE1MS4yNSw1OS40NzYgQzE1MC4yNjksNTguOTA5IDE0OS40NzEsNTcuNTMzIDE0OS40NzEsNTYuNDA4IEwxNDkuNDcxLDIyLjM3NSBMMTQ5LjcwNSwyMi4zNzUgTDE0OS43MDUsNTYuNDA4IEMxNDkuNzA1LDU3LjQ1OSAxNTAuNDUsNTguNzQ0IDE1MS4zNjYsNTkuMjc0IEwxOTMuODM5LDgzLjc5NSBDMTk0LjI2Myw4NC4wNCAxOTQuNjU1LDg0LjA4MyAxOTQuOTQyLDgzLjkxNyBDMTk1LjIyNyw4My43NTMgMTk1LjM4NCw4My4zOTcgMTk1LjM4NCw4Mi45MTUgTDE5NS4zODQsMjguOTgyIEMxOTQuMTAyLDI4LjI0MiAxNzIuMTA0LDE1LjU0MiAxNjkuNjMxLDE0LjExNCBMMTY5LjYzNCwxNS4yMiBDMTY5LjY2OCwxNi4wNTIgMTY5LjY2LDE2Ljg3NCAxNjkuNjEsMTcuNjU5IEMxNjkuNTU2LDE4LjUwMyAxNjkuMjE0LDE5LjEyMyAxNjguNjQ3LDE5LjQwNSBDMTY4LjAyOCwxOS43MTQgMTY3LjE5NywxOS41NzggMTY2LjM2NywxOS4wMzIgQzE2Ni4xODEsMTguOTA5IDE2NS45OTUsMTguNzY2IDE2NS44MTQsMTguNjA2IEwxNTguNDE3LDEyLjA2MiBDMTU3LjI1OSwxMS4wMzYgMTU2LjQxOCw5LjQzNyAxNTYuMjc0LDcuOTg2IEMxNTYuMjY2LDcuOTA3IDE1Ni4yNTcsNy44MjcgMTU2LjI0Nyw3Ljc0OCBDMTU2LjIyMSw3LjU1NSAxNTYuMjA5LDcuMzY1IDE1Ni4yMDksNy4xODQgTDE1Ni4yMDksNi4zNjQgQzE1NS4zNzUsNS44ODMgMTQ5LjUyOSwyLjUwOCAxNDkuNTI5LDIuNTA4IEwxNDkuNjQ2LDIuMzA2IEMxNDkuNjQ2LDIuMzA2IDE1NS44MjcsNS44NzQgMTU2LjM4NCw2LjE5NiBMMTU2LjQ0Miw2LjIzIEwxNTYuNDQyLDcuMTg0IEMxNTYuNDQyLDcuMzU1IDE1Ni40NTQsNy41MzUgMTU2LjQ3OCw3LjcxNyBDMTU2LjQ4OSw3LjggMTU2LjQ5OSw3Ljg4MiAxNTYuNTA3LDcuOTYzIEMxNTYuNjQ1LDkuMzU4IDE1Ny40NTUsMTAuODk4IDE1OC41NzIsMTEuODg2IEwxNjUuOTY5LDE4LjQzMSBDMTY2LjE0MiwxOC41ODQgMTY2LjMxOSwxOC43MiAxNjYuNDk2LDE4LjgzNyBDMTY3LjI1NCwxOS4zMzYgMTY4LDE5LjQ2NyAxNjguNTQzLDE5LjE5NiBDMTY5LjAzMywxOC45NTMgMTY5LjMyOSwxOC40MDEgMTY5LjM3NywxNy42NDUgQzE2OS40MjcsMTYuODY3IDE2OS40MzQsMTYuMDU0IDE2OS40MDEsMTUuMjI4IEwxNjkuMzk3LDE1LjA2NSBMMTY5LjM5NywxMy43MSBMMTY5LjU3MiwxMy44MSBDMTcwLjgzOSwxNC41NDEgMTk1LjU1OSwyOC44MTQgMTk1LjU1OSwyOC44MTQgTDE5NS42MTgsMjguODQ3IEwxOTUuNjE4LDgyLjkxNSBDMTk1LjYxOCw4My40ODQgMTk1LjQyLDgzLjkxMSAxOTUuMDU5LDg0LjExOSBDMTk0LjkwOCw4NC4yMDYgMTk0LjczNyw4NC4yNSAxOTQuNTUzLDg0LjI1IiBpZD0iRmlsbC0xMCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNDUuNjg1LDU2LjE2MSBMMTY5LjgsNzAuMDgzIEwxNDMuODIyLDg1LjA4MSBMMTQyLjM2LDg0Ljc3NCBDMTM1LjgyNiw4Mi42MDQgMTI4LjczMiw4MS4wNDYgMTIxLjM0MSw4MC4xNTggQzExNi45NzYsNzkuNjM0IDExMi42NzgsODEuMjU0IDExMS43NDMsODMuNzc4IEMxMTEuNTA2LDg0LjQxNCAxMTEuNTAzLDg1LjA3MSAxMTEuNzMyLDg1LjcwNiBDMTEzLjI3LDg5Ljk3MyAxMTUuOTY4LDk0LjA2OSAxMTkuNzI3LDk3Ljg0MSBMMTIwLjI1OSw5OC42ODYgQzEyMC4yNiw5OC42ODUgOTQuMjgyLDExMy42ODMgOTQuMjgyLDExMy42ODMgTDcwLjE2Nyw5OS43NjEgTDE0NS42ODUsNTYuMTYxIiBpZD0iRmlsbC0xMSIgZmlsbD0iI0ZGRkZGRiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik05NC4yODIsMTEzLjgxOCBMOTQuMjIzLDExMy43ODUgTDY5LjkzMyw5OS43NjEgTDcwLjEwOCw5OS42NiBMMTQ1LjY4NSw1Ni4wMjYgTDE0NS43NDMsNTYuMDU5IEwxNzAuMDMzLDcwLjA4MyBMMTQzLjg0Miw4NS4yMDUgTDE0My43OTcsODUuMTk1IEMxNDMuNzcyLDg1LjE5IDE0Mi4zMzYsODQuODg4IDE0Mi4zMzYsODQuODg4IEMxMzUuNzg3LDgyLjcxNCAxMjguNzIzLDgxLjE2MyAxMjEuMzI3LDgwLjI3NCBDMTIwLjc4OCw4MC4yMDkgMTIwLjIzNiw4MC4xNzcgMTE5LjY4OSw4MC4xNzcgQzExNS45MzEsODAuMTc3IDExMi42MzUsODEuNzA4IDExMS44NTIsODMuODE5IEMxMTEuNjI0LDg0LjQzMiAxMTEuNjIxLDg1LjA1MyAxMTEuODQyLDg1LjY2NyBDMTEzLjM3Nyw4OS45MjUgMTE2LjA1OCw5My45OTMgMTE5LjgxLDk3Ljc1OCBMMTE5LjgyNiw5Ny43NzkgTDEyMC4zNTIsOTguNjE0IEMxMjAuMzU0LDk4LjYxNyAxMjAuMzU2LDk4LjYyIDEyMC4zNTgsOTguNjI0IEwxMjAuNDIyLDk4LjcyNiBMMTIwLjMxNyw5OC43ODcgQzEyMC4yNjQsOTguODE4IDk0LjU5OSwxMTMuNjM1IDk0LjM0LDExMy43ODUgTDk0LjI4MiwxMTMuODE4IEw5NC4yODIsMTEzLjgxOCBaIE03MC40MDEsOTkuNzYxIEw5NC4yODIsMTEzLjU0OSBMMTE5LjA4NCw5OS4yMjkgQzExOS42Myw5OC45MTQgMTE5LjkzLDk4Ljc0IDEyMC4xMDEsOTguNjU0IEwxMTkuNjM1LDk3LjkxNCBDMTE1Ljg2NCw5NC4xMjcgMTEzLjE2OCw5MC4wMzMgMTExLjYyMiw4NS43NDYgQzExMS4zODIsODUuMDc5IDExMS4zODYsODQuNDA0IDExMS42MzMsODMuNzM4IEMxMTIuNDQ4LDgxLjUzOSAxMTUuODM2LDc5Ljk0MyAxMTkuNjg5LDc5Ljk0MyBDMTIwLjI0Niw3OS45NDMgMTIwLjgwNiw3OS45NzYgMTIxLjM1NSw4MC4wNDIgQzEyOC43NjcsODAuOTMzIDEzNS44NDYsODIuNDg3IDE0Mi4zOTYsODQuNjYzIEMxNDMuMjMyLDg0LjgzOCAxNDMuNjExLDg0LjkxNyAxNDMuNzg2LDg0Ljk2NyBMMTY5LjU2Niw3MC4wODMgTDE0NS42ODUsNTYuMjk1IEw3MC40MDEsOTkuNzYxIEw3MC40MDEsOTkuNzYxIFoiIGlkPSJGaWxsLTEyIiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE2Ny4yMywxOC45NzkgTDE2Ny4yMyw2OS44NSBMMTM5LjkwOSw4NS42MjMgTDEzMy40NDgsNzEuNDU2IEMxMzIuNTM4LDY5LjQ2IDEzMC4wMiw2OS43MTggMTI3LjgyNCw3Mi4wMyBDMTI2Ljc2OSw3My4xNCAxMjUuOTMxLDc0LjU4NSAxMjUuNDk0LDc2LjA0OCBMMTE5LjAzNCw5Ny42NzYgTDkxLjcxMiwxMTMuNDUgTDkxLjcxMiw2Mi41NzkgTDE2Ny4yMywxOC45NzkiIGlkPSJGaWxsLTEzIiBmaWxsPSIjRkZGRkZGIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTkxLjcxMiwxMTMuNTY3IEM5MS42OTIsMTEzLjU2NyA5MS42NzIsMTEzLjU2MSA5MS42NTMsMTEzLjU1MSBDOTEuNjE4LDExMy41MyA5MS41OTUsMTEzLjQ5MiA5MS41OTUsMTEzLjQ1IEw5MS41OTUsNjIuNTc5IEM5MS41OTUsNjIuNTM3IDkxLjYxOCw2Mi40OTkgOTEuNjUzLDYyLjQ3OCBMMTY3LjE3MiwxOC44NzggQzE2Ny4yMDgsMTguODU3IDE2Ny4yNTIsMTguODU3IDE2Ny4yODgsMTguODc4IEMxNjcuMzI0LDE4Ljg5OSAxNjcuMzQ3LDE4LjkzNyAxNjcuMzQ3LDE4Ljk3OSBMMTY3LjM0Nyw2OS44NSBDMTY3LjM0Nyw2OS44OTEgMTY3LjMyNCw2OS45MyAxNjcuMjg4LDY5Ljk1IEwxMzkuOTY3LDg1LjcyNSBDMTM5LjkzOSw4NS43NDEgMTM5LjkwNSw4NS43NDUgMTM5Ljg3Myw4NS43MzUgQzEzOS44NDIsODUuNzI1IDEzOS44MTYsODUuNzAyIDEzOS44MDIsODUuNjcyIEwxMzMuMzQyLDcxLjUwNCBDMTMyLjk2Nyw3MC42ODIgMTMyLjI4LDcwLjIyOSAxMzEuNDA4LDcwLjIyOSBDMTMwLjMxOSw3MC4yMjkgMTI5LjA0NCw3MC45MTUgMTI3LjkwOCw3Mi4xMSBDMTI2Ljg3NCw3My4yIDEyNi4wMzQsNzQuNjQ3IDEyNS42MDYsNzYuMDgyIEwxMTkuMTQ2LDk3LjcwOSBDMTE5LjEzNyw5Ny43MzggMTE5LjExOCw5Ny43NjIgMTE5LjA5Miw5Ny43NzcgTDkxLjc3LDExMy41NTEgQzkxLjc1MiwxMTMuNTYxIDkxLjczMiwxMTMuNTY3IDkxLjcxMiwxMTMuNTY3IEw5MS43MTIsMTEzLjU2NyBaIE05MS44MjksNjIuNjQ3IEw5MS44MjksMTEzLjI0OCBMMTE4LjkzNSw5Ny41OTggTDEyNS4zODIsNzYuMDE1IEMxMjUuODI3LDc0LjUyNSAxMjYuNjY0LDczLjA4MSAxMjcuNzM5LDcxLjk1IEMxMjguOTE5LDcwLjcwOCAxMzAuMjU2LDY5Ljk5NiAxMzEuNDA4LDY5Ljk5NiBDMTMyLjM3Nyw2OS45OTYgMTMzLjEzOSw3MC40OTcgMTMzLjU1NCw3MS40MDcgTDEzOS45NjEsODUuNDU4IEwxNjcuMTEzLDY5Ljc4MiBMMTY3LjExMywxOS4xODEgTDkxLjgyOSw2Mi42NDcgTDkxLjgyOSw2Mi42NDcgWiIgaWQ9IkZpbGwtMTQiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTY4LjU0MywxOS4yMTMgTDE2OC41NDMsNzAuMDgzIEwxNDEuMjIxLDg1Ljg1NyBMMTM0Ljc2MSw3MS42ODkgQzEzMy44NTEsNjkuNjk0IDEzMS4zMzMsNjkuOTUxIDEyOS4xMzcsNzIuMjYzIEMxMjguMDgyLDczLjM3NCAxMjcuMjQ0LDc0LjgxOSAxMjYuODA3LDc2LjI4MiBMMTIwLjM0Niw5Ny45MDkgTDkzLjAyNSwxMTMuNjgzIEw5My4wMjUsNjIuODEzIEwxNjguNTQzLDE5LjIxMyIgaWQ9IkZpbGwtMTUiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNOTMuMDI1LDExMy44IEM5My4wMDUsMTEzLjggOTIuOTg0LDExMy43OTUgOTIuOTY2LDExMy43ODUgQzkyLjkzMSwxMTMuNzY0IDkyLjkwOCwxMTMuNzI1IDkyLjkwOCwxMTMuNjg0IEw5Mi45MDgsNjIuODEzIEM5Mi45MDgsNjIuNzcxIDkyLjkzMSw2Mi43MzMgOTIuOTY2LDYyLjcxMiBMMTY4LjQ4NCwxOS4xMTIgQzE2OC41MiwxOS4wOSAxNjguNTY1LDE5LjA5IDE2OC42MDEsMTkuMTEyIEMxNjguNjM3LDE5LjEzMiAxNjguNjYsMTkuMTcxIDE2OC42NiwxOS4yMTIgTDE2OC42Niw3MC4wODMgQzE2OC42Niw3MC4xMjUgMTY4LjYzNyw3MC4xNjQgMTY4LjYwMSw3MC4xODQgTDE0MS4yOCw4NS45NTggQzE0MS4yNTEsODUuOTc1IDE0MS4yMTcsODUuOTc5IDE0MS4xODYsODUuOTY4IEMxNDEuMTU0LDg1Ljk1OCAxNDEuMTI5LDg1LjkzNiAxNDEuMTE1LDg1LjkwNiBMMTM0LjY1NSw3MS43MzggQzEzNC4yOCw3MC45MTUgMTMzLjU5Myw3MC40NjMgMTMyLjcyLDcwLjQ2MyBDMTMxLjYzMiw3MC40NjMgMTMwLjM1Nyw3MS4xNDggMTI5LjIyMSw3Mi4zNDQgQzEyOC4xODYsNzMuNDMzIDEyNy4zNDcsNzQuODgxIDEyNi45MTksNzYuMzE1IEwxMjAuNDU4LDk3Ljk0MyBDMTIwLjQ1LDk3Ljk3MiAxMjAuNDMxLDk3Ljk5NiAxMjAuNDA1LDk4LjAxIEw5My4wODMsMTEzLjc4NSBDOTMuMDY1LDExMy43OTUgOTMuMDQ1LDExMy44IDkzLjAyNSwxMTMuOCBMOTMuMDI1LDExMy44IFogTTkzLjE0Miw2Mi44ODEgTDkzLjE0MiwxMTMuNDgxIEwxMjAuMjQ4LDk3LjgzMiBMMTI2LjY5NSw3Ni4yNDggQzEyNy4xNCw3NC43NTggMTI3Ljk3Nyw3My4zMTUgMTI5LjA1Miw3Mi4xODMgQzEzMC4yMzEsNzAuOTQyIDEzMS41NjgsNzAuMjI5IDEzMi43Miw3MC4yMjkgQzEzMy42ODksNzAuMjI5IDEzNC40NTIsNzAuNzMxIDEzNC44NjcsNzEuNjQxIEwxNDEuMjc0LDg1LjY5MiBMMTY4LjQyNiw3MC4wMTYgTDE2OC40MjYsMTkuNDE1IEw5My4xNDIsNjIuODgxIEw5My4xNDIsNjIuODgxIFoiIGlkPSJGaWxsLTE2IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE2OS44LDcwLjA4MyBMMTQyLjQ3OCw4NS44NTcgTDEzNi4wMTgsNzEuNjg5IEMxMzUuMTA4LDY5LjY5NCAxMzIuNTksNjkuOTUxIDEzMC4zOTMsNzIuMjYzIEMxMjkuMzM5LDczLjM3NCAxMjguNSw3NC44MTkgMTI4LjA2NCw3Ni4yODIgTDEyMS42MDMsOTcuOTA5IEw5NC4yODIsMTEzLjY4MyBMOTQuMjgyLDYyLjgxMyBMMTY5LjgsMTkuMjEzIEwxNjkuOCw3MC4wODMgWiIgaWQ9IkZpbGwtMTciIGZpbGw9IiNGQUZBRkEiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNOTQuMjgyLDExMy45MTcgQzk0LjI0MSwxMTMuOTE3IDk0LjIwMSwxMTMuOTA3IDk0LjE2NSwxMTMuODg2IEM5NC4wOTMsMTEzLjg0NSA5NC4wNDgsMTEzLjc2NyA5NC4wNDgsMTEzLjY4NCBMOTQuMDQ4LDYyLjgxMyBDOTQuMDQ4LDYyLjczIDk0LjA5Myw2Mi42NTIgOTQuMTY1LDYyLjYxMSBMMTY5LjY4MywxOS4wMSBDMTY5Ljc1NSwxOC45NjkgMTY5Ljg0NCwxOC45NjkgMTY5LjkxNywxOS4wMSBDMTY5Ljk4OSwxOS4wNTIgMTcwLjAzMywxOS4xMjkgMTcwLjAzMywxOS4yMTIgTDE3MC4wMzMsNzAuMDgzIEMxNzAuMDMzLDcwLjE2NiAxNjkuOTg5LDcwLjI0NCAxNjkuOTE3LDcwLjI4NSBMMTQyLjU5NSw4Ni4wNiBDMTQyLjUzOCw4Ni4wOTIgMTQyLjQ2OSw4Ni4xIDE0Mi40MDcsODYuMDggQzE0Mi4zNDQsODYuMDYgMTQyLjI5Myw4Ni4wMTQgMTQyLjI2Niw4NS45NTQgTDEzNS44MDUsNzEuNzg2IEMxMzUuNDQ1LDcwLjk5NyAxMzQuODEzLDcwLjU4IDEzMy45NzcsNzAuNTggQzEzMi45MjEsNzAuNTggMTMxLjY3Niw3MS4yNTIgMTMwLjU2Miw3Mi40MjQgQzEyOS41NCw3My41MDEgMTI4LjcxMSw3NC45MzEgMTI4LjI4Nyw3Ni4zNDggTDEyMS44MjcsOTcuOTc2IEMxMjEuODEsOTguMDM0IDEyMS43NzEsOTguMDgyIDEyMS43Miw5OC4xMTIgTDk0LjM5OCwxMTMuODg2IEM5NC4zNjIsMTEzLjkwNyA5NC4zMjIsMTEzLjkxNyA5NC4yODIsMTEzLjkxNyBMOTQuMjgyLDExMy45MTcgWiBNOTQuNTE1LDYyLjk0OCBMOTQuNTE1LDExMy4yNzkgTDEyMS40MDYsOTcuNzU0IEwxMjcuODQsNzYuMjE1IEMxMjguMjksNzQuNzA4IDEyOS4xMzcsNzMuMjQ3IDEzMC4yMjQsNzIuMTAzIEMxMzEuNDI1LDcwLjgzOCAxMzIuNzkzLDcwLjExMiAxMzMuOTc3LDcwLjExMiBDMTM0Ljk5NSw3MC4xMTIgMTM1Ljc5NSw3MC42MzggMTM2LjIzLDcxLjU5MiBMMTQyLjU4NCw4NS41MjYgTDE2OS41NjYsNjkuOTQ4IEwxNjkuNTY2LDE5LjYxNyBMOTQuNTE1LDYyLjk0OCBMOTQuNTE1LDYyLjk0OCBaIiBpZD0iRmlsbC0xOCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMDkuODk0LDkyLjk0MyBMMTA5Ljg5NCw5Mi45NDMgQzEwOC4xMiw5Mi45NDMgMTA2LjY1Myw5Mi4yMTggMTA1LjY1LDkwLjgyMyBDMTA1LjU4Myw5MC43MzEgMTA1LjU5Myw5MC42MSAxMDUuNjczLDkwLjUyOSBDMTA1Ljc1Myw5MC40NDggMTA1Ljg4LDkwLjQ0IDEwNS45NzQsOTAuNTA2IEMxMDYuNzU0LDkxLjA1MyAxMDcuNjc5LDkxLjMzMyAxMDguNzI0LDkxLjMzMyBDMTEwLjA0Nyw5MS4zMzMgMTExLjQ3OCw5MC44OTQgMTEyLjk4LDkwLjAyNyBDMTE4LjI5MSw4Ni45NiAxMjIuNjExLDc5LjUwOSAxMjIuNjExLDczLjQxNiBDMTIyLjYxMSw3MS40ODkgMTIyLjE2OSw2OS44NTYgMTIxLjMzMyw2OC42OTIgQzEyMS4yNjYsNjguNiAxMjEuMjc2LDY4LjQ3MyAxMjEuMzU2LDY4LjM5MiBDMTIxLjQzNiw2OC4zMTEgMTIxLjU2Myw2OC4yOTkgMTIxLjY1Niw2OC4zNjUgQzEyMy4zMjcsNjkuNTM3IDEyNC4yNDcsNzEuNzQ2IDEyNC4yNDcsNzQuNTg0IEMxMjQuMjQ3LDgwLjgyNiAxMTkuODIxLDg4LjQ0NyAxMTQuMzgyLDkxLjU4NyBDMTEyLjgwOCw5Mi40OTUgMTExLjI5OCw5Mi45NDMgMTA5Ljg5NCw5Mi45NDMgTDEwOS44OTQsOTIuOTQzIFogTTEwNi45MjUsOTEuNDAxIEMxMDcuNzM4LDkyLjA1MiAxMDguNzQ1LDkyLjI3OCAxMDkuODkzLDkyLjI3OCBMMTA5Ljg5NCw5Mi4yNzggQzExMS4yMTUsOTIuMjc4IDExMi42NDcsOTEuOTUxIDExNC4xNDgsOTEuMDg0IEMxMTkuNDU5LDg4LjAxNyAxMjMuNzgsODAuNjIxIDEyMy43OCw3NC41MjggQzEyMy43OCw3Mi41NDkgMTIzLjMxNyw3MC45MjkgMTIyLjQ1NCw2OS43NjcgQzEyMi44NjUsNzAuODAyIDEyMy4wNzksNzIuMDQyIDEyMy4wNzksNzMuNDAyIEMxMjMuMDc5LDc5LjY0NSAxMTguNjUzLDg3LjI4NSAxMTMuMjE0LDkwLjQyNSBDMTExLjY0LDkxLjMzNCAxMTAuMTMsOTEuNzQyIDEwOC43MjQsOTEuNzQyIEMxMDguMDgzLDkxLjc0MiAxMDcuNDgxLDkxLjU5MyAxMDYuOTI1LDkxLjQwMSBMMTA2LjkyNSw5MS40MDEgWiIgaWQ9IkZpbGwtMTkiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEzLjA5Nyw5MC4yMyBDMTE4LjQ4MSw4Ny4xMjIgMTIyLjg0NSw3OS41OTQgMTIyLjg0NSw3My40MTYgQzEyMi44NDUsNzEuMzY1IDEyMi4zNjIsNjkuNzI0IDEyMS41MjIsNjguNTU2IEMxMTkuNzM4LDY3LjMwNCAxMTcuMTQ4LDY3LjM2MiAxMTQuMjY1LDY5LjAyNiBDMTA4Ljg4MSw3Mi4xMzQgMTA0LjUxNyw3OS42NjIgMTA0LjUxNyw4NS44NCBDMTA0LjUxNyw4Ny44OTEgMTA1LDg5LjUzMiAxMDUuODQsOTAuNyBDMTA3LjYyNCw5MS45NTIgMTEwLjIxNCw5MS44OTQgMTEzLjA5Nyw5MC4yMyIgaWQ9IkZpbGwtMjAiIGZpbGw9IiNGQUZBRkEiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTA4LjcyNCw5MS42MTQgTDEwOC43MjQsOTEuNjE0IEMxMDcuNTgyLDkxLjYxNCAxMDYuNTY2LDkxLjQwMSAxMDUuNzA1LDkwLjc5NyBDMTA1LjY4NCw5MC43ODMgMTA1LjY2NSw5MC44MTEgMTA1LjY1LDkwLjc5IEMxMDQuNzU2LDg5LjU0NiAxMDQuMjgzLDg3Ljg0MiAxMDQuMjgzLDg1LjgxNyBDMTA0LjI4Myw3OS41NzUgMTA4LjcwOSw3MS45NTMgMTE0LjE0OCw2OC44MTIgQzExNS43MjIsNjcuOTA0IDExNy4yMzIsNjcuNDQ5IDExOC42MzgsNjcuNDQ5IEMxMTkuNzgsNjcuNDQ5IDEyMC43OTYsNjcuNzU4IDEyMS42NTYsNjguMzYyIEMxMjEuNjc4LDY4LjM3NyAxMjEuNjk3LDY4LjM5NyAxMjEuNzEyLDY4LjQxOCBDMTIyLjYwNiw2OS42NjIgMTIzLjA3OSw3MS4zOSAxMjMuMDc5LDczLjQxNSBDMTIzLjA3OSw3OS42NTggMTE4LjY1Myw4Ny4xOTggMTEzLjIxNCw5MC4zMzggQzExMS42NCw5MS4yNDcgMTEwLjEzLDkxLjYxNCAxMDguNzI0LDkxLjYxNCBMMTA4LjcyNCw5MS42MTQgWiBNMTA2LjAwNiw5MC41MDUgQzEwNi43OCw5MS4wMzcgMTA3LjY5NCw5MS4yODEgMTA4LjcyNCw5MS4yODEgQzExMC4wNDcsOTEuMjgxIDExMS40NzgsOTAuODY4IDExMi45OCw5MC4wMDEgQzExOC4yOTEsODYuOTM1IDEyMi42MTEsNzkuNDk2IDEyMi42MTEsNzMuNDAzIEMxMjIuNjExLDcxLjQ5NCAxMjIuMTc3LDY5Ljg4IDEyMS4zNTYsNjguNzE4IEMxMjAuNTgyLDY4LjE4NSAxMTkuNjY4LDY3LjkxOSAxMTguNjM4LDY3LjkxOSBDMTE3LjMxNSw2Ny45MTkgMTE1Ljg4Myw2OC4zNiAxMTQuMzgyLDY5LjIyNyBDMTA5LjA3MSw3Mi4yOTMgMTA0Ljc1MSw3OS43MzMgMTA0Ljc1MSw4NS44MjYgQzEwNC43NTEsODcuNzM1IDEwNS4xODUsODkuMzQzIDEwNi4wMDYsOTAuNTA1IEwxMDYuMDA2LDkwLjUwNSBaIiBpZD0iRmlsbC0yMSIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNDkuMzE4LDcuMjYyIEwxMzkuMzM0LDE2LjE0IEwxNTUuMjI3LDI3LjE3MSBMMTYwLjgxNiwyMS4wNTkgTDE0OS4zMTgsNy4yNjIiIGlkPSJGaWxsLTIyIiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE2OS42NzYsMTMuODQgTDE1OS45MjgsMTkuNDY3IEMxNTYuMjg2LDIxLjU3IDE1MC40LDIxLjU4IDE0Ni43ODEsMTkuNDkxIEMxNDMuMTYxLDE3LjQwMiAxNDMuMTgsMTQuMDAzIDE0Ni44MjIsMTEuOSBMMTU2LjMxNyw2LjI5MiBMMTQ5LjU4OCwyLjQwNyBMNjcuNzUyLDQ5LjQ3OCBMMTEzLjY3NSw3NS45OTIgTDExNi43NTYsNzQuMjEzIEMxMTcuMzg3LDczLjg0OCAxMTcuNjI1LDczLjMxNSAxMTcuMzc0LDcyLjgyMyBDMTE1LjAxNyw2OC4xOTEgMTE0Ljc4MSw2My4yNzcgMTE2LjY5MSw1OC41NjEgQzEyMi4zMjksNDQuNjQxIDE0MS4yLDMzLjc0NiAxNjUuMzA5LDMwLjQ5MSBDMTczLjQ3OCwyOS4zODggMTgxLjk4OSwyOS41MjQgMTkwLjAxMywzMC44ODUgQzE5MC44NjUsMzEuMDMgMTkxLjc4OSwzMC44OTMgMTkyLjQyLDMwLjUyOCBMMTk1LjUwMSwyOC43NSBMMTY5LjY3NiwxMy44NCIgaWQ9IkZpbGwtMjMiIGZpbGw9IiNGQUZBRkEiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEzLjY3NSw3Ni40NTkgQzExMy41OTQsNzYuNDU5IDExMy41MTQsNzYuNDM4IDExMy40NDIsNzYuMzk3IEw2Ny41MTgsNDkuODgyIEM2Ny4zNzQsNDkuNzk5IDY3LjI4NCw0OS42NDUgNjcuMjg1LDQ5LjQ3OCBDNjcuMjg1LDQ5LjMxMSA2Ny4zNzQsNDkuMTU3IDY3LjUxOSw0OS4wNzMgTDE0OS4zNTUsMi4wMDIgQzE0OS40OTksMS45MTkgMTQ5LjY3NywxLjkxOSAxNDkuODIxLDIuMDAyIEwxNTYuNTUsNS44ODcgQzE1Ni43NzQsNi4wMTcgMTU2Ljg1LDYuMzAyIDE1Ni43MjIsNi41MjYgQzE1Ni41OTIsNi43NDkgMTU2LjMwNyw2LjgyNiAxNTYuMDgzLDYuNjk2IEwxNDkuNTg3LDIuOTQ2IEw2OC42ODcsNDkuNDc5IEwxMTMuNjc1LDc1LjQ1MiBMMTE2LjUyMyw3My44MDggQzExNi43MTUsNzMuNjk3IDExNy4xNDMsNzMuMzk5IDExNi45NTgsNzMuMDM1IEMxMTQuNTQyLDY4LjI4NyAxMTQuMyw2My4yMjEgMTE2LjI1OCw1OC4zODUgQzExOS4wNjQsNTEuNDU4IDEyNS4xNDMsNDUuMTQzIDEzMy44NCw0MC4xMjIgQzE0Mi40OTcsMzUuMTI0IDE1My4zNTgsMzEuNjMzIDE2NS4yNDcsMzAuMDI4IEMxNzMuNDQ1LDI4LjkyMSAxODIuMDM3LDI5LjA1OCAxOTAuMDkxLDMwLjQyNSBDMTkwLjgzLDMwLjU1IDE5MS42NTIsMzAuNDMyIDE5Mi4xODYsMzAuMTI0IEwxOTQuNTY3LDI4Ljc1IEwxNjkuNDQyLDE0LjI0NCBDMTY5LjIxOSwxNC4xMTUgMTY5LjE0MiwxMy44MjkgMTY5LjI3MSwxMy42MDYgQzE2OS40LDEzLjM4MiAxNjkuNjg1LDEzLjMwNiAxNjkuOTA5LDEzLjQzNSBMMTk1LjczNCwyOC4zNDUgQzE5NS44NzksMjguNDI4IDE5NS45NjgsMjguNTgzIDE5NS45NjgsMjguNzUgQzE5NS45NjgsMjguOTE2IDE5NS44NzksMjkuMDcxIDE5NS43MzQsMjkuMTU0IEwxOTIuNjUzLDMwLjkzMyBDMTkxLjkzMiwzMS4zNSAxOTAuODksMzEuNTA4IDE4OS45MzUsMzEuMzQ2IEMxODEuOTcyLDI5Ljk5NSAxNzMuNDc4LDI5Ljg2IDE2NS4zNzIsMzAuOTU0IEMxNTMuNjAyLDMyLjU0MyAxNDIuODYsMzUuOTkzIDEzNC4zMDcsNDAuOTMxIEMxMjUuNzkzLDQ1Ljg0NyAxMTkuODUxLDUyLjAwNCAxMTcuMTI0LDU4LjczNiBDMTE1LjI3LDYzLjMxNCAxMTUuNTAxLDY4LjExMiAxMTcuNzksNzIuNjExIEMxMTguMTYsNzMuMzM2IDExNy44NDUsNzQuMTI0IDExNi45OSw3NC42MTcgTDExMy45MDksNzYuMzk3IEMxMTMuODM2LDc2LjQzOCAxMTMuNzU2LDc2LjQ1OSAxMTMuNjc1LDc2LjQ1OSIgaWQ9IkZpbGwtMjQiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTUzLjMxNiwyMS4yNzkgQzE1MC45MDMsMjEuMjc5IDE0OC40OTUsMjAuNzUxIDE0Ni42NjQsMTkuNjkzIEMxNDQuODQ2LDE4LjY0NCAxNDMuODQ0LDE3LjIzMiAxNDMuODQ0LDE1LjcxOCBDMTQzLjg0NCwxNC4xOTEgMTQ0Ljg2LDEyLjc2MyAxNDYuNzA1LDExLjY5OCBMMTU2LjE5OCw2LjA5MSBDMTU2LjMwOSw2LjAyNSAxNTYuNDUyLDYuMDYyIDE1Ni41MTgsNi4xNzMgQzE1Ni41ODMsNi4yODQgMTU2LjU0Nyw2LjQyNyAxNTYuNDM2LDYuNDkzIEwxNDYuOTQsMTIuMTAyIEMxNDUuMjQ0LDEzLjA4MSAxNDQuMzEyLDE0LjM2NSAxNDQuMzEyLDE1LjcxOCBDMTQ0LjMxMiwxNy4wNTggMTQ1LjIzLDE4LjMyNiAxNDYuODk3LDE5LjI4OSBDMTUwLjQ0NiwyMS4zMzggMTU2LjI0LDIxLjMyNyAxNTkuODExLDE5LjI2NSBMMTY5LjU1OSwxMy42MzcgQzE2OS42NywxMy41NzMgMTY5LjgxMywxMy42MTEgMTY5Ljg3OCwxMy43MjMgQzE2OS45NDMsMTMuODM0IDE2OS45MDQsMTMuOTc3IDE2OS43OTMsMTQuMDQyIEwxNjAuMDQ1LDE5LjY3IEMxNTguMTg3LDIwLjc0MiAxNTUuNzQ5LDIxLjI3OSAxNTMuMzE2LDIxLjI3OSIgaWQ9IkZpbGwtMjUiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEzLjY3NSw3NS45OTIgTDY3Ljc2Miw0OS40ODQiIGlkPSJGaWxsLTI2IiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTExMy42NzUsNzYuMzQyIEMxMTMuNjE1LDc2LjM0MiAxMTMuNTU1LDc2LjMyNyAxMTMuNSw3Ni4yOTUgTDY3LjU4Nyw0OS43ODcgQzY3LjQxOSw0OS42OSA2Ny4zNjIsNDkuNDc2IDY3LjQ1OSw0OS4zMDkgQzY3LjU1Niw0OS4xNDEgNjcuNzcsNDkuMDgzIDY3LjkzNyw0OS4xOCBMMTEzLjg1LDc1LjY4OCBDMTE0LjAxOCw3NS43ODUgMTE0LjA3NSw3NiAxMTMuOTc4LDc2LjE2NyBDMTEzLjkxNCw3Ni4yNzkgMTEzLjc5Niw3Ni4zNDIgMTEzLjY3NSw3Ni4zNDIiIGlkPSJGaWxsLTI3IiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTY3Ljc2Miw0OS40ODQgTDY3Ljc2MiwxMDMuNDg1IEM2Ny43NjIsMTA0LjU3NSA2OC41MzIsMTA1LjkwMyA2OS40ODIsMTA2LjQ1MiBMMTExLjk1NSwxMzAuOTczIEMxMTIuOTA1LDEzMS41MjIgMTEzLjY3NSwxMzEuMDgzIDExMy42NzUsMTI5Ljk5MyBMMTEzLjY3NSw3NS45OTIiIGlkPSJGaWxsLTI4IiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTExMi43MjcsMTMxLjU2MSBDMTEyLjQzLDEzMS41NjEgMTEyLjEwNywxMzEuNDY2IDExMS43OCwxMzEuMjc2IEw2OS4zMDcsMTA2Ljc1NSBDNjguMjQ0LDEwNi4xNDIgNjcuNDEyLDEwNC43MDUgNjcuNDEyLDEwMy40ODUgTDY3LjQxMiw0OS40ODQgQzY3LjQxMiw0OS4yOSA2Ny41NjksNDkuMTM0IDY3Ljc2Miw0OS4xMzQgQzY3Ljk1Niw0OS4xMzQgNjguMTEzLDQ5LjI5IDY4LjExMyw0OS40ODQgTDY4LjExMywxMDMuNDg1IEM2OC4xMTMsMTA0LjQ0NSA2OC44MiwxMDUuNjY1IDY5LjY1NywxMDYuMTQ4IEwxMTIuMTMsMTMwLjY3IEMxMTIuNDc0LDEzMC44NjggMTEyLjc5MSwxMzAuOTEzIDExMywxMzAuNzkyIEMxMTMuMjA2LDEzMC42NzMgMTEzLjMyNSwxMzAuMzgxIDExMy4zMjUsMTI5Ljk5MyBMMTEzLjMyNSw3NS45OTIgQzExMy4zMjUsNzUuNzk4IDExMy40ODIsNzUuNjQxIDExMy42NzUsNzUuNjQxIEMxMTMuODY5LDc1LjY0MSAxMTQuMDI1LDc1Ljc5OCAxMTQuMDI1LDc1Ljk5MiBMMTE0LjAyNSwxMjkuOTkzIEMxMTQuMDI1LDEzMC42NDggMTEzLjc4NiwxMzEuMTQ3IDExMy4zNSwxMzEuMzk5IEMxMTMuMTYyLDEzMS41MDcgMTEyLjk1MiwxMzEuNTYxIDExMi43MjcsMTMxLjU2MSIgaWQ9IkZpbGwtMjkiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEyLjg2LDQwLjUxMiBDMTEyLjg2LDQwLjUxMiAxMTIuODYsNDAuNTEyIDExMi44NTksNDAuNTEyIEMxMTAuNTQxLDQwLjUxMiAxMDguMzYsMzkuOTkgMTA2LjcxNywzOS4wNDEgQzEwNS4wMTIsMzguMDU3IDEwNC4wNzQsMzYuNzI2IDEwNC4wNzQsMzUuMjkyIEMxMDQuMDc0LDMzLjg0NyAxMDUuMDI2LDMyLjUwMSAxMDYuNzU0LDMxLjUwNCBMMTE4Ljc5NSwyNC41NTEgQzEyMC40NjMsMjMuNTg5IDEyMi42NjksMjMuMDU4IDEyNS4wMDcsMjMuMDU4IEMxMjcuMzI1LDIzLjA1OCAxMjkuNTA2LDIzLjU4MSAxMzEuMTUsMjQuNTMgQzEzMi44NTQsMjUuNTE0IDEzMy43OTMsMjYuODQ1IDEzMy43OTMsMjguMjc4IEMxMzMuNzkzLDI5LjcyNCAxMzIuODQxLDMxLjA2OSAxMzEuMTEzLDMyLjA2NyBMMTE5LjA3MSwzOS4wMTkgQzExNy40MDMsMzkuOTgyIDExNS4xOTcsNDAuNTEyIDExMi44Niw0MC41MTIgTDExMi44Niw0MC41MTIgWiBNMTI1LjAwNywyMy43NTkgQzEyMi43OSwyMy43NTkgMTIwLjcwOSwyNC4yNTYgMTE5LjE0NiwyNS4xNTggTDEwNy4xMDQsMzIuMTEgQzEwNS42MDIsMzIuOTc4IDEwNC43NzQsMzQuMTA4IDEwNC43NzQsMzUuMjkyIEMxMDQuNzc0LDM2LjQ2NSAxMDUuNTg5LDM3LjU4MSAxMDcuMDY3LDM4LjQzNCBDMTA4LjYwNSwzOS4zMjMgMTEwLjY2MywzOS44MTIgMTEyLjg1OSwzOS44MTIgTDExMi44NiwzOS44MTIgQzExNS4wNzYsMzkuODEyIDExNy4xNTgsMzkuMzE1IDExOC43MjEsMzguNDEzIEwxMzAuNzYyLDMxLjQ2IEMxMzIuMjY0LDMwLjU5MyAxMzMuMDkyLDI5LjQ2MyAxMzMuMDkyLDI4LjI3OCBDMTMzLjA5MiwyNy4xMDYgMTMyLjI3OCwyNS45OSAxMzAuOCwyNS4xMzYgQzEyOS4yNjEsMjQuMjQ4IDEyNy4yMDQsMjMuNzU5IDEyNS4wMDcsMjMuNzU5IEwxMjUuMDA3LDIzLjc1OSBaIiBpZD0iRmlsbC0zMCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNjUuNjMsMTYuMjE5IEwxNTkuODk2LDE5LjUzIEMxNTYuNzI5LDIxLjM1OCAxNTEuNjEsMjEuMzY3IDE0OC40NjMsMTkuNTUgQzE0NS4zMTYsMTcuNzMzIDE0NS4zMzIsMTQuNzc4IDE0OC40OTksMTIuOTQ5IEwxNTQuMjMzLDkuNjM5IEwxNjUuNjMsMTYuMjE5IiBpZD0iRmlsbC0zMSIgZmlsbD0iI0ZBRkFGQSI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNTQuMjMzLDEwLjQ0OCBMMTY0LjIyOCwxNi4yMTkgTDE1OS41NDYsMTguOTIzIEMxNTguMTEyLDE5Ljc1IDE1Ni4xOTQsMjAuMjA2IDE1NC4xNDcsMjAuMjA2IEMxNTIuMTE4LDIwLjIwNiAxNTAuMjI0LDE5Ljc1NyAxNDguODE0LDE4Ljk0MyBDMTQ3LjUyNCwxOC4xOTkgMTQ2LjgxNCwxNy4yNDkgMTQ2LjgxNCwxNi4yNjkgQzE0Ni44MTQsMTUuMjc4IDE0Ny41MzcsMTQuMzE0IDE0OC44NSwxMy41NTYgTDE1NC4yMzMsMTAuNDQ4IE0xNTQuMjMzLDkuNjM5IEwxNDguNDk5LDEyLjk0OSBDMTQ1LjMzMiwxNC43NzggMTQ1LjMxNiwxNy43MzMgMTQ4LjQ2MywxOS41NSBDMTUwLjAzMSwyMC40NTUgMTUyLjA4NiwyMC45MDcgMTU0LjE0NywyMC45MDcgQzE1Ni4yMjQsMjAuOTA3IDE1OC4zMDYsMjAuNDQ3IDE1OS44OTYsMTkuNTMgTDE2NS42MywxNi4yMTkgTDE1NC4yMzMsOS42MzkiIGlkPSJGaWxsLTMyIiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE0NS40NDUsNzIuNjY3IEwxNDUuNDQ1LDcyLjY2NyBDMTQzLjY3Miw3Mi42NjcgMTQyLjIwNCw3MS44MTcgMTQxLjIwMiw3MC40MjIgQzE0MS4xMzUsNzAuMzMgMTQxLjE0NSw3MC4xNDcgMTQxLjIyNSw3MC4wNjYgQzE0MS4zMDUsNjkuOTg1IDE0MS40MzIsNjkuOTQ2IDE0MS41MjUsNzAuMDExIEMxNDIuMzA2LDcwLjU1OSAxNDMuMjMxLDcwLjgyMyAxNDQuMjc2LDcwLjgyMiBDMTQ1LjU5OCw3MC44MjIgMTQ3LjAzLDcwLjM3NiAxNDguNTMyLDY5LjUwOSBDMTUzLjg0Miw2Ni40NDMgMTU4LjE2Myw1OC45ODcgMTU4LjE2Myw1Mi44OTQgQzE1OC4xNjMsNTAuOTY3IDE1Ny43MjEsNDkuMzMyIDE1Ni44ODQsNDguMTY4IEMxNTYuODE4LDQ4LjA3NiAxNTYuODI4LDQ3Ljk0OCAxNTYuOTA4LDQ3Ljg2NyBDMTU2Ljk4OCw0Ny43ODYgMTU3LjExNCw0Ny43NzQgMTU3LjIwOCw0Ny44NCBDMTU4Ljg3OCw0OS4wMTIgMTU5Ljc5OCw1MS4yMiAxNTkuNzk4LDU0LjA1OSBDMTU5Ljc5OCw2MC4zMDEgMTU1LjM3Myw2OC4wNDYgMTQ5LjkzMyw3MS4xODYgQzE0OC4zNiw3Mi4wOTQgMTQ2Ljg1LDcyLjY2NyAxNDUuNDQ1LDcyLjY2NyBMMTQ1LjQ0NSw3Mi42NjcgWiBNMTQyLjQ3Niw3MSBDMTQzLjI5LDcxLjY1MSAxNDQuMjk2LDcyLjAwMiAxNDUuNDQ1LDcyLjAwMiBDMTQ2Ljc2Nyw3Mi4wMDIgMTQ4LjE5OCw3MS41NSAxNDkuNyw3MC42ODIgQzE1NS4wMSw2Ny42MTcgMTU5LjMzMSw2MC4xNTkgMTU5LjMzMSw1NC4wNjUgQzE1OS4zMzEsNTIuMDg1IDE1OC44NjgsNTAuNDM1IDE1OC4wMDYsNDkuMjcyIEMxNTguNDE3LDUwLjMwNyAxNTguNjMsNTEuNTMyIDE1OC42Myw1Mi44OTIgQzE1OC42Myw1OS4xMzQgMTU0LjIwNSw2Ni43NjcgMTQ4Ljc2NSw2OS45MDcgQzE0Ny4xOTIsNzAuODE2IDE0NS42ODEsNzEuMjgzIDE0NC4yNzYsNzEuMjgzIEMxNDMuNjM0LDcxLjI4MyAxNDMuMDMzLDcxLjE5MiAxNDIuNDc2LDcxIEwxNDIuNDc2LDcxIFoiIGlkPSJGaWxsLTMzIiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE0OC42NDgsNjkuNzA0IEMxNTQuMDMyLDY2LjU5NiAxNTguMzk2LDU5LjA2OCAxNTguMzk2LDUyLjg5MSBDMTU4LjM5Niw1MC44MzkgMTU3LjkxMyw0OS4xOTggMTU3LjA3NCw0OC4wMyBDMTU1LjI4OSw0Ni43NzggMTUyLjY5OSw0Ni44MzYgMTQ5LjgxNiw0OC41MDEgQzE0NC40MzMsNTEuNjA5IDE0MC4wNjgsNTkuMTM3IDE0MC4wNjgsNjUuMzE0IEMxNDAuMDY4LDY3LjM2NSAxNDAuNTUyLDY5LjAwNiAxNDEuMzkxLDcwLjE3NCBDMTQzLjE3Niw3MS40MjcgMTQ1Ljc2NSw3MS4zNjkgMTQ4LjY0OCw2OS43MDQiIGlkPSJGaWxsLTM0IiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE0NC4yNzYsNzEuMjc2IEwxNDQuMjc2LDcxLjI3NiBDMTQzLjEzMyw3MS4yNzYgMTQyLjExOCw3MC45NjkgMTQxLjI1Nyw3MC4zNjUgQzE0MS4yMzYsNzAuMzUxIDE0MS4yMTcsNzAuMzMyIDE0MS4yMDIsNzAuMzExIEMxNDAuMzA3LDY5LjA2NyAxMzkuODM1LDY3LjMzOSAxMzkuODM1LDY1LjMxNCBDMTM5LjgzNSw1OS4wNzMgMTQ0LjI2LDUxLjQzOSAxNDkuNyw0OC4yOTggQzE1MS4yNzMsNDcuMzkgMTUyLjc4NCw0Ni45MjkgMTU0LjE4OSw0Ni45MjkgQzE1NS4zMzIsNDYuOTI5IDE1Ni4zNDcsNDcuMjM2IDE1Ny4yMDgsNDcuODM5IEMxNTcuMjI5LDQ3Ljg1NCAxNTcuMjQ4LDQ3Ljg3MyAxNTcuMjYzLDQ3Ljg5NCBDMTU4LjE1Nyw0OS4xMzggMTU4LjYzLDUwLjg2NSAxNTguNjMsNTIuODkxIEMxNTguNjMsNTkuMTMyIDE1NC4yMDUsNjYuNzY2IDE0OC43NjUsNjkuOTA3IEMxNDcuMTkyLDcwLjgxNSAxNDUuNjgxLDcxLjI3NiAxNDQuMjc2LDcxLjI3NiBMMTQ0LjI3Niw3MS4yNzYgWiBNMTQxLjU1OCw3MC4xMDQgQzE0Mi4zMzEsNzAuNjM3IDE0My4yNDUsNzEuMDA1IDE0NC4yNzYsNzEuMDA1IEMxNDUuNTk4LDcxLjAwNSAxNDcuMDMsNzAuNDY3IDE0OC41MzIsNjkuNiBDMTUzLjg0Miw2Ni41MzQgMTU4LjE2Myw1OS4wMzMgMTU4LjE2Myw1Mi45MzkgQzE1OC4xNjMsNTEuMDMxIDE1Ny43MjksNDkuMzg1IDE1Ni45MDcsNDguMjIzIEMxNTYuMTMzLDQ3LjY5MSAxNTUuMjE5LDQ3LjQwOSAxNTQuMTg5LDQ3LjQwOSBDMTUyLjg2Nyw0Ny40MDkgMTUxLjQzNSw0Ny44NDIgMTQ5LjkzMyw0OC43MDkgQzE0NC42MjMsNTEuNzc1IDE0MC4zMDIsNTkuMjczIDE0MC4zMDIsNjUuMzY2IEMxNDAuMzAyLDY3LjI3NiAxNDAuNzM2LDY4Ljk0MiAxNDEuNTU4LDcwLjEwNCBMMTQxLjU1OCw3MC4xMDQgWiIgaWQ9IkZpbGwtMzUiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTUwLjcyLDY1LjM2MSBMMTUwLjM1Nyw2NS4wNjYgQzE1MS4xNDcsNjQuMDkyIDE1MS44NjksNjMuMDQgMTUyLjUwNSw2MS45MzggQzE1My4zMTMsNjAuNTM5IDE1My45NzgsNTkuMDY3IDE1NC40ODIsNTcuNTYzIEwxNTQuOTI1LDU3LjcxMiBDMTU0LjQxMiw1OS4yNDUgMTUzLjczMyw2MC43NDUgMTUyLjkxLDYyLjE3MiBDMTUyLjI2Miw2My4yOTUgMTUxLjUyNSw2NC4zNjggMTUwLjcyLDY1LjM2MSIgaWQ9IkZpbGwtMzYiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTE1LjkxNyw4NC41MTQgTDExNS41NTQsODQuMjIgQzExNi4zNDQsODMuMjQ1IDExNy4wNjYsODIuMTk0IDExNy43MDIsODEuMDkyIEMxMTguNTEsNzkuNjkyIDExOS4xNzUsNzguMjIgMTE5LjY3OCw3Ni43MTcgTDEyMC4xMjEsNzYuODY1IEMxMTkuNjA4LDc4LjM5OCAxMTguOTMsNzkuODk5IDExOC4xMDYsODEuMzI2IEMxMTcuNDU4LDgyLjQ0OCAxMTYuNzIyLDgzLjUyMSAxMTUuOTE3LDg0LjUxNCIgaWQ9IkZpbGwtMzciIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTE0LDEzMC40NzYgTDExNCwxMzAuMDA4IEwxMTQsNzYuMDUyIEwxMTQsNzUuNTg0IEwxMTQsNzYuMDUyIEwxMTQsMTMwLjAwOCBMMTE0LDEzMC40NzYiIGlkPSJGaWxsLTM4IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICA8L2c+CiAgICAgICAgICAgICAgICA8ZyBpZD0iSW1wb3J0ZWQtTGF5ZXJzLUNvcHkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDYyLjAwMDAwMCwgMC4wMDAwMDApIiBza2V0Y2g6dHlwZT0iTVNTaGFwZUdyb3VwIj4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTkuODIyLDM3LjQ3NCBDMTkuODM5LDM3LjMzOSAxOS43NDcsMzcuMTk0IDE5LjU1NSwzNy4wODIgQzE5LjIyOCwzNi44OTQgMTguNzI5LDM2Ljg3MiAxOC40NDYsMzcuMDM3IEwxMi40MzQsNDAuNTA4IEMxMi4zMDMsNDAuNTg0IDEyLjI0LDQwLjY4NiAxMi4yNDMsNDAuNzkzIEMxMi4yNDUsNDAuOTI1IDEyLjI0NSw0MS4yNTQgMTIuMjQ1LDQxLjM3MSBMMTIuMjQ1LDQxLjQxNCBMMTIuMjM4LDQxLjU0MiBDOC4xNDgsNDMuODg3IDUuNjQ3LDQ1LjMyMSA1LjY0Nyw0NS4zMjEgQzUuNjQ2LDQ1LjMyMSAzLjU3LDQ2LjM2NyAyLjg2LDUwLjUxMyBDMi44Niw1MC41MTMgMS45NDgsNTcuNDc0IDEuOTYyLDcwLjI1OCBDMS45NzcsODIuODI4IDIuNTY4LDg3LjMyOCAzLjEyOSw5MS42MDkgQzMuMzQ5LDkzLjI5MyA2LjEzLDkzLjczNCA2LjEzLDkzLjczNCBDNi40NjEsOTMuNzc0IDYuODI4LDkzLjcwNyA3LjIxLDkzLjQ4NiBMODIuNDgzLDQ5LjkzNSBDODQuMjkxLDQ4Ljg2NiA4NS4xNSw0Ni4yMTYgODUuNTM5LDQzLjY1MSBDODYuNzUyLDM1LjY2MSA4Ny4yMTQsMTAuNjczIDg1LjI2NCwzLjc3MyBDODUuMDY4LDMuMDggODQuNzU0LDIuNjkgODQuMzk2LDIuNDkxIEw4Mi4zMSwxLjcwMSBDODEuNTgzLDEuNzI5IDgwLjg5NCwyLjE2OCA4MC43NzYsMi4yMzYgQzgwLjYzNiwyLjMxNyA0MS44MDcsMjQuNTg1IDIwLjAzMiwzNy4wNzIgTDE5LjgyMiwzNy40NzQiIGlkPSJGaWxsLTEiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNODIuMzExLDEuNzAxIEw4NC4zOTYsMi40OTEgQzg0Ljc1NCwyLjY5IDg1LjA2OCwzLjA4IDg1LjI2NCwzLjc3MyBDODcuMjEzLDEwLjY3MyA4Ni43NTEsMzUuNjYgODUuNTM5LDQzLjY1MSBDODUuMTQ5LDQ2LjIxNiA4NC4yOSw0OC44NjYgODIuNDgzLDQ5LjkzNSBMNy4yMSw5My40ODYgQzYuODk3LDkzLjY2NyA2LjU5NSw5My43NDQgNi4zMTQsOTMuNzQ0IEw2LjEzMSw5My43MzMgQzYuMTMxLDkzLjczNCAzLjM0OSw5My4yOTMgMy4xMjgsOTEuNjA5IEMyLjU2OCw4Ny4zMjcgMS45NzcsODIuODI4IDEuOTYzLDcwLjI1OCBDMS45NDgsNTcuNDc0IDIuODYsNTAuNTEzIDIuODYsNTAuNTEzIEMzLjU3LDQ2LjM2NyA1LjY0Nyw0NS4zMjEgNS42NDcsNDUuMzIxIEM1LjY0Nyw0NS4zMjEgOC4xNDgsNDMuODg3IDEyLjIzOCw0MS41NDIgTDEyLjI0NSw0MS40MTQgTDEyLjI0NSw0MS4zNzEgQzEyLjI0NSw0MS4yNTQgMTIuMjQ1LDQwLjkyNSAxMi4yNDMsNDAuNzkzIEMxMi4yNCw0MC42ODYgMTIuMzAyLDQwLjU4MyAxMi40MzQsNDAuNTA4IEwxOC40NDYsMzcuMDM2IEMxOC41NzQsMzYuOTYyIDE4Ljc0NiwzNi45MjYgMTguOTI3LDM2LjkyNiBDMTkuMTQ1LDM2LjkyNiAxOS4zNzYsMzYuOTc5IDE5LjU1NCwzNy4wODIgQzE5Ljc0NywzNy4xOTQgMTkuODM5LDM3LjM0IDE5LjgyMiwzNy40NzQgTDIwLjAzMywzNy4wNzIgQzQxLjgwNiwyNC41ODUgODAuNjM2LDIuMzE4IDgwLjc3NywyLjIzNiBDODAuODk0LDIuMTY4IDgxLjU4MywxLjcyOSA4Mi4zMTEsMS43MDEgTTgyLjMxMSwwLjcwNCBMODIuMjcyLDAuNzA1IEM4MS42NTQsMC43MjggODAuOTg5LDAuOTQ5IDgwLjI5OCwxLjM2MSBMODAuMjc3LDEuMzczIEM4MC4xMjksMS40NTggNTkuNzY4LDEzLjEzNSAxOS43NTgsMzYuMDc5IEMxOS41LDM1Ljk4MSAxOS4yMTQsMzUuOTI5IDE4LjkyNywzNS45MjkgQzE4LjU2MiwzNS45MjkgMTguMjIzLDM2LjAxMyAxNy45NDcsMzYuMTczIEwxMS45MzUsMzkuNjQ0IEMxMS40OTMsMzkuODk5IDExLjIzNiw0MC4zMzQgMTEuMjQ2LDQwLjgxIEwxMS4yNDcsNDAuOTYgTDUuMTY3LDQ0LjQ0NyBDNC43OTQsNDQuNjQ2IDIuNjI1LDQ1Ljk3OCAxLjg3Nyw1MC4zNDUgTDEuODcxLDUwLjM4NCBDMS44NjIsNTAuNDU0IDAuOTUxLDU3LjU1NyAwLjk2NSw3MC4yNTkgQzAuOTc5LDgyLjg3OSAxLjU2OCw4Ny4zNzUgMi4xMzcsOTEuNzI0IEwyLjEzOSw5MS43MzkgQzIuNDQ3LDk0LjA5NCA1LjYxNCw5NC42NjIgNS45NzUsOTQuNzE5IEw2LjAwOSw5NC43MjMgQzYuMTEsOTQuNzM2IDYuMjEzLDk0Ljc0MiA2LjMxNCw5NC43NDIgQzYuNzksOTQuNzQyIDcuMjYsOTQuNjEgNy43MSw5NC4zNSBMODIuOTgzLDUwLjc5OCBDODQuNzk0LDQ5LjcyNyA4NS45ODIsNDcuMzc1IDg2LjUyNSw0My44MDEgQzg3LjcxMSwzNS45ODcgODguMjU5LDEwLjcwNSA4Ni4yMjQsMy41MDIgQzg1Ljk3MSwyLjYwOSA4NS41MiwxLjk3NSA4NC44ODEsMS42MiBMODQuNzQ5LDEuNTU4IEw4Mi42NjQsMC43NjkgQzgyLjU1MSwwLjcyNSA4Mi40MzEsMC43MDQgODIuMzExLDAuNzA0IiBpZD0iRmlsbC0yIiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTY2LjI2NywxMS41NjUgTDY3Ljc2MiwxMS45OTkgTDExLjQyMyw0NC4zMjUiIGlkPSJGaWxsLTMiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTIuMjAyLDkwLjU0NSBDMTIuMDI5LDkwLjU0NSAxMS44NjIsOTAuNDU1IDExLjc2OSw5MC4yOTUgQzExLjYzMiw5MC4wNTcgMTEuNzEzLDg5Ljc1MiAxMS45NTIsODkuNjE0IEwzMC4zODksNzguOTY5IEMzMC42MjgsNzguODMxIDMwLjkzMyw3OC45MTMgMzEuMDcxLDc5LjE1MiBDMzEuMjA4LDc5LjM5IDMxLjEyNyw3OS42OTYgMzAuODg4LDc5LjgzMyBMMTIuNDUxLDkwLjQ3OCBMMTIuMjAyLDkwLjU0NSIgaWQ9IkZpbGwtNCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMy43NjQsNDIuNjU0IEwxMy42NTYsNDIuNTkyIEwxMy43MDIsNDIuNDIxIEwxOC44MzcsMzkuNDU3IEwxOS4wMDcsMzkuNTAyIEwxOC45NjIsMzkuNjczIEwxMy44MjcsNDIuNjM3IEwxMy43NjQsNDIuNjU0IiBpZD0iRmlsbC01IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTguNTIsOTAuMzc1IEw4LjUyLDQ2LjQyMSBMOC41ODMsNDYuMzg1IEw3NS44NCw3LjU1NCBMNzUuODQsNTEuNTA4IEw3NS43NzgsNTEuNTQ0IEw4LjUyLDkwLjM3NSBMOC41Miw5MC4zNzUgWiBNOC43Nyw0Ni41NjQgTDguNzcsODkuOTQ0IEw3NS41OTEsNTEuMzY1IEw3NS41OTEsNy45ODUgTDguNzcsNDYuNTY0IEw4Ljc3LDQ2LjU2NCBaIiBpZD0iRmlsbC02IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTI0Ljk4Niw4My4xODIgQzI0Ljc1Niw4My4zMzEgMjQuMzc0LDgzLjU2NiAyNC4xMzcsODMuNzA1IEwxMi42MzIsOTAuNDA2IEMxMi4zOTUsOTAuNTQ1IDEyLjQyNiw5MC42NTggMTIuNyw5MC42NTggTDEzLjI2NSw5MC42NTggQzEzLjU0LDkwLjY1OCAxMy45NTgsOTAuNTQ1IDE0LjE5NSw5MC40MDYgTDI1LjcsODMuNzA1IEMyNS45MzcsODMuNTY2IDI2LjEyOCw4My40NTIgMjYuMTI1LDgzLjQ0OSBDMjYuMTIyLDgzLjQ0NyAyNi4xMTksODMuMjIgMjYuMTE5LDgyLjk0NiBDMjYuMTE5LDgyLjY3MiAyNS45MzEsODIuNTY5IDI1LjcwMSw4Mi43MTkgTDI0Ljk4Niw4My4xODIiIGlkPSJGaWxsLTciIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTMuMjY2LDkwLjc4MiBMMTIuNyw5MC43ODIgQzEyLjUsOTAuNzgyIDEyLjM4NCw5MC43MjYgMTIuMzU0LDkwLjYxNiBDMTIuMzI0LDkwLjUwNiAxMi4zOTcsOTAuMzk5IDEyLjU2OSw5MC4yOTkgTDI0LjA3NCw4My41OTcgQzI0LjMxLDgzLjQ1OSAyNC42ODksODMuMjI2IDI0LjkxOCw4My4wNzggTDI1LjYzMyw4Mi42MTQgQzI1LjcyMyw4Mi41NTUgMjUuODEzLDgyLjUyNSAyNS44OTksODIuNTI1IEMyNi4wNzEsODIuNTI1IDI2LjI0NCw4Mi42NTUgMjYuMjQ0LDgyLjk0NiBDMjYuMjQ0LDgzLjE2IDI2LjI0NSw4My4zMDkgMjYuMjQ3LDgzLjM4MyBMMjYuMjUzLDgzLjM4NyBMMjYuMjQ5LDgzLjQ1NiBDMjYuMjQ2LDgzLjUzMSAyNi4yNDYsODMuNTMxIDI1Ljc2Myw4My44MTIgTDE0LjI1OCw5MC41MTQgQzE0LDkwLjY2NSAxMy41NjQsOTAuNzgyIDEzLjI2Niw5MC43ODIgTDEzLjI2Niw5MC43ODIgWiBNMTIuNjY2LDkwLjUzMiBMMTIuNyw5MC41MzMgTDEzLjI2Niw5MC41MzMgQzEzLjUxOCw5MC41MzMgMTMuOTE1LDkwLjQyNSAxNC4xMzIsOTAuMjk5IEwyNS42MzcsODMuNTk3IEMyNS44MDUsODMuNDk5IDI1LjkzMSw4My40MjQgMjUuOTk4LDgzLjM4MyBDMjUuOTk0LDgzLjI5OSAyNS45OTQsODMuMTY1IDI1Ljk5NCw4Mi45NDYgTDI1Ljg5OSw4Mi43NzUgTDI1Ljc2OCw4Mi44MjQgTDI1LjA1NCw4My4yODcgQzI0LjgyMiw4My40MzcgMjQuNDM4LDgzLjY3MyAyNC4yLDgzLjgxMiBMMTIuNjk1LDkwLjUxNCBMMTIuNjY2LDkwLjUzMiBMMTIuNjY2LDkwLjUzMiBaIiBpZD0iRmlsbC04IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTEzLjI2Niw4OS44NzEgTDEyLjcsODkuODcxIEMxMi41LDg5Ljg3MSAxMi4zODQsODkuODE1IDEyLjM1NCw4OS43MDUgQzEyLjMyNCw4OS41OTUgMTIuMzk3LDg5LjQ4OCAxMi41NjksODkuMzg4IEwyNC4wNzQsODIuNjg2IEMyNC4zMzIsODIuNTM1IDI0Ljc2OCw4Mi40MTggMjUuMDY3LDgyLjQxOCBMMjUuNjMyLDgyLjQxOCBDMjUuODMyLDgyLjQxOCAyNS45NDgsODIuNDc0IDI1Ljk3OCw4Mi41ODQgQzI2LjAwOCw4Mi42OTQgMjUuOTM1LDgyLjgwMSAyNS43NjMsODIuOTAxIEwxNC4yNTgsODkuNjAzIEMxNCw4OS43NTQgMTMuNTY0LDg5Ljg3MSAxMy4yNjYsODkuODcxIEwxMy4yNjYsODkuODcxIFogTTEyLjY2Niw4OS42MjEgTDEyLjcsODkuNjIyIEwxMy4yNjYsODkuNjIyIEMxMy41MTgsODkuNjIyIDEzLjkxNSw4OS41MTUgMTQuMTMyLDg5LjM4OCBMMjUuNjM3LDgyLjY4NiBMMjUuNjY3LDgyLjY2OCBMMjUuNjMyLDgyLjY2NyBMMjUuMDY3LDgyLjY2NyBDMjQuODE1LDgyLjY2NyAyNC40MTgsODIuNzc1IDI0LjIsODIuOTAxIEwxMi42OTUsODkuNjAzIEwxMi42NjYsODkuNjIxIEwxMi42NjYsODkuNjIxIFoiIGlkPSJGaWxsLTkiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTIuMzcsOTAuODAxIEwxMi4zNyw4OS41NTQgTDEyLjM3LDkwLjgwMSIgaWQ9IkZpbGwtMTAiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNi4xMyw5My45MDEgQzUuMzc5LDkzLjgwOCA0LjgxNiw5My4xNjQgNC42OTEsOTIuNTI1IEMzLjg2LDg4LjI4NyAzLjU0LDgzLjc0MyAzLjUyNiw3MS4xNzMgQzMuNTExLDU4LjM4OSA0LjQyMyw1MS40MjggNC40MjMsNTEuNDI4IEM1LjEzNCw0Ny4yODIgNy4yMSw0Ni4yMzYgNy4yMSw0Ni4yMzYgQzcuMjEsNDYuMjM2IDgxLjY2NywzLjI1IDgyLjA2OSwzLjAxNyBDODIuMjkyLDIuODg4IDg0LjU1NiwxLjQzMyA4NS4yNjQsMy45NCBDODcuMjE0LDEwLjg0IDg2Ljc1MiwzNS44MjcgODUuNTM5LDQzLjgxOCBDODUuMTUsNDYuMzgzIDg0LjI5MSw0OS4wMzMgODIuNDgzLDUwLjEwMSBMNy4yMSw5My42NTMgQzYuODI4LDkzLjg3NCA2LjQ2MSw5My45NDEgNi4xMyw5My45MDEgQzYuMTMsOTMuOTAxIDMuMzQ5LDkzLjQ2IDMuMTI5LDkxLjc3NiBDMi41NjgsODcuNDk1IDEuOTc3LDgyLjk5NSAxLjk2Miw3MC40MjUgQzEuOTQ4LDU3LjY0MSAyLjg2LDUwLjY4IDIuODYsNTAuNjggQzMuNTcsNDYuNTM0IDUuNjQ3LDQ1LjQ4OSA1LjY0Nyw0NS40ODkgQzUuNjQ2LDQ1LjQ4OSA4LjA2NSw0NC4wOTIgMTIuMjQ1LDQxLjY3OSBMMTMuMTE2LDQxLjU2IEwxOS43MTUsMzcuNzMgTDE5Ljc2MSwzNy4yNjkgTDYuMTMsOTMuOTAxIiBpZD0iRmlsbC0xMSIgZmlsbD0iI0ZBRkFGQSI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik02LjMxNyw5NC4xNjEgTDYuMTAyLDk0LjE0OCBMNi4xMDEsOTQuMTQ4IEw1Ljg1Nyw5NC4xMDEgQzUuMTM4LDkzLjk0NSAzLjA4NSw5My4zNjUgMi44ODEsOTEuODA5IEMyLjMxMyw4Ny40NjkgMS43MjcsODIuOTk2IDEuNzEzLDcwLjQyNSBDMS42OTksNTcuNzcxIDIuNjA0LDUwLjcxOCAyLjYxMyw1MC42NDggQzMuMzM4LDQ2LjQxNyA1LjQ0NSw0NS4zMSA1LjUzNSw0NS4yNjYgTDEyLjE2Myw0MS40MzkgTDEzLjAzMyw0MS4zMiBMMTkuNDc5LDM3LjU3OCBMMTkuNTEzLDM3LjI0NCBDMTkuNTI2LDM3LjEwNyAxOS42NDcsMzcuMDA4IDE5Ljc4NiwzNy4wMjEgQzE5LjkyMiwzNy4wMzQgMjAuMDIzLDM3LjE1NiAyMC4wMDksMzcuMjkzIEwxOS45NSwzNy44ODIgTDEzLjE5OCw0MS44MDEgTDEyLjMyOCw0MS45MTkgTDUuNzcyLDQ1LjcwNCBDNS43NDEsNDUuNzIgMy43ODIsNDYuNzcyIDMuMTA2LDUwLjcyMiBDMy4wOTksNTAuNzgyIDIuMTk4LDU3LjgwOCAyLjIxMiw3MC40MjQgQzIuMjI2LDgyLjk2MyAyLjgwOSw4Ny40MiAzLjM3Myw5MS43MjkgQzMuNDY0LDkyLjQyIDQuMDYyLDkyLjg4MyA0LjY4Miw5My4xODEgQzQuNTY2LDkyLjk4NCA0LjQ4Niw5Mi43NzYgNC40NDYsOTIuNTcyIEMzLjY2NSw4OC41ODggMy4yOTEsODQuMzcgMy4yNzYsNzEuMTczIEMzLjI2Miw1OC41MiA0LjE2Nyw1MS40NjYgNC4xNzYsNTEuMzk2IEM0LjkwMSw0Ny4xNjUgNy4wMDgsNDYuMDU5IDcuMDk4LDQ2LjAxNCBDNy4wOTQsNDYuMDE1IDgxLjU0MiwzLjAzNCA4MS45NDQsMi44MDIgTDgxLjk3MiwyLjc4NSBDODIuODc2LDIuMjQ3IDgzLjY5MiwyLjA5NyA4NC4zMzIsMi4zNTIgQzg0Ljg4NywyLjU3MyA4NS4yODEsMy4wODUgODUuNTA0LDMuODcyIEM4Ny41MTgsMTEgODYuOTY0LDM2LjA5MSA4NS43ODUsNDMuODU1IEM4NS4yNzgsNDcuMTk2IDg0LjIxLDQ5LjM3IDgyLjYxLDUwLjMxNyBMNy4zMzUsOTMuODY5IEM2Ljk5OSw5NC4wNjMgNi42NTgsOTQuMTYxIDYuMzE3LDk0LjE2MSBMNi4zMTcsOTQuMTYxIFogTTYuMTcsOTMuNjU0IEM2LjQ2Myw5My42OSA2Ljc3NCw5My42MTcgNy4wODUsOTMuNDM3IEw4Mi4zNTgsNDkuODg2IEM4NC4xODEsNDguODA4IDg0Ljk2LDQ1Ljk3MSA4NS4yOTIsNDMuNzggQzg2LjQ2NiwzNi4wNDkgODcuMDIzLDExLjA4NSA4NS4wMjQsNC4wMDggQzg0Ljg0NiwzLjM3NyA4NC41NTEsMi45NzYgODQuMTQ4LDIuODE2IEM4My42NjQsMi42MjMgODIuOTgyLDIuNzY0IDgyLjIyNywzLjIxMyBMODIuMTkzLDMuMjM0IEM4MS43OTEsMy40NjYgNy4zMzUsNDYuNDUyIDcuMzM1LDQ2LjQ1MiBDNy4zMDQsNDYuNDY5IDUuMzQ2LDQ3LjUyMSA0LjY2OSw1MS40NzEgQzQuNjYyLDUxLjUzIDMuNzYxLDU4LjU1NiAzLjc3NSw3MS4xNzMgQzMuNzksODQuMzI4IDQuMTYxLDg4LjUyNCA0LjkzNiw5Mi40NzYgQzUuMDI2LDkyLjkzNyA1LjQxMiw5My40NTkgNS45NzMsOTMuNjE1IEM2LjA4Nyw5My42NCA2LjE1OCw5My42NTIgNi4xNjksOTMuNjU0IEw2LjE3LDkzLjY1NCBMNi4xNyw5My42NTQgWiIgaWQ9IkZpbGwtMTIiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNy4zMTcsNjguOTgyIEM3LjgwNiw2OC43MDEgOC4yMDIsNjguOTI2IDguMjAyLDY5LjQ4NyBDOC4yMDIsNzAuMDQ3IDcuODA2LDcwLjczIDcuMzE3LDcxLjAxMiBDNi44MjksNzEuMjk0IDYuNDMzLDcxLjA2OSA2LjQzMyw3MC41MDggQzYuNDMzLDY5Ljk0OCA2LjgyOSw2OS4yNjUgNy4zMTcsNjguOTgyIiBpZD0iRmlsbC0xMyIgZmlsbD0iI0ZGRkZGRiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik02LjkyLDcxLjEzMyBDNi42MzEsNzEuMTMzIDYuNDMzLDcwLjkwNSA2LjQzMyw3MC41MDggQzYuNDMzLDY5Ljk0OCA2LjgyOSw2OS4yNjUgNy4zMTcsNjguOTgyIEM3LjQ2LDY4LjkgNy41OTUsNjguODYxIDcuNzE0LDY4Ljg2MSBDOC4wMDMsNjguODYxIDguMjAyLDY5LjA5IDguMjAyLDY5LjQ4NyBDOC4yMDIsNzAuMDQ3IDcuODA2LDcwLjczIDcuMzE3LDcxLjAxMiBDNy4xNzQsNzEuMDk0IDcuMDM5LDcxLjEzMyA2LjkyLDcxLjEzMyBNNy43MTQsNjguNjc0IEM3LjU1Nyw2OC42NzQgNy4zOTIsNjguNzIzIDcuMjI0LDY4LjgyMSBDNi42NzYsNjkuMTM4IDYuMjQ2LDY5Ljg3OSA2LjI0Niw3MC41MDggQzYuMjQ2LDcwLjk5NCA2LjUxNyw3MS4zMiA2LjkyLDcxLjMyIEM3LjA3OCw3MS4zMiA3LjI0Myw3MS4yNzEgNy40MTEsNzEuMTc0IEM3Ljk1OSw3MC44NTcgOC4zODksNzAuMTE3IDguMzg5LDY5LjQ4NyBDOC4zODksNjkuMDAxIDguMTE3LDY4LjY3NCA3LjcxNCw2OC42NzQiIGlkPSJGaWxsLTE0IiBmaWxsPSIjODA5N0EyIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTYuOTIsNzAuOTQ3IEM2LjY0OSw3MC45NDcgNi42MjEsNzAuNjQgNi42MjEsNzAuNTA4IEM2LjYyMSw3MC4wMTcgNi45ODIsNjkuMzkyIDcuNDExLDY5LjE0NSBDNy41MjEsNjkuMDgyIDcuNjI1LDY5LjA0OSA3LjcxNCw2OS4wNDkgQzcuOTg2LDY5LjA0OSA4LjAxNSw2OS4zNTUgOC4wMTUsNjkuNDg3IEM4LjAxNSw2OS45NzggNy42NTIsNzAuNjAzIDcuMjI0LDcwLjg1MSBDNy4xMTUsNzAuOTE0IDcuMDEsNzAuOTQ3IDYuOTIsNzAuOTQ3IE03LjcxNCw2OC44NjEgQzcuNTk1LDY4Ljg2MSA3LjQ2LDY4LjkgNy4zMTcsNjguOTgyIEM2LjgyOSw2OS4yNjUgNi40MzMsNjkuOTQ4IDYuNDMzLDcwLjUwOCBDNi40MzMsNzAuOTA1IDYuNjMxLDcxLjEzMyA2LjkyLDcxLjEzMyBDNy4wMzksNzEuMTMzIDcuMTc0LDcxLjA5NCA3LjMxNyw3MS4wMTIgQzcuODA2LDcwLjczIDguMjAyLDcwLjA0NyA4LjIwMiw2OS40ODcgQzguMjAyLDY5LjA5IDguMDAzLDY4Ljg2MSA3LjcxNCw2OC44NjEiIGlkPSJGaWxsLTE1IiBmaWxsPSIjODA5N0EyIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTcuNDQ0LDg1LjM1IEM3LjcwOCw4NS4xOTggNy45MjEsODUuMzE5IDcuOTIxLDg1LjYyMiBDNy45MjEsODUuOTI1IDcuNzA4LDg2LjI5MiA3LjQ0NCw4Ni40NDQgQzcuMTgxLDg2LjU5NyA2Ljk2Nyw4Ni40NzUgNi45NjcsODYuMTczIEM2Ljk2Nyw4NS44NzEgNy4xODEsODUuNTAyIDcuNDQ0LDg1LjM1IiBpZD0iRmlsbC0xNiIgZmlsbD0iI0ZGRkZGRiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik03LjIzLDg2LjUxIEM3LjA3NCw4Ni41MSA2Ljk2Nyw4Ni4zODcgNi45NjcsODYuMTczIEM2Ljk2Nyw4NS44NzEgNy4xODEsODUuNTAyIDcuNDQ0LDg1LjM1IEM3LjUyMSw4NS4zMDUgNy41OTQsODUuMjg0IDcuNjU4LDg1LjI4NCBDNy44MTQsODUuMjg0IDcuOTIxLDg1LjQwOCA3LjkyMSw4NS42MjIgQzcuOTIxLDg1LjkyNSA3LjcwOCw4Ni4yOTIgNy40NDQsODYuNDQ0IEM3LjM2Nyw4Ni40ODkgNy4yOTQsODYuNTEgNy4yMyw4Ni41MSBNNy42NTgsODUuMDk4IEM3LjU1OCw4NS4wOTggNy40NTUsODUuMTI3IDcuMzUxLDg1LjE4OCBDNy4wMzEsODUuMzczIDYuNzgxLDg1LjgwNiA2Ljc4MSw4Ni4xNzMgQzYuNzgxLDg2LjQ4MiA2Ljk2Niw4Ni42OTcgNy4yMyw4Ni42OTcgQzcuMzMsODYuNjk3IDcuNDMzLDg2LjY2NiA3LjUzOCw4Ni42MDcgQzcuODU4LDg2LjQyMiA4LjEwOCw4NS45ODkgOC4xMDgsODUuNjIyIEM4LjEwOCw4NS4zMTMgNy45MjMsODUuMDk4IDcuNjU4LDg1LjA5OCIgaWQ9IkZpbGwtMTciIGZpbGw9IiM4MDk3QTIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNy4yMyw4Ni4zMjIgTDcuMTU0LDg2LjE3MyBDNy4xNTQsODUuOTM4IDcuMzMzLDg1LjYyOSA3LjUzOCw4NS41MTIgTDcuNjU4LDg1LjQ3MSBMNy43MzQsODUuNjIyIEM3LjczNCw4NS44NTYgNy41NTUsODYuMTY0IDcuMzUxLDg2LjI4MiBMNy4yMyw4Ni4zMjIgTTcuNjU4LDg1LjI4NCBDNy41OTQsODUuMjg0IDcuNTIxLDg1LjMwNSA3LjQ0NCw4NS4zNSBDNy4xODEsODUuNTAyIDYuOTY3LDg1Ljg3MSA2Ljk2Nyw4Ni4xNzMgQzYuOTY3LDg2LjM4NyA3LjA3NCw4Ni41MSA3LjIzLDg2LjUxIEM3LjI5NCw4Ni41MSA3LjM2Nyw4Ni40ODkgNy40NDQsODYuNDQ0IEM3LjcwOCw4Ni4yOTIgNy45MjEsODUuOTI1IDcuOTIxLDg1LjYyMiBDNy45MjEsODUuNDA4IDcuODE0LDg1LjI4NCA3LjY1OCw4NS4yODQiIGlkPSJGaWxsLTE4IiBmaWxsPSIjODA5N0EyIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTc3LjI3OCw3Ljc2OSBMNzcuMjc4LDUxLjQzNiBMMTAuMjA4LDkwLjE2IEwxMC4yMDgsNDYuNDkzIEw3Ny4yNzgsNy43NjkiIGlkPSJGaWxsLTE5IiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTEwLjA4Myw5MC4zNzUgTDEwLjA4Myw0Ni40MjEgTDEwLjE0Niw0Ni4zODUgTDc3LjQwMyw3LjU1NCBMNzcuNDAzLDUxLjUwOCBMNzcuMzQxLDUxLjU0NCBMMTAuMDgzLDkwLjM3NSBMMTAuMDgzLDkwLjM3NSBaIE0xMC4zMzMsNDYuNTY0IEwxMC4zMzMsODkuOTQ0IEw3Ny4xNTQsNTEuMzY1IEw3Ny4xNTQsNy45ODUgTDEwLjMzMyw0Ni41NjQgTDEwLjMzMyw0Ni41NjQgWiIgaWQ9IkZpbGwtMjAiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMjUuNzM3LDg4LjY0NyBMMTE4LjA5OCw5MS45ODEgTDExOC4wOTgsODQgTDEwNi42MzksODguNzEzIEwxMDYuNjM5LDk2Ljk4MiBMOTksMTAwLjMxNSBMMTEyLjM2OSwxMDMuOTYxIEwxMjUuNzM3LDg4LjY0NyIgaWQ9IkltcG9ydGVkLUxheWVycy1Db3B5LTIiIGZpbGw9IiM0NTVBNjQiIHNrZXRjaDp0eXBlPSJNU1NoYXBlR3JvdXAiPjwvcGF0aD4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+';
  39826. function RotateInstructions() {
  39827. this.loadIcon_();
  39828. var overlay = document.createElement('div');
  39829. var s = overlay.style;
  39830. s.position = 'fixed';
  39831. s.top = 0;
  39832. s.right = 0;
  39833. s.bottom = 0;
  39834. s.left = 0;
  39835. s.backgroundColor = 'gray';
  39836. s.fontFamily = 'sans-serif';
  39837. s.zIndex = 1000000;
  39838. var img = document.createElement('img');
  39839. img.src = this.icon;
  39840. var s = img.style;
  39841. s.marginLeft = '25%';
  39842. s.marginTop = '25%';
  39843. s.width = '50%';
  39844. overlay.appendChild(img);
  39845. var text = document.createElement('div');
  39846. var s = text.style;
  39847. s.textAlign = 'center';
  39848. s.fontSize = '16px';
  39849. s.lineHeight = '24px';
  39850. s.margin = '24px 25%';
  39851. s.width = '50%';
  39852. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  39853. overlay.appendChild(text);
  39854. var snackbar = document.createElement('div');
  39855. var s = snackbar.style;
  39856. s.backgroundColor = '#CFD8DC';
  39857. s.position = 'fixed';
  39858. s.bottom = 0;
  39859. s.width = '100%';
  39860. s.height = '48px';
  39861. s.padding = '14px 24px';
  39862. s.boxSizing = 'border-box';
  39863. s.color = '#656A6B';
  39864. overlay.appendChild(snackbar);
  39865. var snackbarText = document.createElement('div');
  39866. snackbarText.style.float = 'left';
  39867. snackbarText.innerHTML = 'No Cardboard viewer?';
  39868. var snackbarButton = document.createElement('a');
  39869. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  39870. snackbarButton.innerHTML = 'get one';
  39871. snackbarButton.target = '_blank';
  39872. var s = snackbarButton.style;
  39873. s.float = 'right';
  39874. s.fontWeight = 600;
  39875. s.textTransform = 'uppercase';
  39876. s.borderLeft = '1px solid gray';
  39877. s.paddingLeft = '24px';
  39878. s.textDecoration = 'none';
  39879. s.color = '#656A6B';
  39880. snackbar.appendChild(snackbarText);
  39881. snackbar.appendChild(snackbarButton);
  39882. this.overlay = overlay;
  39883. this.text = text;
  39884. this.hide();
  39885. }
  39886. RotateInstructions.prototype.show = function (parent) {
  39887. if (!parent && !this.overlay.parentElement) {
  39888. document.body.appendChild(this.overlay);
  39889. } else if (parent) {
  39890. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  39891. parent.appendChild(this.overlay);
  39892. }
  39893. this.overlay.style.display = 'block';
  39894. var img = this.overlay.querySelector('img');
  39895. var s = img.style;
  39896. if (isLandscapeMode()) {
  39897. s.width = '20%';
  39898. s.marginLeft = '40%';
  39899. s.marginTop = '3%';
  39900. } else {
  39901. s.width = '50%';
  39902. s.marginLeft = '25%';
  39903. s.marginTop = '25%';
  39904. }
  39905. };
  39906. RotateInstructions.prototype.hide = function () {
  39907. this.overlay.style.display = 'none';
  39908. };
  39909. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  39910. this.show(parent);
  39911. this.timer = setTimeout(this.hide.bind(this), ms);
  39912. };
  39913. RotateInstructions.prototype.disableShowTemporarily = function () {
  39914. clearTimeout(this.timer);
  39915. };
  39916. RotateInstructions.prototype.update = function () {
  39917. this.disableShowTemporarily();
  39918. if (!isLandscapeMode() && isMobile()) {
  39919. this.show();
  39920. } else {
  39921. this.hide();
  39922. }
  39923. };
  39924. RotateInstructions.prototype.loadIcon_ = function () {
  39925. this.icon = base64('image/svg+xml', rotateInstructionsAsset);
  39926. };
  39927. var DEFAULT_VIEWER = 'CardboardV1';
  39928. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  39929. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  39930. function ViewerSelector() {
  39931. try {
  39932. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  39933. } catch (error) {
  39934. console.error('Failed to load viewer profile: %s', error);
  39935. }
  39936. if (!this.selectedKey) {
  39937. this.selectedKey = DEFAULT_VIEWER;
  39938. }
  39939. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  39940. this.root = null;
  39941. this.onChangeCallbacks_ = [];
  39942. }
  39943. ViewerSelector.prototype.show = function (root) {
  39944. this.root = root;
  39945. root.appendChild(this.dialog);
  39946. var selected = this.dialog.querySelector('#' + this.selectedKey);
  39947. selected.checked = true;
  39948. this.dialog.style.display = 'block';
  39949. };
  39950. ViewerSelector.prototype.hide = function () {
  39951. if (this.root && this.root.contains(this.dialog)) {
  39952. this.root.removeChild(this.dialog);
  39953. }
  39954. this.dialog.style.display = 'none';
  39955. };
  39956. ViewerSelector.prototype.getCurrentViewer = function () {
  39957. return DeviceInfo.Viewers[this.selectedKey];
  39958. };
  39959. ViewerSelector.prototype.getSelectedKey_ = function () {
  39960. var input = this.dialog.querySelector('input[name=field]:checked');
  39961. if (input) {
  39962. return input.id;
  39963. }
  39964. return null;
  39965. };
  39966. ViewerSelector.prototype.onChange = function (cb) {
  39967. this.onChangeCallbacks_.push(cb);
  39968. };
  39969. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  39970. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  39971. this.onChangeCallbacks_[i](viewer);
  39972. }
  39973. };
  39974. ViewerSelector.prototype.onSave_ = function () {
  39975. this.selectedKey = this.getSelectedKey_();
  39976. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  39977. console.error('ViewerSelector.onSave_: this should never happen!');
  39978. return;
  39979. }
  39980. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  39981. try {
  39982. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  39983. } catch (error) {
  39984. console.error('Failed to save viewer profile: %s', error);
  39985. }
  39986. this.hide();
  39987. };
  39988. ViewerSelector.prototype.createDialog_ = function (options) {
  39989. var container = document.createElement('div');
  39990. container.classList.add(CLASS_NAME);
  39991. container.style.display = 'none';
  39992. var overlay = document.createElement('div');
  39993. var s = overlay.style;
  39994. s.position = 'fixed';
  39995. s.left = 0;
  39996. s.top = 0;
  39997. s.width = '100%';
  39998. s.height = '100%';
  39999. s.background = 'rgba(0, 0, 0, 0.3)';
  40000. overlay.addEventListener('click', this.hide.bind(this));
  40001. var width = 280;
  40002. var dialog = document.createElement('div');
  40003. var s = dialog.style;
  40004. s.boxSizing = 'border-box';
  40005. s.position = 'fixed';
  40006. s.top = '24px';
  40007. s.left = '50%';
  40008. s.marginLeft = -width / 2 + 'px';
  40009. s.width = width + 'px';
  40010. s.padding = '24px';
  40011. s.overflow = 'hidden';
  40012. s.background = '#fafafa';
  40013. s.fontFamily = "'Roboto', sans-serif";
  40014. s.boxShadow = '0px 5px 20px #666';
  40015. dialog.appendChild(this.createH1_('Select your viewer'));
  40016. for (var id in options) {
  40017. dialog.appendChild(this.createChoice_(id, options[id].label));
  40018. }
  40019. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  40020. container.appendChild(overlay);
  40021. container.appendChild(dialog);
  40022. return container;
  40023. };
  40024. ViewerSelector.prototype.createH1_ = function (name) {
  40025. var h1 = document.createElement('h1');
  40026. var s = h1.style;
  40027. s.color = 'black';
  40028. s.fontSize = '20px';
  40029. s.fontWeight = 'bold';
  40030. s.marginTop = 0;
  40031. s.marginBottom = '24px';
  40032. h1.innerHTML = name;
  40033. return h1;
  40034. };
  40035. ViewerSelector.prototype.createChoice_ = function (id, name) {
  40036. var div = document.createElement('div');
  40037. div.style.marginTop = '8px';
  40038. div.style.color = 'black';
  40039. var input = document.createElement('input');
  40040. input.style.fontSize = '30px';
  40041. input.setAttribute('id', id);
  40042. input.setAttribute('type', 'radio');
  40043. input.setAttribute('value', id);
  40044. input.setAttribute('name', 'field');
  40045. var label = document.createElement('label');
  40046. label.style.marginLeft = '4px';
  40047. label.setAttribute('for', id);
  40048. label.innerHTML = name;
  40049. div.appendChild(input);
  40050. div.appendChild(label);
  40051. return div;
  40052. };
  40053. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  40054. var button = document.createElement('button');
  40055. button.innerHTML = label;
  40056. var s = button.style;
  40057. s.float = 'right';
  40058. s.textTransform = 'uppercase';
  40059. s.color = '#1094f7';
  40060. s.fontSize = '14px';
  40061. s.letterSpacing = 0;
  40062. s.border = 0;
  40063. s.background = 'none';
  40064. s.marginTop = '16px';
  40065. button.addEventListener('click', onclick);
  40066. return button;
  40067. };
  40068. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  40069. function unwrapExports$$1 (x) {
  40070. return x && x.__esModule ? x['default'] : x;
  40071. }
  40072. function createCommonjsModule$$1(fn, module) {
  40073. return module = { exports: {} }, fn(module, module.exports), module.exports;
  40074. }
  40075. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  40076. (function webpackUniversalModuleDefinition(root, factory) {
  40077. module.exports = factory();
  40078. })(commonjsGlobal$$1, function() {
  40079. return (function(modules) {
  40080. var installedModules = {};
  40081. function __webpack_require__(moduleId) {
  40082. if(installedModules[moduleId]) {
  40083. return installedModules[moduleId].exports;
  40084. }
  40085. var module = installedModules[moduleId] = {
  40086. i: moduleId,
  40087. l: false,
  40088. exports: {}
  40089. };
  40090. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  40091. module.l = true;
  40092. return module.exports;
  40093. }
  40094. __webpack_require__.m = modules;
  40095. __webpack_require__.c = installedModules;
  40096. __webpack_require__.d = function(exports, name, getter) {
  40097. if(!__webpack_require__.o(exports, name)) {
  40098. Object.defineProperty(exports, name, {
  40099. configurable: false,
  40100. enumerable: true,
  40101. get: getter
  40102. });
  40103. }
  40104. };
  40105. __webpack_require__.n = function(module) {
  40106. var getter = module && module.__esModule ?
  40107. function getDefault() { return module['default']; } :
  40108. function getModuleExports() { return module; };
  40109. __webpack_require__.d(getter, 'a', getter);
  40110. return getter;
  40111. };
  40112. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  40113. __webpack_require__.p = "";
  40114. return __webpack_require__(__webpack_require__.s = 0);
  40115. })
  40116. ([
  40117. (function(module, exports, __webpack_require__) {
  40118. 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; }; }();
  40119. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  40120. var mediaFile = __webpack_require__(1);
  40121. 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;
  40122. var NoSleep = function () {
  40123. function NoSleep() {
  40124. _classCallCheck(this, NoSleep);
  40125. if (oldIOS) {
  40126. this.noSleepTimer = null;
  40127. } else {
  40128. this.noSleepVideo = document.createElement('video');
  40129. this.noSleepVideo.setAttribute('playsinline', '');
  40130. this.noSleepVideo.setAttribute('src', mediaFile);
  40131. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  40132. if (this.noSleepVideo.currentTime > 0.5) {
  40133. this.noSleepVideo.currentTime = Math.random();
  40134. }
  40135. }.bind(this));
  40136. }
  40137. }
  40138. _createClass(NoSleep, [{
  40139. key: 'enable',
  40140. value: function enable() {
  40141. if (oldIOS) {
  40142. this.disable();
  40143. this.noSleepTimer = window.setInterval(function () {
  40144. window.location.href = '/';
  40145. window.setTimeout(window.stop, 0);
  40146. }, 15000);
  40147. } else {
  40148. this.noSleepVideo.play();
  40149. }
  40150. }
  40151. }, {
  40152. key: 'disable',
  40153. value: function disable() {
  40154. if (oldIOS) {
  40155. if (this.noSleepTimer) {
  40156. window.clearInterval(this.noSleepTimer);
  40157. this.noSleepTimer = null;
  40158. }
  40159. } else {
  40160. this.noSleepVideo.pause();
  40161. }
  40162. }
  40163. }]);
  40164. return NoSleep;
  40165. }();
  40166. module.exports = NoSleep;
  40167. }),
  40168. (function(module, exports, __webpack_require__) {
  40169. 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=';
  40170. })
  40171. ]);
  40172. });
  40173. });
  40174. var NoSleep$1 = unwrapExports$$1(NoSleep);
  40175. var nextDisplayId = 1000;
  40176. var defaultLeftBounds = [0, 0, 0.5, 1];
  40177. var defaultRightBounds = [0.5, 0, 0.5, 1];
  40178. var raf = window.requestAnimationFrame;
  40179. var caf = window.cancelAnimationFrame;
  40180. function VRFrameData() {
  40181. this.leftProjectionMatrix = new Float32Array(16);
  40182. this.leftViewMatrix = new Float32Array(16);
  40183. this.rightProjectionMatrix = new Float32Array(16);
  40184. this.rightViewMatrix = new Float32Array(16);
  40185. this.pose = null;
  40186. }
  40187. function VRDisplayCapabilities(config) {
  40188. Object.defineProperties(this, {
  40189. hasPosition: {
  40190. writable: false, enumerable: true, value: config.hasPosition
  40191. },
  40192. hasExternalDisplay: {
  40193. writable: false, enumerable: true, value: config.hasExternalDisplay
  40194. },
  40195. canPresent: {
  40196. writable: false, enumerable: true, value: config.canPresent
  40197. },
  40198. maxLayers: {
  40199. writable: false, enumerable: true, value: config.maxLayers
  40200. },
  40201. hasOrientation: {
  40202. enumerable: true, get: function get() {
  40203. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  40204. return config.hasOrientation;
  40205. }
  40206. }
  40207. });
  40208. }
  40209. function VRDisplay(config) {
  40210. config = config || {};
  40211. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  40212. this.isPolyfilled = true;
  40213. this.displayId = nextDisplayId++;
  40214. this.displayName = '';
  40215. this.depthNear = 0.01;
  40216. this.depthFar = 10000.0;
  40217. this.isPresenting = false;
  40218. Object.defineProperty(this, 'isConnected', {
  40219. get: function get() {
  40220. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  40221. return false;
  40222. }
  40223. });
  40224. this.capabilities = new VRDisplayCapabilities({
  40225. hasPosition: false,
  40226. hasOrientation: false,
  40227. hasExternalDisplay: false,
  40228. canPresent: false,
  40229. maxLayers: 1
  40230. });
  40231. this.stageParameters = null;
  40232. this.waitingForPresent_ = false;
  40233. this.layer_ = null;
  40234. this.originalParent_ = null;
  40235. this.fullscreenElement_ = null;
  40236. this.fullscreenWrapper_ = null;
  40237. this.fullscreenElementCachedStyle_ = null;
  40238. this.fullscreenEventTarget_ = null;
  40239. this.fullscreenChangeHandler_ = null;
  40240. this.fullscreenErrorHandler_ = null;
  40241. if (USE_WAKELOCK && isMobile()) {
  40242. this.wakelock_ = new NoSleep$1();
  40243. }
  40244. }
  40245. VRDisplay.prototype.getFrameData = function (frameData) {
  40246. return frameDataFromPose(frameData, this._getPose(), this);
  40247. };
  40248. VRDisplay.prototype.getPose = function () {
  40249. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  40250. return this._getPose();
  40251. };
  40252. VRDisplay.prototype.resetPose = function () {
  40253. deprecateWarning('VRDisplay.prototype.resetPose');
  40254. return this._resetPose();
  40255. };
  40256. VRDisplay.prototype.getImmediatePose = function () {
  40257. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  40258. return this._getPose();
  40259. };
  40260. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  40261. return raf(callback);
  40262. };
  40263. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  40264. return caf(id);
  40265. };
  40266. VRDisplay.prototype.wrapForFullscreen = function (element) {
  40267. if (isIOS()) {
  40268. return element;
  40269. }
  40270. if (!this.fullscreenWrapper_) {
  40271. this.fullscreenWrapper_ = document.createElement('div');
  40272. 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'];
  40273. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  40274. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  40275. }
  40276. if (this.fullscreenElement_ == element) {
  40277. return this.fullscreenWrapper_;
  40278. }
  40279. if (this.fullscreenElement_) {
  40280. if (this.originalParent_) {
  40281. this.originalParent_.appendChild(this.fullscreenElement_);
  40282. } else {
  40283. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  40284. }
  40285. }
  40286. this.fullscreenElement_ = element;
  40287. this.originalParent_ = element.parentElement;
  40288. if (!this.originalParent_) {
  40289. document.body.appendChild(element);
  40290. }
  40291. if (!this.fullscreenWrapper_.parentElement) {
  40292. var parent = this.fullscreenElement_.parentElement;
  40293. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  40294. parent.removeChild(this.fullscreenElement_);
  40295. }
  40296. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  40297. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  40298. var self = this;
  40299. function applyFullscreenElementStyle() {
  40300. if (!self.fullscreenElement_) {
  40301. return;
  40302. }
  40303. 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'];
  40304. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  40305. }
  40306. applyFullscreenElementStyle();
  40307. return this.fullscreenWrapper_;
  40308. };
  40309. VRDisplay.prototype.removeFullscreenWrapper = function () {
  40310. if (!this.fullscreenElement_) {
  40311. return;
  40312. }
  40313. var element = this.fullscreenElement_;
  40314. if (this.fullscreenElementCachedStyle_) {
  40315. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  40316. } else {
  40317. element.removeAttribute('style');
  40318. }
  40319. this.fullscreenElement_ = null;
  40320. this.fullscreenElementCachedStyle_ = null;
  40321. var parent = this.fullscreenWrapper_.parentElement;
  40322. this.fullscreenWrapper_.removeChild(element);
  40323. if (this.originalParent_ === parent) {
  40324. parent.insertBefore(element, this.fullscreenWrapper_);
  40325. }
  40326. else if (this.originalParent_) {
  40327. this.originalParent_.appendChild(element);
  40328. }
  40329. parent.removeChild(this.fullscreenWrapper_);
  40330. return element;
  40331. };
  40332. VRDisplay.prototype.requestPresent = function (layers) {
  40333. var wasPresenting = this.isPresenting;
  40334. var self = this;
  40335. if (!(layers instanceof Array)) {
  40336. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  40337. layers = [layers];
  40338. }
  40339. return new Promise(function (resolve, reject) {
  40340. if (!self.capabilities.canPresent) {
  40341. reject(new Error('VRDisplay is not capable of presenting.'));
  40342. return;
  40343. }
  40344. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  40345. reject(new Error('Invalid number of layers.'));
  40346. return;
  40347. }
  40348. var incomingLayer = layers[0];
  40349. if (!incomingLayer.source) {
  40350. resolve();
  40351. return;
  40352. }
  40353. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  40354. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  40355. if (wasPresenting) {
  40356. var layer = self.layer_;
  40357. if (layer.source !== incomingLayer.source) {
  40358. layer.source = incomingLayer.source;
  40359. }
  40360. for (var i = 0; i < 4; i++) {
  40361. layer.leftBounds[i] = leftBounds[i];
  40362. layer.rightBounds[i] = rightBounds[i];
  40363. }
  40364. self.wrapForFullscreen(self.layer_.source);
  40365. self.updatePresent_();
  40366. resolve();
  40367. return;
  40368. }
  40369. self.layer_ = {
  40370. predistorted: incomingLayer.predistorted,
  40371. source: incomingLayer.source,
  40372. leftBounds: leftBounds.slice(0),
  40373. rightBounds: rightBounds.slice(0)
  40374. };
  40375. self.waitingForPresent_ = false;
  40376. if (self.layer_ && self.layer_.source) {
  40377. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  40378. var onFullscreenChange = function onFullscreenChange() {
  40379. var actualFullscreenElement = getFullscreenElement();
  40380. self.isPresenting = fullscreenElement === actualFullscreenElement;
  40381. if (self.isPresenting) {
  40382. if (screen.orientation && screen.orientation.lock) {
  40383. screen.orientation.lock('landscape-primary').catch(function (error) {
  40384. console.error('screen.orientation.lock() failed due to', error.message);
  40385. });
  40386. }
  40387. self.waitingForPresent_ = false;
  40388. self.beginPresent_();
  40389. resolve();
  40390. } else {
  40391. if (screen.orientation && screen.orientation.unlock) {
  40392. screen.orientation.unlock();
  40393. }
  40394. self.removeFullscreenWrapper();
  40395. self.disableWakeLock();
  40396. self.endPresent_();
  40397. self.removeFullscreenListeners_();
  40398. }
  40399. self.fireVRDisplayPresentChange_();
  40400. };
  40401. var onFullscreenError = function onFullscreenError() {
  40402. if (!self.waitingForPresent_) {
  40403. return;
  40404. }
  40405. self.removeFullscreenWrapper();
  40406. self.removeFullscreenListeners_();
  40407. self.disableWakeLock();
  40408. self.waitingForPresent_ = false;
  40409. self.isPresenting = false;
  40410. reject(new Error('Unable to present.'));
  40411. };
  40412. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  40413. if (requestFullscreen(fullscreenElement)) {
  40414. self.enableWakeLock();
  40415. self.waitingForPresent_ = true;
  40416. } else if (isIOS() || isWebViewAndroid()) {
  40417. self.enableWakeLock();
  40418. self.isPresenting = true;
  40419. self.beginPresent_();
  40420. self.fireVRDisplayPresentChange_();
  40421. resolve();
  40422. }
  40423. }
  40424. if (!self.waitingForPresent_ && !isIOS()) {
  40425. exitFullscreen();
  40426. reject(new Error('Unable to present.'));
  40427. }
  40428. });
  40429. };
  40430. VRDisplay.prototype.exitPresent = function () {
  40431. var wasPresenting = this.isPresenting;
  40432. var self = this;
  40433. this.isPresenting = false;
  40434. this.layer_ = null;
  40435. this.disableWakeLock();
  40436. return new Promise(function (resolve, reject) {
  40437. if (wasPresenting) {
  40438. if (!exitFullscreen() && isIOS()) {
  40439. self.endPresent_();
  40440. self.fireVRDisplayPresentChange_();
  40441. }
  40442. if (isWebViewAndroid()) {
  40443. self.removeFullscreenWrapper();
  40444. self.removeFullscreenListeners_();
  40445. self.endPresent_();
  40446. self.fireVRDisplayPresentChange_();
  40447. }
  40448. resolve();
  40449. } else {
  40450. reject(new Error('Was not presenting to VRDisplay.'));
  40451. }
  40452. });
  40453. };
  40454. VRDisplay.prototype.getLayers = function () {
  40455. if (this.layer_) {
  40456. return [this.layer_];
  40457. }
  40458. return [];
  40459. };
  40460. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  40461. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  40462. window.dispatchEvent(event);
  40463. };
  40464. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  40465. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  40466. window.dispatchEvent(event);
  40467. };
  40468. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  40469. this.removeFullscreenListeners_();
  40470. this.fullscreenEventTarget_ = element;
  40471. this.fullscreenChangeHandler_ = changeHandler;
  40472. this.fullscreenErrorHandler_ = errorHandler;
  40473. if (changeHandler) {
  40474. if (document.fullscreenEnabled) {
  40475. element.addEventListener('fullscreenchange', changeHandler, false);
  40476. } else if (document.webkitFullscreenEnabled) {
  40477. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  40478. } else if (document.mozFullScreenEnabled) {
  40479. document.addEventListener('mozfullscreenchange', changeHandler, false);
  40480. } else if (document.msFullscreenEnabled) {
  40481. element.addEventListener('msfullscreenchange', changeHandler, false);
  40482. }
  40483. }
  40484. if (errorHandler) {
  40485. if (document.fullscreenEnabled) {
  40486. element.addEventListener('fullscreenerror', errorHandler, false);
  40487. } else if (document.webkitFullscreenEnabled) {
  40488. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  40489. } else if (document.mozFullScreenEnabled) {
  40490. document.addEventListener('mozfullscreenerror', errorHandler, false);
  40491. } else if (document.msFullscreenEnabled) {
  40492. element.addEventListener('msfullscreenerror', errorHandler, false);
  40493. }
  40494. }
  40495. };
  40496. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  40497. if (!this.fullscreenEventTarget_) return;
  40498. var element = this.fullscreenEventTarget_;
  40499. if (this.fullscreenChangeHandler_) {
  40500. var changeHandler = this.fullscreenChangeHandler_;
  40501. element.removeEventListener('fullscreenchange', changeHandler, false);
  40502. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  40503. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  40504. element.removeEventListener('msfullscreenchange', changeHandler, false);
  40505. }
  40506. if (this.fullscreenErrorHandler_) {
  40507. var errorHandler = this.fullscreenErrorHandler_;
  40508. element.removeEventListener('fullscreenerror', errorHandler, false);
  40509. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  40510. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  40511. element.removeEventListener('msfullscreenerror', errorHandler, false);
  40512. }
  40513. this.fullscreenEventTarget_ = null;
  40514. this.fullscreenChangeHandler_ = null;
  40515. this.fullscreenErrorHandler_ = null;
  40516. };
  40517. VRDisplay.prototype.enableWakeLock = function () {
  40518. if (this.wakelock_) {
  40519. this.wakelock_.enable();
  40520. }
  40521. };
  40522. VRDisplay.prototype.disableWakeLock = function () {
  40523. if (this.wakelock_) {
  40524. this.wakelock_.disable();
  40525. }
  40526. };
  40527. VRDisplay.prototype.beginPresent_ = function () {
  40528. };
  40529. VRDisplay.prototype.endPresent_ = function () {
  40530. };
  40531. VRDisplay.prototype.submitFrame = function (pose) {
  40532. };
  40533. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  40534. return null;
  40535. };
  40536. var config = {
  40537. MOBILE_WAKE_LOCK: true,
  40538. DEBUG: false,
  40539. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  40540. K_FILTER: 0.98,
  40541. PREDICTION_TIME_S: 0.040,
  40542. CARDBOARD_UI_DISABLED: false,
  40543. ROTATE_INSTRUCTIONS_DISABLED: false,
  40544. YAW_ONLY: false,
  40545. BUFFER_SCALE: 0.5,
  40546. DIRTY_SUBMIT_FRAME_BINDINGS: false
  40547. };
  40548. var Eye = {
  40549. LEFT: 'left',
  40550. RIGHT: 'right'
  40551. };
  40552. function CardboardVRDisplay(config$$1) {
  40553. var defaults = extend({}, config);
  40554. config$$1 = extend(defaults, config$$1 || {});
  40555. VRDisplay.call(this, {
  40556. wakelock: config$$1.MOBILE_WAKE_LOCK
  40557. });
  40558. this.config = config$$1;
  40559. this.displayName = 'Cardboard VRDisplay';
  40560. this.capabilities = new VRDisplayCapabilities({
  40561. hasPosition: false,
  40562. hasOrientation: true,
  40563. hasExternalDisplay: false,
  40564. canPresent: true,
  40565. maxLayers: 1
  40566. });
  40567. this.stageParameters = null;
  40568. this.bufferScale_ = this.config.BUFFER_SCALE;
  40569. this.poseSensor_ = new PoseSensor(this.config);
  40570. this.distorter_ = null;
  40571. this.cardboardUI_ = null;
  40572. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  40573. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams());
  40574. this.viewerSelector_ = new ViewerSelector();
  40575. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  40576. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  40577. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  40578. this.rotateInstructions_ = new RotateInstructions();
  40579. }
  40580. if (isIOS()) {
  40581. window.addEventListener('resize', this.onResize_.bind(this));
  40582. }
  40583. }
  40584. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  40585. CardboardVRDisplay.prototype._getPose = function () {
  40586. return {
  40587. position: null,
  40588. orientation: this.poseSensor_.getOrientation(),
  40589. linearVelocity: null,
  40590. linearAcceleration: null,
  40591. angularVelocity: null,
  40592. angularAcceleration: null
  40593. };
  40594. };
  40595. CardboardVRDisplay.prototype._resetPose = function () {
  40596. if (this.poseSensor_.resetPose) {
  40597. this.poseSensor_.resetPose();
  40598. }
  40599. };
  40600. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  40601. var fieldOfView;
  40602. if (whichEye == Eye.LEFT) {
  40603. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  40604. } else if (whichEye == Eye.RIGHT) {
  40605. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  40606. } else {
  40607. console.error('Invalid eye provided: %s', whichEye);
  40608. return null;
  40609. }
  40610. return fieldOfView;
  40611. };
  40612. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  40613. var offset;
  40614. if (whichEye == Eye.LEFT) {
  40615. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  40616. } else if (whichEye == Eye.RIGHT) {
  40617. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  40618. } else {
  40619. console.error('Invalid eye provided: %s', whichEye);
  40620. return null;
  40621. }
  40622. return offset;
  40623. };
  40624. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  40625. var offset = this._getEyeOffset(whichEye);
  40626. var fieldOfView = this._getFieldOfView(whichEye);
  40627. var eyeParams = {
  40628. offset: offset,
  40629. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  40630. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  40631. };
  40632. Object.defineProperty(eyeParams, 'fieldOfView', {
  40633. enumerable: true,
  40634. get: function get() {
  40635. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  40636. return fieldOfView;
  40637. }
  40638. });
  40639. return eyeParams;
  40640. };
  40641. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  40642. if (this.config.DEBUG) {
  40643. console.log('DPDB reported that device params were updated.');
  40644. }
  40645. this.deviceInfo_.updateDeviceParams(newParams);
  40646. if (this.distorter_) {
  40647. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40648. }
  40649. };
  40650. CardboardVRDisplay.prototype.updateBounds_ = function () {
  40651. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  40652. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  40653. }
  40654. };
  40655. CardboardVRDisplay.prototype.beginPresent_ = function () {
  40656. var gl = this.layer_.source.getContext('webgl');
  40657. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  40658. if (!gl) gl = this.layer_.source.getContext('webgl2');
  40659. if (!gl) return;
  40660. if (this.layer_.predistorted) {
  40661. if (!this.config.CARDBOARD_UI_DISABLED) {
  40662. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  40663. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  40664. this.cardboardUI_ = new CardboardUI(gl);
  40665. }
  40666. } else {
  40667. if (!this.config.CARDBOARD_UI_DISABLED) {
  40668. this.cardboardUI_ = new CardboardUI(gl);
  40669. }
  40670. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  40671. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40672. }
  40673. if (this.cardboardUI_) {
  40674. this.cardboardUI_.listen(function (e) {
  40675. this.viewerSelector_.show(this.layer_.source.parentElement);
  40676. e.stopPropagation();
  40677. e.preventDefault();
  40678. }.bind(this), function (e) {
  40679. this.exitPresent();
  40680. e.stopPropagation();
  40681. e.preventDefault();
  40682. }.bind(this));
  40683. }
  40684. if (this.rotateInstructions_) {
  40685. if (isLandscapeMode() && isMobile()) {
  40686. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  40687. } else {
  40688. this.rotateInstructions_.update();
  40689. }
  40690. }
  40691. this.orientationHandler = this.onOrientationChange_.bind(this);
  40692. window.addEventListener('orientationchange', this.orientationHandler);
  40693. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  40694. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  40695. this.fireVRDisplayDeviceParamsChange_();
  40696. };
  40697. CardboardVRDisplay.prototype.endPresent_ = function () {
  40698. if (this.distorter_) {
  40699. this.distorter_.destroy();
  40700. this.distorter_ = null;
  40701. }
  40702. if (this.cardboardUI_) {
  40703. this.cardboardUI_.destroy();
  40704. this.cardboardUI_ = null;
  40705. }
  40706. if (this.rotateInstructions_) {
  40707. this.rotateInstructions_.hide();
  40708. }
  40709. this.viewerSelector_.hide();
  40710. window.removeEventListener('orientationchange', this.orientationHandler);
  40711. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  40712. };
  40713. CardboardVRDisplay.prototype.updatePresent_ = function () {
  40714. this.endPresent_();
  40715. this.beginPresent_();
  40716. };
  40717. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  40718. if (this.distorter_) {
  40719. this.updateBounds_();
  40720. this.distorter_.submitFrame();
  40721. } else if (this.cardboardUI_ && this.layer_) {
  40722. var canvas = this.layer_.source.getContext('webgl').canvas;
  40723. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  40724. this.cardboardUI_.onResize();
  40725. }
  40726. this.lastWidth = canvas.width;
  40727. this.lastHeight = canvas.height;
  40728. this.cardboardUI_.render();
  40729. }
  40730. };
  40731. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  40732. this.viewerSelector_.hide();
  40733. if (this.rotateInstructions_) {
  40734. this.rotateInstructions_.update();
  40735. }
  40736. this.onResize_();
  40737. };
  40738. CardboardVRDisplay.prototype.onResize_ = function (e) {
  40739. if (this.layer_) {
  40740. var gl = this.layer_.source.getContext('webgl');
  40741. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  40742. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  40743. 'padding: 0px', 'box-sizing: content-box'];
  40744. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  40745. safariCssSizeWorkaround(gl.canvas);
  40746. }
  40747. };
  40748. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  40749. this.deviceInfo_.setViewer(viewer);
  40750. if (this.distorter_) {
  40751. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40752. }
  40753. this.fireVRDisplayDeviceParamsChange_();
  40754. };
  40755. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  40756. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  40757. detail: {
  40758. vrdisplay: this,
  40759. deviceInfo: this.deviceInfo_
  40760. }
  40761. });
  40762. window.dispatchEvent(event);
  40763. };
  40764. CardboardVRDisplay.VRFrameData = VRFrameData;
  40765. CardboardVRDisplay.VRDisplay = VRDisplay;
  40766. return CardboardVRDisplay;
  40767. })));
  40768. });
  40769. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  40770. var version = "0.10.5";
  40771. var DefaultConfig = {
  40772. PROVIDE_MOBILE_VRDISPLAY: true,
  40773. GET_VR_DISPLAYS_TIMEOUT: 1000,
  40774. MOBILE_WAKE_LOCK: true,
  40775. DEBUG: false,
  40776. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  40777. K_FILTER: 0.98,
  40778. PREDICTION_TIME_S: 0.040,
  40779. TOUCH_PANNER_DISABLED: true,
  40780. CARDBOARD_UI_DISABLED: false,
  40781. ROTATE_INSTRUCTIONS_DISABLED: false,
  40782. YAW_ONLY: false,
  40783. BUFFER_SCALE: 0.5,
  40784. DIRTY_SUBMIT_FRAME_BINDINGS: false
  40785. };
  40786. function WebVRPolyfill(config) {
  40787. this.config = extend(extend({}, DefaultConfig), config);
  40788. this.polyfillDisplays = [];
  40789. this.enabled = false;
  40790. this.hasNative = 'getVRDisplays' in navigator;
  40791. this.native = {};
  40792. this.native.getVRDisplays = navigator.getVRDisplays;
  40793. this.native.VRFrameData = window.VRFrameData;
  40794. this.native.VRDisplay = window.VRDisplay;
  40795. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  40796. this.enable();
  40797. this.getVRDisplays().then(function (displays) {
  40798. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  40799. displays[0].fireVRDisplayConnect_();
  40800. }
  40801. });
  40802. }
  40803. }
  40804. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  40805. if (this._polyfillDisplaysPopulated) {
  40806. return this.polyfillDisplays;
  40807. }
  40808. if (isMobile()) {
  40809. var vrDisplay = new CardboardVRDisplay({
  40810. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  40811. DEBUG: this.config.DEBUG,
  40812. DPDB_URL: this.config.DPDB_URL,
  40813. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  40814. K_FILTER: this.config.K_FILTER,
  40815. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  40816. TOUCH_PANNER_DISABLED: this.config.TOUCH_PANNER_DISABLED,
  40817. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  40818. YAW_ONLY: this.config.YAW_ONLY,
  40819. BUFFER_SCALE: this.config.BUFFER_SCALE,
  40820. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  40821. });
  40822. this.polyfillDisplays.push(vrDisplay);
  40823. }
  40824. this._polyfillDisplaysPopulated = true;
  40825. return this.polyfillDisplays;
  40826. };
  40827. WebVRPolyfill.prototype.enable = function () {
  40828. this.enabled = true;
  40829. if (this.hasNative && this.native.VRFrameData) {
  40830. var NativeVRFrameData = this.native.VRFrameData;
  40831. var nativeFrameData = new this.native.VRFrameData();
  40832. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  40833. window.VRDisplay.prototype.getFrameData = function (frameData) {
  40834. if (frameData instanceof NativeVRFrameData) {
  40835. nativeGetFrameData.call(this, frameData);
  40836. return;
  40837. }
  40838. nativeGetFrameData.call(this, nativeFrameData);
  40839. frameData.pose = nativeFrameData.pose;
  40840. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  40841. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  40842. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  40843. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  40844. };
  40845. }
  40846. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  40847. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  40848. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  40849. };
  40850. WebVRPolyfill.prototype.getVRDisplays = function () {
  40851. var _this = this;
  40852. var config = this.config;
  40853. if (!this.hasNative) {
  40854. return Promise.resolve(this.getPolyfillDisplays());
  40855. }
  40856. var timeoutId;
  40857. var vrDisplaysNative = this.native.getVRDisplays.call(navigator);
  40858. var timeoutPromise = new Promise(function (resolve) {
  40859. timeoutId = setTimeout(function () {
  40860. console.warn('Native WebVR implementation detected, but `getVRDisplays()` failed to resolve. Falling back to polyfill.');
  40861. resolve([]);
  40862. }, config.GET_VR_DISPLAYS_TIMEOUT);
  40863. });
  40864. return race([vrDisplaysNative, timeoutPromise]).then(function (nativeDisplays) {
  40865. clearTimeout(timeoutId);
  40866. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  40867. });
  40868. };
  40869. WebVRPolyfill.version = version;
  40870. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  40871. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  40872. var webvrPolyfill = Object.freeze({
  40873. default: WebVRPolyfill
  40874. });
  40875. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  40876. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  40877. if (!commonjsGlobal.document) {
  40878. commonjsGlobal.document = commonjsGlobal.window.document;
  40879. }
  40880. if (!commonjsGlobal.navigator) {
  40881. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  40882. }
  40883. }
  40884. var src = require$$0;
  40885. return src;
  40886. })));
  40887. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  40888. },{}],47:[function(_dereq_,module,exports){
  40889. var newline = /\n/
  40890. var newlineChar = '\n'
  40891. var whitespace = /\s/
  40892. module.exports = function(text, opt) {
  40893. var lines = module.exports.lines(text, opt)
  40894. return lines.map(function(line) {
  40895. return text.substring(line.start, line.end)
  40896. }).join('\n')
  40897. }
  40898. module.exports.lines = function wordwrap(text, opt) {
  40899. opt = opt||{}
  40900. //zero width results in nothing visible
  40901. if (opt.width === 0 && opt.mode !== 'nowrap')
  40902. return []
  40903. text = text||''
  40904. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  40905. var start = Math.max(0, opt.start||0)
  40906. var end = typeof opt.end === 'number' ? opt.end : text.length
  40907. var mode = opt.mode
  40908. var measure = opt.measure || monospace
  40909. if (mode === 'pre')
  40910. return pre(measure, text, start, end, width)
  40911. else
  40912. return greedy(measure, text, start, end, width, mode)
  40913. }
  40914. function idxOf(text, chr, start, end) {
  40915. var idx = text.indexOf(chr, start)
  40916. if (idx === -1 || idx > end)
  40917. return end
  40918. return idx
  40919. }
  40920. function isWhitespace(chr) {
  40921. return whitespace.test(chr)
  40922. }
  40923. function pre(measure, text, start, end, width) {
  40924. var lines = []
  40925. var lineStart = start
  40926. for (var i=start; i<end && i<text.length; i++) {
  40927. var chr = text.charAt(i)
  40928. var isNewline = newline.test(chr)
  40929. //If we've reached a newline, then step down a line
  40930. //Or if we've reached the EOF
  40931. if (isNewline || i===end-1) {
  40932. var lineEnd = isNewline ? i : i+1
  40933. var measured = measure(text, lineStart, lineEnd, width)
  40934. lines.push(measured)
  40935. lineStart = i+1
  40936. }
  40937. }
  40938. return lines
  40939. }
  40940. function greedy(measure, text, start, end, width, mode) {
  40941. //A greedy word wrapper based on LibGDX algorithm
  40942. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  40943. var lines = []
  40944. var testWidth = width
  40945. //if 'nowrap' is specified, we only wrap on newline chars
  40946. if (mode === 'nowrap')
  40947. testWidth = Number.MAX_VALUE
  40948. while (start < end && start < text.length) {
  40949. //get next newline position
  40950. var newLine = idxOf(text, newlineChar, start, end)
  40951. //eat whitespace at start of line
  40952. while (start < newLine) {
  40953. if (!isWhitespace( text.charAt(start) ))
  40954. break
  40955. start++
  40956. }
  40957. //determine visible # of glyphs for the available width
  40958. var measured = measure(text, start, newLine, testWidth)
  40959. var lineEnd = start + (measured.end-measured.start)
  40960. var nextStart = lineEnd + newlineChar.length
  40961. //if we had to cut the line before the next newline...
  40962. if (lineEnd < newLine) {
  40963. //find char to break on
  40964. while (lineEnd > start) {
  40965. if (isWhitespace(text.charAt(lineEnd)))
  40966. break
  40967. lineEnd--
  40968. }
  40969. if (lineEnd === start) {
  40970. if (nextStart > start + newlineChar.length) nextStart--
  40971. lineEnd = nextStart // If no characters to break, show all.
  40972. } else {
  40973. nextStart = lineEnd
  40974. //eat whitespace at end of line
  40975. while (lineEnd > start) {
  40976. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  40977. break
  40978. lineEnd--
  40979. }
  40980. }
  40981. }
  40982. if (lineEnd >= start) {
  40983. var result = measure(text, start, lineEnd, testWidth)
  40984. lines.push(result)
  40985. }
  40986. start = nextStart
  40987. }
  40988. return lines
  40989. }
  40990. //determines the visible number of glyphs within a given width
  40991. function monospace(text, start, end, width) {
  40992. var glyphs = Math.min(width, end-start)
  40993. return {
  40994. start: start,
  40995. end: start+glyphs
  40996. }
  40997. }
  40998. },{}],48:[function(_dereq_,module,exports){
  40999. "use strict";
  41000. var window = _dereq_("global/window")
  41001. var isFunction = _dereq_("is-function")
  41002. var parseHeaders = _dereq_("parse-headers")
  41003. var xtend = _dereq_("xtend")
  41004. module.exports = createXHR
  41005. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  41006. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  41007. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  41008. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  41009. options = initParams(uri, options, callback)
  41010. options.method = method.toUpperCase()
  41011. return _createXHR(options)
  41012. }
  41013. })
  41014. function forEachArray(array, iterator) {
  41015. for (var i = 0; i < array.length; i++) {
  41016. iterator(array[i])
  41017. }
  41018. }
  41019. function isEmpty(obj){
  41020. for(var i in obj){
  41021. if(obj.hasOwnProperty(i)) return false
  41022. }
  41023. return true
  41024. }
  41025. function initParams(uri, options, callback) {
  41026. var params = uri
  41027. if (isFunction(options)) {
  41028. callback = options
  41029. if (typeof uri === "string") {
  41030. params = {uri:uri}
  41031. }
  41032. } else {
  41033. params = xtend(options, {uri: uri})
  41034. }
  41035. params.callback = callback
  41036. return params
  41037. }
  41038. function createXHR(uri, options, callback) {
  41039. options = initParams(uri, options, callback)
  41040. return _createXHR(options)
  41041. }
  41042. function _createXHR(options) {
  41043. if(typeof options.callback === "undefined"){
  41044. throw new Error("callback argument missing")
  41045. }
  41046. var called = false
  41047. var callback = function cbOnce(err, response, body){
  41048. if(!called){
  41049. called = true
  41050. options.callback(err, response, body)
  41051. }
  41052. }
  41053. function readystatechange() {
  41054. if (xhr.readyState === 4) {
  41055. setTimeout(loadFunc, 0)
  41056. }
  41057. }
  41058. function getBody() {
  41059. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  41060. var body = undefined
  41061. if (xhr.response) {
  41062. body = xhr.response
  41063. } else {
  41064. body = xhr.responseText || getXml(xhr)
  41065. }
  41066. if (isJson) {
  41067. try {
  41068. body = JSON.parse(body)
  41069. } catch (e) {}
  41070. }
  41071. return body
  41072. }
  41073. function errorFunc(evt) {
  41074. clearTimeout(timeoutTimer)
  41075. if(!(evt instanceof Error)){
  41076. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  41077. }
  41078. evt.statusCode = 0
  41079. return callback(evt, failureResponse)
  41080. }
  41081. // will load the data & process the response in a special response object
  41082. function loadFunc() {
  41083. if (aborted) return
  41084. var status
  41085. clearTimeout(timeoutTimer)
  41086. if(options.useXDR && xhr.status===undefined) {
  41087. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  41088. status = 200
  41089. } else {
  41090. status = (xhr.status === 1223 ? 204 : xhr.status)
  41091. }
  41092. var response = failureResponse
  41093. var err = null
  41094. if (status !== 0){
  41095. response = {
  41096. body: getBody(),
  41097. statusCode: status,
  41098. method: method,
  41099. headers: {},
  41100. url: uri,
  41101. rawRequest: xhr
  41102. }
  41103. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  41104. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  41105. }
  41106. } else {
  41107. err = new Error("Internal XMLHttpRequest Error")
  41108. }
  41109. return callback(err, response, response.body)
  41110. }
  41111. var xhr = options.xhr || null
  41112. if (!xhr) {
  41113. if (options.cors || options.useXDR) {
  41114. xhr = new createXHR.XDomainRequest()
  41115. }else{
  41116. xhr = new createXHR.XMLHttpRequest()
  41117. }
  41118. }
  41119. var key
  41120. var aborted
  41121. var uri = xhr.url = options.uri || options.url
  41122. var method = xhr.method = options.method || "GET"
  41123. var body = options.body || options.data
  41124. var headers = xhr.headers = options.headers || {}
  41125. var sync = !!options.sync
  41126. var isJson = false
  41127. var timeoutTimer
  41128. var failureResponse = {
  41129. body: undefined,
  41130. headers: {},
  41131. statusCode: 0,
  41132. method: method,
  41133. url: uri,
  41134. rawRequest: xhr
  41135. }
  41136. if ("json" in options && options.json !== false) {
  41137. isJson = true
  41138. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  41139. if (method !== "GET" && method !== "HEAD") {
  41140. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  41141. body = JSON.stringify(options.json === true ? body : options.json)
  41142. }
  41143. }
  41144. xhr.onreadystatechange = readystatechange
  41145. xhr.onload = loadFunc
  41146. xhr.onerror = errorFunc
  41147. // IE9 must have onprogress be set to a unique function.
  41148. xhr.onprogress = function () {
  41149. // IE must die
  41150. }
  41151. xhr.onabort = function(){
  41152. aborted = true;
  41153. }
  41154. xhr.ontimeout = errorFunc
  41155. xhr.open(method, uri, !sync, options.username, options.password)
  41156. //has to be after open
  41157. if(!sync) {
  41158. xhr.withCredentials = !!options.withCredentials
  41159. }
  41160. // Cannot set timeout with sync request
  41161. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  41162. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  41163. if (!sync && options.timeout > 0 ) {
  41164. timeoutTimer = setTimeout(function(){
  41165. if (aborted) return
  41166. aborted = true//IE9 may still call readystatechange
  41167. xhr.abort("timeout")
  41168. var e = new Error("XMLHttpRequest timeout")
  41169. e.code = "ETIMEDOUT"
  41170. errorFunc(e)
  41171. }, options.timeout )
  41172. }
  41173. if (xhr.setRequestHeader) {
  41174. for(key in headers){
  41175. if(headers.hasOwnProperty(key)){
  41176. xhr.setRequestHeader(key, headers[key])
  41177. }
  41178. }
  41179. } else if (options.headers && !isEmpty(options.headers)) {
  41180. throw new Error("Headers cannot be set on an XDomainRequest object")
  41181. }
  41182. if ("responseType" in options) {
  41183. xhr.responseType = options.responseType
  41184. }
  41185. if ("beforeSend" in options &&
  41186. typeof options.beforeSend === "function"
  41187. ) {
  41188. options.beforeSend(xhr)
  41189. }
  41190. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  41191. // XMLHttpRequest spec says to pass null as body to indicate no body
  41192. // See https://github.com/naugtur/xhr/issues/100.
  41193. xhr.send(body || null)
  41194. return xhr
  41195. }
  41196. function getXml(xhr) {
  41197. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  41198. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  41199. try {
  41200. if (xhr.responseType === "document") {
  41201. return xhr.responseXML
  41202. }
  41203. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  41204. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  41205. return xhr.responseXML
  41206. }
  41207. } catch (e) {}
  41208. return null
  41209. }
  41210. function noop() {}
  41211. },{"global/window":15,"is-function":19,"parse-headers":30,"xtend":50}],49:[function(_dereq_,module,exports){
  41212. module.exports = (function xmlparser() {
  41213. //common browsers
  41214. if (typeof self.DOMParser !== 'undefined') {
  41215. return function(str) {
  41216. var parser = new self.DOMParser()
  41217. return parser.parseFromString(str, 'application/xml')
  41218. }
  41219. }
  41220. //IE8 fallback
  41221. if (typeof self.ActiveXObject !== 'undefined'
  41222. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  41223. return function(str) {
  41224. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  41225. xmlDoc.async = "false"
  41226. xmlDoc.loadXML(str)
  41227. return xmlDoc
  41228. }
  41229. }
  41230. //last resort fallback
  41231. return function(str) {
  41232. var div = document.createElement('div')
  41233. div.innerHTML = str
  41234. return div
  41235. }
  41236. })()
  41237. },{}],50:[function(_dereq_,module,exports){
  41238. module.exports = extend
  41239. var hasOwnProperty = Object.prototype.hasOwnProperty;
  41240. function extend() {
  41241. var target = {}
  41242. for (var i = 0; i < arguments.length; i++) {
  41243. var source = arguments[i]
  41244. for (var key in source) {
  41245. if (hasOwnProperty.call(source, key)) {
  41246. target[key] = source[key]
  41247. }
  41248. }
  41249. }
  41250. return target
  41251. }
  41252. },{}],51:[function(_dereq_,module,exports){
  41253. module.exports={
  41254. "name": "aframe",
  41255. "version": "0.8.2",
  41256. "description": "A web framework for building virtual reality experiences.",
  41257. "homepage": "https://aframe.io/",
  41258. "main": "dist/aframe-master.js",
  41259. "scripts": {
  41260. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  41261. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [envify --INSPECTOR_VERSION dev] -o build/aframe.js",
  41262. "codecov": "codecov",
  41263. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  41264. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  41265. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  41266. "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",
  41267. "docs": "markserv --dir docs --port 9001",
  41268. "preghpages": "node ./scripts/preghpages.js",
  41269. "ghpages": "ghpages -p gh-pages/",
  41270. "lint": "semistandard -v | snazzy",
  41271. "lint:fix": "semistandard --fix",
  41272. "precommit": "npm run lint",
  41273. "prepush": "node scripts/testOnlyCheck.js",
  41274. "prerelease": "node scripts/release.js 0.7.1 0.8.0",
  41275. "start": "npm run dev",
  41276. "test": "karma start ./tests/karma.conf.js",
  41277. "test:docs": "node scripts/docsLint.js",
  41278. "test:firefox": "npm test -- --browsers Firefox",
  41279. "test:chrome": "npm test -- --browsers Chrome",
  41280. "test:nobrowser": "NO_BROWSER=true npm test",
  41281. "test:node": "mocha --ui tdd tests/node"
  41282. },
  41283. "repository": "aframevr/aframe",
  41284. "license": "MIT",
  41285. "files": [
  41286. "dist/*",
  41287. "docs/**/*",
  41288. "src/**/*",
  41289. "vendor/**/*"
  41290. ],
  41291. "dependencies": {
  41292. "animejs": "^2.2.0",
  41293. "browserify-css": "^0.8.2",
  41294. "debug": "ngokevin/debug#noTimestamp",
  41295. "deep-assign": "^2.0.0",
  41296. "document-register-element": "dmarcos/document-register-element#8ccc532b7f3744be954574caf3072a5fd260ca90",
  41297. "envify": "^3.4.1",
  41298. "load-bmfont": "^1.2.3",
  41299. "object-assign": "^4.0.1",
  41300. "present": "0.0.6",
  41301. "promise-polyfill": "^3.1.0",
  41302. "style-attr": "^1.0.2",
  41303. "three": "0.95.0",
  41304. "three-bmfont-text": "^2.1.0",
  41305. "webvr-polyfill": "^0.10.5"
  41306. },
  41307. "devDependencies": {
  41308. "browserify": "^13.1.0",
  41309. "browserify-derequire": "^0.9.4",
  41310. "browserify-istanbul": "^2.0.0",
  41311. "budo": "^9.2.0",
  41312. "chai": "^3.5.0",
  41313. "chai-shallow-deep-equal": "^1.4.0",
  41314. "chalk": "^1.1.3",
  41315. "codecov": "^1.0.1",
  41316. "cross-env": "^5.0.1",
  41317. "exorcist": "^0.4.0",
  41318. "ghpages": "0.0.8",
  41319. "git-rev": "^0.2.1",
  41320. "glob": "^7.1.1",
  41321. "husky": "^0.11.7",
  41322. "istanbul": "^0.4.5",
  41323. "jsdom": "^9.11.0",
  41324. "karma": "1.4.1",
  41325. "karma-browserify": "^5.1.0",
  41326. "karma-chai-shallow-deep-equal": "0.0.4",
  41327. "karma-chrome-launcher": "^2.0.0",
  41328. "karma-coverage": "^1.1.1",
  41329. "karma-env-preprocessor": "^0.1.1",
  41330. "karma-firefox-launcher": "^1.0.0",
  41331. "karma-mocha": "^1.1.1",
  41332. "karma-mocha-reporter": "^2.1.0",
  41333. "karma-sinon-chai": "1.2.4",
  41334. "lolex": "^1.5.1",
  41335. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  41336. "minifyify": "^7.3.3",
  41337. "mocha": "^3.0.2",
  41338. "mozilla-download": "^1.1.1",
  41339. "replace-in-file": "^2.5.3",
  41340. "semistandard": "^9.0.0",
  41341. "shelljs": "^0.7.7",
  41342. "shx": "^0.2.2",
  41343. "sinon": "^1.17.5",
  41344. "sinon-chai": "2.8.0",
  41345. "snazzy": "^5.0.0",
  41346. "too-wordy": "ngokevin/too-wordy",
  41347. "uglifyjs": "^2.4.10",
  41348. "write-good": "^0.9.1"
  41349. },
  41350. "link": true,
  41351. "browserify": {
  41352. "transform": [
  41353. "browserify-css",
  41354. "envify"
  41355. ]
  41356. },
  41357. "semistandard": {
  41358. "ignore": [
  41359. "build/**",
  41360. "dist/**",
  41361. "examples/**/shaders/*.js",
  41362. "**/vendor/**"
  41363. ]
  41364. },
  41365. "keywords": [
  41366. "3d",
  41367. "aframe",
  41368. "cardboard",
  41369. "components",
  41370. "oculus",
  41371. "three",
  41372. "three.js",
  41373. "rift",
  41374. "vive",
  41375. "vr",
  41376. "web-components",
  41377. "webvr"
  41378. ],
  41379. "browserify-css": {
  41380. "minify": true
  41381. },
  41382. "engines": {
  41383. "node": ">= 4.6.0",
  41384. "npm": "^2.15.9"
  41385. }
  41386. }
  41387. },{}],52:[function(_dereq_,module,exports){
  41388. var anime = _dereq_('animejs');
  41389. var components = _dereq_('../core/component').components;
  41390. var registerComponent = _dereq_('../core/component').registerComponent;
  41391. var THREE = _dereq_('../lib/three');
  41392. var utils = _dereq_('../utils');
  41393. var colorHelperFrom = new THREE.Color();
  41394. var colorHelperTo = new THREE.Color();
  41395. var getComponentProperty = utils.entity.getComponentProperty;
  41396. var setComponentProperty = utils.entity.setComponentProperty;
  41397. var splitCache = {};
  41398. var TYPE_COLOR = 'color';
  41399. var PROP_POSITION = 'position';
  41400. var PROP_ROTATION = 'rotation';
  41401. var PROP_SCALE = 'scale';
  41402. var STRING_COMPONENTS = 'components';
  41403. var STRING_OBJECT3D = 'object3D';
  41404. /**
  41405. * Animation component for A-Frame using anime.js.
  41406. *
  41407. * The component manually controls the tick by setting `autoplay: false` on anime.js and
  41408. * manually * calling `animation.tick()` in the tick handler. To pause or resume, we toggle a
  41409. * boolean * flag * `isAnimationPlaying`.
  41410. *
  41411. * anime.js animation config for tweenining Javascript objects and values works as:
  41412. *
  41413. * config = {
  41414. * targets: {foo: 0.0, bar: '#000'},
  41415. * foo: 1.0,
  41416. * bar: '#FFF'
  41417. * }
  41418. *
  41419. * The above will tween each property in `targets`. The `to` values are set in the root of
  41420. * the config.
  41421. *
  41422. * @member {object} animation - anime.js instance.
  41423. * @member {boolean} animationIsPlaying - Control if animation is playing.
  41424. */
  41425. module.exports.Component = registerComponent('animation', {
  41426. schema: {
  41427. autoplay: {default: true},
  41428. delay: {default: 0},
  41429. dir: {default: ''},
  41430. dur: {default: 1000},
  41431. easing: {default: 'easeInQuad'},
  41432. elasticity: {default: 400},
  41433. enabled: {default: true},
  41434. from: {default: ''},
  41435. loop: {
  41436. default: 0,
  41437. parse: function (value) {
  41438. // Boolean or integer.
  41439. if (value === true || value === 'true') { return true; }
  41440. if (value === false || value === 'false') { return false; }
  41441. return parseInt(value, 10);
  41442. }
  41443. },
  41444. property: {default: ''},
  41445. startEvents: {type: 'array'},
  41446. pauseEvents: {type: 'array'},
  41447. resumeEvents: {type: 'array'},
  41448. round: {default: false},
  41449. to: {default: ''},
  41450. type: {default: ''},
  41451. isRawProperty: {default: false}
  41452. },
  41453. multiple: true,
  41454. init: function () {
  41455. var self = this;
  41456. this.eventDetail = {name: this.attrName};
  41457. this.time = 0;
  41458. this.animation = null;
  41459. this.animationIsPlaying = false;
  41460. this.onStartEvent = this.onStartEvent.bind(this);
  41461. this.beginAnimation = this.beginAnimation.bind(this);
  41462. this.pauseAnimation = this.pauseAnimation.bind(this);
  41463. this.resumeAnimation = this.resumeAnimation.bind(this);
  41464. this.fromColor = {};
  41465. this.toColor = {};
  41466. this.targets = {};
  41467. this.targetsArray = [];
  41468. this.updateConfigForDefault = this.updateConfigForDefault.bind(this);
  41469. this.updateConfigForRawColor = this.updateConfigForRawColor.bind(this);
  41470. this.config = {
  41471. complete: function () {
  41472. self.animationIsPlaying = false;
  41473. self.el.emit('animationcomplete', self.eventDetail, false);
  41474. if (self.id) {
  41475. self.el.emit('animationcomplete__' + self.id, self.eventDetail, false);
  41476. }
  41477. }
  41478. };
  41479. },
  41480. update: function (oldData) {
  41481. var config = this.config;
  41482. var data = this.data;
  41483. this.animationIsPlaying = false;
  41484. if (oldData.enabled && !this.data.enabled) { return; }
  41485. if (!data.property) { return; }
  41486. // Base config.
  41487. config.autoplay = false;
  41488. config.direction = data.dir;
  41489. config.duration = data.dur;
  41490. config.easing = data.easing;
  41491. config.elasticity = data.elasticity;
  41492. config.loop = data.loop;
  41493. config.round = data.round;
  41494. // Start new animation.
  41495. this.createAndStartAnimation();
  41496. },
  41497. tick: function (t, dt) {
  41498. if (!this.animationIsPlaying) { return; }
  41499. this.time += dt;
  41500. this.animation.tick(this.time);
  41501. },
  41502. remove: function () {
  41503. this.pauseAnimation();
  41504. this.removeEventListeners();
  41505. },
  41506. pause: function () {
  41507. this.paused = true;
  41508. this.pausedWasPlaying = true;
  41509. this.pauseAnimation();
  41510. this.removeEventListeners();
  41511. },
  41512. /**
  41513. * `play` handler only for resuming scene.
  41514. */
  41515. play: function () {
  41516. if (!this.paused) { return; }
  41517. this.paused = false;
  41518. this.addEventListeners();
  41519. if (this.pausedWasPlaying) {
  41520. this.resumeAnimation();
  41521. this.pausedWasPlaying = false;
  41522. }
  41523. },
  41524. /**
  41525. * Start animation from scratch.
  41526. */
  41527. createAndStartAnimation: function () {
  41528. var data = this.data;
  41529. this.updateConfig();
  41530. this.animationIsPlaying = false;
  41531. this.animation = anime(this.config);
  41532. this.removeEventListeners();
  41533. this.addEventListeners();
  41534. // Wait for start events for animation.
  41535. if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
  41536. // Delay animation.
  41537. if (data.delay) {
  41538. setTimeout(this.beginAnimation, data.delay);
  41539. return;
  41540. }
  41541. // Play animation.
  41542. this.beginAnimation();
  41543. },
  41544. /**
  41545. * This is before animation start (including from startEvents).
  41546. * Set to initial state (config.from, time = 0, seekTime = 0).
  41547. */
  41548. beginAnimation: function () {
  41549. this.updateConfig();
  41550. this.time = 0;
  41551. this.animationIsPlaying = true;
  41552. this.stopRelatedAnimations();
  41553. this.el.emit('animationbegin', this.eventDetail);
  41554. },
  41555. pauseAnimation: function () {
  41556. this.animationIsPlaying = false;
  41557. },
  41558. resumeAnimation: function () {
  41559. this.animationIsPlaying = true;
  41560. },
  41561. /**
  41562. * startEvents callback.
  41563. */
  41564. onStartEvent: function () {
  41565. if (!this.data.enabled) { return; }
  41566. this.updateConfig();
  41567. if (this.animation) {
  41568. this.animation.pause();
  41569. }
  41570. this.animation = anime(this.config);
  41571. // Include the delay before each start event.
  41572. if (this.data.delay) {
  41573. setTimeout(this.beginAnimation, this.data.delay);
  41574. return;
  41575. }
  41576. this.beginAnimation();
  41577. },
  41578. /**
  41579. * rawProperty: true and type: color;
  41580. */
  41581. updateConfigForRawColor: function () {
  41582. var config = this.config;
  41583. var data = this.data;
  41584. var el = this.el;
  41585. var from;
  41586. var key;
  41587. var to;
  41588. if (this.waitComponentInitRawProperty(this.updateConfigForRawColor)) {
  41589. return;
  41590. }
  41591. from = data.from === '' ? getRawProperty(el, data.property) : data.from;
  41592. to = data.to;
  41593. // Use r/g/b vector for color type.
  41594. this.setColorConfig(from, to);
  41595. from = this.fromColor;
  41596. to = this.toColor;
  41597. this.targetsArray.length = 0;
  41598. this.targetsArray.push(from);
  41599. config.targets = this.targetsArray;
  41600. for (key in to) { config[key] = to[key]; }
  41601. config.update = (function () {
  41602. var lastValue = {};
  41603. return function (anim) {
  41604. var value;
  41605. value = anim.animatables[0].target;
  41606. // For animation timeline.
  41607. if (value.r === lastValue.r &&
  41608. value.g === lastValue.g &&
  41609. value.b === lastValue.b) { return; }
  41610. setRawProperty(el, data.property, value, data.type);
  41611. };
  41612. })();
  41613. },
  41614. /**
  41615. * Stuff property into generic `property` key.
  41616. */
  41617. updateConfigForDefault: function () {
  41618. var config = this.config;
  41619. var data = this.data;
  41620. var el = this.el;
  41621. var from;
  41622. var isBoolean;
  41623. var isNumber;
  41624. var to;
  41625. if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
  41626. return;
  41627. }
  41628. if (data.from === '') {
  41629. // Infer from.
  41630. from = isRawProperty(data)
  41631. ? getRawProperty(el, data.property)
  41632. : getComponentProperty(el, data.property);
  41633. } else {
  41634. // Explicit from.
  41635. from = data.from;
  41636. }
  41637. to = data.to;
  41638. isNumber = !isNaN(from || to);
  41639. if (isNumber) {
  41640. from = parseFloat(from);
  41641. to = parseFloat(to);
  41642. } else {
  41643. from = from ? from.toString() : from;
  41644. to = to ? to.toString() : to;
  41645. }
  41646. // Convert booleans to integer to allow boolean flipping.
  41647. isBoolean = data.to === 'true' || data.to === 'false' ||
  41648. data.to === true || data.to === false;
  41649. if (isBoolean) {
  41650. from = data.from === 'true' || data.from === true ? 1 : 0;
  41651. to = data.to === 'true' || data.to === true ? 1 : 0;
  41652. }
  41653. this.targets.aframeProperty = from;
  41654. config.targets = this.targets;
  41655. config.aframeProperty = to;
  41656. config.update = (function () {
  41657. var lastValue;
  41658. return function (anim) {
  41659. var value;
  41660. value = anim.animatables[0].target.aframeProperty;
  41661. // Need to do a last value check for animation timeline since all the tweening
  41662. // begins simultaenously even if the value has not changed. Also better for perf
  41663. // anyways.
  41664. if (value === lastValue) { return; }
  41665. lastValue = value;
  41666. if (isBoolean) { value = value >= 1; }
  41667. if (isRawProperty(data)) {
  41668. setRawProperty(el, data.property, value, data.type);
  41669. } else {
  41670. setComponentProperty(el, data.property, value);
  41671. }
  41672. };
  41673. })();
  41674. },
  41675. /**
  41676. * Extend x/y/z/w onto the config.
  41677. * Update vector by modifying object3D.
  41678. */
  41679. updateConfigForVector: function () {
  41680. var config = this.config;
  41681. var data = this.data;
  41682. var el = this.el;
  41683. var key;
  41684. var from;
  41685. var to;
  41686. // Parse coordinates.
  41687. from = data.from !== ''
  41688. ? utils.coordinates.parse(data.from) // If data.from defined, use that.
  41689. : getComponentProperty(el, data.property); // If data.from not defined, get on the fly.
  41690. to = utils.coordinates.parse(data.to);
  41691. if (data.property === PROP_ROTATION) {
  41692. toRadians(from);
  41693. toRadians(to);
  41694. }
  41695. // Set to and from.
  41696. this.targetsArray.length = 0;
  41697. this.targetsArray.push(from);
  41698. config.targets = this.targetsArray;
  41699. for (key in to) { config[key] = to[key]; }
  41700. // If animating object3D transformation, run more optimized updater.
  41701. if (data.property === PROP_POSITION || data.property === PROP_ROTATION ||
  41702. data.property === PROP_SCALE) {
  41703. config.update = (function () {
  41704. var lastValue = {};
  41705. return function (anim) {
  41706. var value = anim.animatables[0].target;
  41707. if (data.property === PROP_SCALE) {
  41708. value.x = Math.max(0.0001, value.x);
  41709. value.y = Math.max(0.0001, value.y);
  41710. value.z = Math.max(0.0001, value.z);
  41711. }
  41712. // For animation timeline.
  41713. if (value.x === lastValue.x &&
  41714. value.y === lastValue.y &&
  41715. value.z === lastValue.z) { return; }
  41716. lastValue.x = value.x;
  41717. lastValue.y = value.y;
  41718. lastValue.z = value.z;
  41719. el.object3D[data.property].set(value.x, value.y, value.z);
  41720. };
  41721. })();
  41722. return;
  41723. }
  41724. // Animating some vector.
  41725. config.update = (function () {
  41726. var lastValue = {};
  41727. return function (anim) {
  41728. var value = anim.animations[0].target;
  41729. // Animate rotation through radians.
  41730. // For animation timeline.
  41731. if (value.x === lastValue.x &&
  41732. value.y === lastValue.y &&
  41733. value.z === lastValue.z) { return; }
  41734. lastValue.x = value.x;
  41735. lastValue.y = value.y;
  41736. lastValue.z = value.z;
  41737. setComponentProperty(el, data.property, value);
  41738. };
  41739. })();
  41740. },
  41741. /**
  41742. * Update the config before each run.
  41743. */
  41744. updateConfig: function () {
  41745. var propType;
  41746. // Route config type.
  41747. propType = getPropertyType(this.el, this.data.property);
  41748. if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
  41749. this.updateConfigForRawColor();
  41750. } else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
  41751. this.updateConfigForVector();
  41752. } else {
  41753. this.updateConfigForDefault();
  41754. }
  41755. },
  41756. /**
  41757. * Wait for component to initialize.
  41758. */
  41759. waitComponentInitRawProperty: function (cb) {
  41760. var componentName;
  41761. var data = this.data;
  41762. var el = this.el;
  41763. var self = this;
  41764. if (data.from !== '') { return false; }
  41765. if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
  41766. componentName = splitDot(data.property)[1];
  41767. if (el.components[componentName]) { return false; }
  41768. el.addEventListener('componentinitialized', function wait (evt) {
  41769. if (evt.detail.name !== componentName) { return; }
  41770. cb();
  41771. // Since the config was created async, create the animation now since we missed it
  41772. // earlier.
  41773. self.animation = anime(self.config);
  41774. el.removeEventListener('componentinitialized', wait);
  41775. });
  41776. return true;
  41777. },
  41778. /**
  41779. * Make sure two animations on the same property don't fight each other.
  41780. * e.g., animation__mouseenter="property: material.opacity"
  41781. * animation__mouseleave="property: material.opacity"
  41782. */
  41783. stopRelatedAnimations: function () {
  41784. var component;
  41785. var componentName;
  41786. for (componentName in this.el.components) {
  41787. component = this.el.components[componentName];
  41788. if (componentName === this.attrName) { continue; }
  41789. if (component.name !== 'animation') { continue; }
  41790. if (!component.animationIsPlaying) { continue; }
  41791. if (component.data.property !== this.data.property) { continue; }
  41792. component.animationIsPlaying = false;
  41793. }
  41794. },
  41795. addEventListeners: function () {
  41796. var data = this.data;
  41797. var el = this.el;
  41798. addEventListeners(el, data.startEvents, this.onStartEvent);
  41799. addEventListeners(el, data.pauseEvents, this.pauseAnimation);
  41800. addEventListeners(el, data.resumeEvents, this.resumeAnimation);
  41801. },
  41802. removeEventListeners: function () {
  41803. var data = this.data;
  41804. var el = this.el;
  41805. removeEventListeners(el, data.startEvents, this.onStartEvent);
  41806. removeEventListeners(el, data.pauseEvents, this.pauseAnimation);
  41807. removeEventListeners(el, data.resumeEvents, this.resumeAnimation);
  41808. },
  41809. setColorConfig: function (from, to) {
  41810. colorHelperFrom.set(from);
  41811. colorHelperTo.set(to);
  41812. from = this.fromColor;
  41813. to = this.toColor;
  41814. from.r = colorHelperFrom.r;
  41815. from.g = colorHelperFrom.g;
  41816. from.b = colorHelperFrom.b;
  41817. to.r = colorHelperTo.r;
  41818. to.g = colorHelperTo.g;
  41819. to.b = colorHelperTo.b;
  41820. }
  41821. });
  41822. /**
  41823. * Given property name, check schema to see what type we are animating.
  41824. * We just care whether the property is a vector.
  41825. */
  41826. function getPropertyType (el, property) {
  41827. var component;
  41828. var componentName;
  41829. var split;
  41830. var propertyName;
  41831. split = property.split('.');
  41832. componentName = split[0];
  41833. propertyName = split[1];
  41834. component = el.components[componentName] || components[componentName];
  41835. // Primitives.
  41836. if (!component) { return null; }
  41837. // Dynamic schema. We only care about vectors anyways.
  41838. if (propertyName && !component.schema[propertyName]) { return null; }
  41839. // Multi-prop.
  41840. if (propertyName) { return component.schema[propertyName].type; }
  41841. // Single-prop.
  41842. return component.schema.type;
  41843. }
  41844. /**
  41845. * Convert object to radians.
  41846. */
  41847. function toRadians (obj) {
  41848. obj.x = THREE.Math.degToRad(obj.x);
  41849. obj.y = THREE.Math.degToRad(obj.y);
  41850. obj.z = THREE.Math.degToRad(obj.z);
  41851. }
  41852. function addEventListeners (el, eventNames, handler) {
  41853. var i;
  41854. for (i = 0; i < eventNames.length; i++) {
  41855. el.addEventListener(eventNames[i], handler);
  41856. }
  41857. }
  41858. function removeEventListeners (el, eventNames, handler) {
  41859. var i;
  41860. for (i = 0; i < eventNames.length; i++) {
  41861. el.removeEventListener(eventNames[i], handler);
  41862. }
  41863. }
  41864. function getRawProperty (el, path) {
  41865. var i;
  41866. var split;
  41867. var value;
  41868. split = splitDot(path);
  41869. value = el;
  41870. for (i = 0; i < split.length; i++) {
  41871. value = value[split[i]];
  41872. }
  41873. return value;
  41874. }
  41875. function setRawProperty (el, path, value, type) {
  41876. var i;
  41877. var split;
  41878. var propertyName;
  41879. var targetValue;
  41880. if (path.startsWith('object3D.rotation')) {
  41881. value = THREE.Math.degToRad(value);
  41882. }
  41883. // Walk.
  41884. split = splitDot(path);
  41885. targetValue = el;
  41886. for (i = 0; i < split.length - 1; i++) { targetValue = targetValue[split[i]]; }
  41887. propertyName = split[split.length - 1];
  41888. // Raw color.
  41889. if (type === TYPE_COLOR) {
  41890. if ('r' in targetValue[propertyName]) {
  41891. targetValue[propertyName].r = value.r;
  41892. targetValue[propertyName].g = value.g;
  41893. targetValue[propertyName].b = value.b;
  41894. } else {
  41895. targetValue[propertyName].x = value.r;
  41896. targetValue[propertyName].y = value.g;
  41897. targetValue[propertyName].z = value.b;
  41898. }
  41899. return;
  41900. }
  41901. targetValue[propertyName] = value;
  41902. }
  41903. function splitDot (path) {
  41904. if (path in splitCache) { return splitCache[path]; }
  41905. splitCache[path] = path.split('.');
  41906. return splitCache[path];
  41907. }
  41908. function isRawProperty (data) {
  41909. return data.isRawProperty || data.property.startsWith(STRING_COMPONENTS) ||
  41910. data.property.startsWith(STRING_OBJECT3D);
  41911. }
  41912. },{"../core/component":102,"../lib/three":150,"../utils":172,"animejs":2}],53:[function(_dereq_,module,exports){
  41913. var registerComponent = _dereq_('../core/component').registerComponent;
  41914. var THREE = _dereq_('../lib/three');
  41915. /**
  41916. * Camera component.
  41917. * Pairs along with camera system to handle tracking the active camera.
  41918. */
  41919. module.exports.Component = registerComponent('camera', {
  41920. schema: {
  41921. active: {default: true},
  41922. far: {default: 10000},
  41923. fov: {default: 80, min: 0},
  41924. near: {default: 0.005, min: 0},
  41925. spectator: {default: false},
  41926. zoom: {default: 1, min: 0}
  41927. },
  41928. /**
  41929. * Initialize three.js camera and add it to the entity.
  41930. * Add reference from scene to this entity as the camera.
  41931. */
  41932. init: function () {
  41933. var camera;
  41934. var el = this.el;
  41935. // Create camera.
  41936. camera = this.camera = new THREE.PerspectiveCamera();
  41937. el.setObject3D('camera', camera);
  41938. },
  41939. /**
  41940. * Update three.js camera.
  41941. */
  41942. update: function (oldData) {
  41943. var data = this.data;
  41944. var camera = this.camera;
  41945. // Update properties.
  41946. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  41947. camera.far = data.far;
  41948. camera.fov = data.fov;
  41949. camera.near = data.near;
  41950. camera.zoom = data.zoom;
  41951. camera.updateProjectionMatrix();
  41952. this.updateActiveCamera(oldData);
  41953. this.updateSpectatorCamera(oldData);
  41954. },
  41955. updateActiveCamera: function (oldData) {
  41956. var data = this.data;
  41957. var el = this.el;
  41958. var system = this.system;
  41959. // Active property did not change.
  41960. if (oldData && oldData.active === data.active || data.spectator) { return; }
  41961. // If `active` property changes, or first update, handle active camera with system.
  41962. if (data.active && system.activeCameraEl !== el) {
  41963. // Camera enabled. Set camera to this camera.
  41964. system.setActiveCamera(el);
  41965. } else if (!data.active && system.activeCameraEl === el) {
  41966. // Camera disabled. Set camera to another camera.
  41967. system.disableActiveCamera();
  41968. }
  41969. },
  41970. updateSpectatorCamera: function (oldData) {
  41971. var data = this.data;
  41972. var el = this.el;
  41973. var system = this.system;
  41974. // spectator property did not change.
  41975. if (oldData && oldData.spectator === data.spectator) { return; }
  41976. // If `spectator` property changes, or first update, handle spectator camera with system.
  41977. if (data.spectator && system.spectatorCameraEl !== el) {
  41978. // Camera enabled. Set camera to this camera.
  41979. system.setSpectatorCamera(el);
  41980. } else if (!data.spectator && system.spectatorCameraEl === el) {
  41981. // Camera disabled. Set camera to another camera.
  41982. system.disableSpectatorCamera();
  41983. }
  41984. },
  41985. /**
  41986. * Remove camera on remove (callback).
  41987. */
  41988. remove: function () {
  41989. this.el.removeObject3D('camera');
  41990. }
  41991. });
  41992. },{"../core/component":102,"../lib/three":150}],54:[function(_dereq_,module,exports){
  41993. var registerComponent = _dereq_('../core/component').registerComponent;
  41994. var THREE = _dereq_('../lib/three');
  41995. module.exports.Component = registerComponent('collada-model', {
  41996. schema: {type: 'asset'},
  41997. init: function () {
  41998. this.model = null;
  41999. this.loader = new THREE.ColladaLoader();
  42000. },
  42001. update: function () {
  42002. var self = this;
  42003. var el = this.el;
  42004. var src = this.data;
  42005. if (!src) { return; }
  42006. this.remove();
  42007. this.loader.load(src, function (colladaModel) {
  42008. self.model = colladaModel.scene;
  42009. el.setObject3D('mesh', self.model);
  42010. el.emit('model-loaded', {format: 'collada', model: self.model});
  42011. });
  42012. },
  42013. remove: function () {
  42014. if (!this.model) { return; }
  42015. this.el.removeObject3D('mesh');
  42016. }
  42017. });
  42018. },{"../core/component":102,"../lib/three":150}],55:[function(_dereq_,module,exports){
  42019. /* global THREE */
  42020. var registerComponent = _dereq_('../core/component').registerComponent;
  42021. var utils = _dereq_('../utils/');
  42022. var bind = utils.bind;
  42023. var EVENTS = {
  42024. CLICK: 'click',
  42025. FUSING: 'fusing',
  42026. MOUSEENTER: 'mouseenter',
  42027. MOUSEDOWN: 'mousedown',
  42028. MOUSELEAVE: 'mouseleave',
  42029. MOUSEUP: 'mouseup'
  42030. };
  42031. var STATES = {
  42032. FUSING: 'cursor-fusing',
  42033. HOVERING: 'cursor-hovering',
  42034. HOVERED: 'cursor-hovered'
  42035. };
  42036. var CANVAS_EVENTS = {
  42037. DOWN: ['mousedown', 'touchstart'],
  42038. UP: ['mouseup', 'touchend']
  42039. };
  42040. /**
  42041. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  42042. * from the camera and pointing from camera's facing direction, and then only returning the
  42043. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  42044. *
  42045. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  42046. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  42047. * @member {object} intersection - Attributes of the current intersection event, including
  42048. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  42049. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  42050. * emit events when unintersecting.
  42051. */
  42052. module.exports.Component = registerComponent('cursor', {
  42053. dependencies: ['raycaster'],
  42054. schema: {
  42055. downEvents: {default: []},
  42056. fuse: {default: utils.device.isMobile()},
  42057. fuseTimeout: {default: 1500, min: 0},
  42058. upEvents: {default: []},
  42059. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  42060. },
  42061. init: function () {
  42062. var self = this;
  42063. this.fuseTimeout = undefined;
  42064. this.cursorDownEl = null;
  42065. this.intersectedEl = null;
  42066. this.canvasBounds = document.body.getBoundingClientRect();
  42067. // Debounce.
  42068. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  42069. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  42070. }, 500);
  42071. this.eventDetail = {};
  42072. this.intersectedEventDetail = {cursorEl: this.el};
  42073. // Bind methods.
  42074. this.onCursorDown = bind(this.onCursorDown, this);
  42075. this.onCursorUp = bind(this.onCursorUp, this);
  42076. this.onIntersection = bind(this.onIntersection, this);
  42077. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  42078. this.onMouseMove = bind(this.onMouseMove, this);
  42079. },
  42080. update: function (oldData) {
  42081. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  42082. this.updateMouseEventListeners();
  42083. },
  42084. play: function () {
  42085. this.addEventListeners();
  42086. },
  42087. pause: function () {
  42088. this.removeEventListeners();
  42089. },
  42090. remove: function () {
  42091. var el = this.el;
  42092. el.removeState(STATES.HOVERING);
  42093. el.removeState(STATES.FUSING);
  42094. clearTimeout(this.fuseTimeout);
  42095. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  42096. this.removeEventListeners();
  42097. },
  42098. addEventListeners: function () {
  42099. var canvas;
  42100. var data = this.data;
  42101. var el = this.el;
  42102. var self = this;
  42103. function addCanvasListeners () {
  42104. canvas = el.sceneEl.canvas;
  42105. if (data.downEvents.length || data.upEvents.length) { return; }
  42106. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  42107. canvas.addEventListener(downEvent, self.onCursorDown);
  42108. });
  42109. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  42110. canvas.addEventListener(upEvent, self.onCursorUp);
  42111. });
  42112. }
  42113. canvas = el.sceneEl.canvas;
  42114. if (canvas) {
  42115. addCanvasListeners();
  42116. } else {
  42117. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  42118. }
  42119. data.downEvents.forEach(function (downEvent) {
  42120. el.addEventListener(downEvent, self.onCursorDown);
  42121. });
  42122. data.upEvents.forEach(function (upEvent) {
  42123. el.addEventListener(upEvent, self.onCursorUp);
  42124. });
  42125. el.addEventListener('raycaster-intersection', this.onIntersection);
  42126. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  42127. el.sceneEl.addEventListener('rendererresize', this.updateCanvasBounds);
  42128. window.addEventListener('resize', this.updateCanvasBounds);
  42129. window.addEventListener('scroll', this.updateCanvasBounds);
  42130. },
  42131. removeEventListeners: function () {
  42132. var canvas;
  42133. var data = this.data;
  42134. var el = this.el;
  42135. var self = this;
  42136. canvas = el.sceneEl.canvas;
  42137. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  42138. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  42139. canvas.removeEventListener(downEvent, self.onCursorDown);
  42140. });
  42141. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  42142. canvas.removeEventListener(upEvent, self.onCursorUp);
  42143. });
  42144. }
  42145. data.downEvents.forEach(function (downEvent) {
  42146. el.removeEventListener(downEvent, self.onCursorDown);
  42147. });
  42148. data.upEvents.forEach(function (upEvent) {
  42149. el.removeEventListener(upEvent, self.onCursorUp);
  42150. });
  42151. el.removeEventListener('raycaster-intersection', this.onIntersection);
  42152. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  42153. canvas.removeEventListener('mousemove', this.onMouseMove);
  42154. canvas.removeEventListener('touchstart', this.onMouseMove);
  42155. canvas.removeEventListener('touchmove', this.onMouseMove);
  42156. el.sceneEl.removeEventListener('rendererresize', this.updateCanvasBounds);
  42157. window.removeEventListener('resize', this.updateCanvasBounds);
  42158. window.removeEventListener('scroll', this.updateCanvasBounds);
  42159. },
  42160. updateMouseEventListeners: function () {
  42161. var canvas;
  42162. var el = this.el;
  42163. canvas = el.sceneEl.canvas;
  42164. canvas.removeEventListener('mousemove', this.onMouseMove);
  42165. canvas.removeEventListener('touchmove', this.onMouseMove);
  42166. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  42167. if (this.data.rayOrigin !== 'mouse') { return; }
  42168. canvas.addEventListener('mousemove', this.onMouseMove, false);
  42169. canvas.addEventListener('touchmove', this.onMouseMove, false);
  42170. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  42171. this.updateCanvasBounds();
  42172. },
  42173. onMouseMove: (function () {
  42174. var direction = new THREE.Vector3();
  42175. var mouse = new THREE.Vector2();
  42176. var origin = new THREE.Vector3();
  42177. var rayCasterConfig = {origin: origin, direction: direction};
  42178. return function (evt) {
  42179. var bounds = this.canvasBounds;
  42180. var camera = this.el.sceneEl.camera;
  42181. var left;
  42182. var point;
  42183. var top;
  42184. camera.parent.updateMatrixWorld();
  42185. // Calculate mouse position based on the canvas element
  42186. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  42187. // Track the first touch for simplicity.
  42188. point = evt.touches.item(0);
  42189. } else {
  42190. point = evt;
  42191. }
  42192. left = point.clientX - bounds.left;
  42193. top = point.clientY - bounds.top;
  42194. mouse.x = (left / bounds.width) * 2 - 1;
  42195. mouse.y = -(top / bounds.height) * 2 + 1;
  42196. origin.setFromMatrixPosition(camera.matrixWorld);
  42197. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  42198. this.el.setAttribute('raycaster', rayCasterConfig);
  42199. if (evt.type === 'touchmove') { evt.preventDefault(); }
  42200. };
  42201. })(),
  42202. /**
  42203. * Trigger mousedown and keep track of the mousedowned entity.
  42204. */
  42205. onCursorDown: function (evt) {
  42206. // Raycast again for touch.
  42207. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  42208. this.onMouseMove(evt);
  42209. this.el.components.raycaster.checkIntersections();
  42210. evt.preventDefault();
  42211. }
  42212. this.twoWayEmit(EVENTS.MOUSEDOWN);
  42213. this.cursorDownEl = this.intersectedEl;
  42214. },
  42215. /**
  42216. * Trigger mouseup if:
  42217. * - Not fusing (mobile has no mouse).
  42218. * - Currently intersecting an entity.
  42219. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  42220. * in case user mousedowned one entity, dragged to another, and mouseupped.
  42221. */
  42222. onCursorUp: function (evt) {
  42223. this.twoWayEmit(EVENTS.MOUSEUP);
  42224. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  42225. // previously cursorUp entity.
  42226. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  42227. this.intersectedEventDetail.intersection = null;
  42228. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  42229. }
  42230. if (!this.data.fuse && this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  42231. this.twoWayEmit(EVENTS.CLICK);
  42232. }
  42233. this.cursorDownEl = null;
  42234. if (evt.type === 'touchend') { evt.preventDefault(); }
  42235. },
  42236. /**
  42237. * Handle intersection.
  42238. */
  42239. onIntersection: function (evt) {
  42240. var currentIntersection;
  42241. var cursorEl = this.el;
  42242. var index;
  42243. var intersectedEl;
  42244. var intersection;
  42245. // Select closest object, excluding the cursor.
  42246. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  42247. intersection = evt.detail.intersections[index];
  42248. intersectedEl = evt.detail.els[index];
  42249. // If cursor is the only intersected object, ignore the event.
  42250. if (!intersectedEl) { return; }
  42251. // Already intersecting this entity.
  42252. if (this.intersectedEl === intersectedEl) { return; }
  42253. // Ignore events further away than active intersection.
  42254. if (this.intersectedEl) {
  42255. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  42256. if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; }
  42257. }
  42258. // Unset current intersection.
  42259. this.clearCurrentIntersection(true);
  42260. this.setIntersection(intersectedEl, intersection);
  42261. },
  42262. /**
  42263. * Handle intersection cleared.
  42264. */
  42265. onIntersectionCleared: function (evt) {
  42266. var clearedEls = evt.detail.clearedEls;
  42267. // Check if the current intersection has ended
  42268. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  42269. this.clearCurrentIntersection();
  42270. },
  42271. setIntersection: function (intersectedEl, intersection) {
  42272. var cursorEl = this.el;
  42273. var data = this.data;
  42274. var self = this;
  42275. // Already intersecting.
  42276. if (this.intersectedEl === intersectedEl) { return; }
  42277. // Set new intersection.
  42278. this.intersectedEl = intersectedEl;
  42279. // Hovering.
  42280. cursorEl.addState(STATES.HOVERING);
  42281. intersectedEl.addState(STATES.HOVERED);
  42282. this.twoWayEmit(EVENTS.MOUSEENTER);
  42283. // Begin fuse if necessary.
  42284. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  42285. cursorEl.addState(STATES.FUSING);
  42286. this.twoWayEmit(EVENTS.FUSING);
  42287. this.fuseTimeout = setTimeout(function fuse () {
  42288. cursorEl.removeState(STATES.FUSING);
  42289. self.twoWayEmit(EVENTS.CLICK);
  42290. }, data.fuseTimeout);
  42291. },
  42292. clearCurrentIntersection: function (ignoreRemaining) {
  42293. var index;
  42294. var intersection;
  42295. var intersections;
  42296. var cursorEl = this.el;
  42297. // Nothing to be cleared.
  42298. if (!this.intersectedEl) { return; }
  42299. // No longer hovering (or fusing).
  42300. this.intersectedEl.removeState(STATES.HOVERED);
  42301. cursorEl.removeState(STATES.HOVERING);
  42302. cursorEl.removeState(STATES.FUSING);
  42303. this.twoWayEmit(EVENTS.MOUSELEAVE);
  42304. // Unset intersected entity (after emitting the event).
  42305. this.intersectedEl = null;
  42306. // Clear fuseTimeout.
  42307. clearTimeout(this.fuseTimeout);
  42308. // Set intersection to another raycasted element if any.
  42309. if (ignoreRemaining === true) { return; }
  42310. intersections = this.el.components.raycaster.intersections;
  42311. if (intersections.length === 0) { return; }
  42312. // Exclude the cursor.
  42313. index = intersections[0].object.el === cursorEl ? 1 : 0;
  42314. intersection = intersections[index];
  42315. if (!intersection) { return; }
  42316. this.setIntersection(intersection.object.el, intersection);
  42317. },
  42318. /**
  42319. * Helper to emit on both the cursor and the intersected entity (if exists).
  42320. */
  42321. twoWayEmit: function (evtName) {
  42322. var el = this.el;
  42323. var intersectedEl = this.intersectedEl;
  42324. var intersection;
  42325. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  42326. this.eventDetail.intersectedEl = intersectedEl;
  42327. this.eventDetail.intersection = intersection;
  42328. el.emit(evtName, this.eventDetail);
  42329. if (!intersectedEl) { return; }
  42330. this.intersectedEventDetail.intersection = intersection;
  42331. intersectedEl.emit(evtName, this.intersectedEventDetail);
  42332. }
  42333. });
  42334. },{"../core/component":102,"../utils/":172}],56:[function(_dereq_,module,exports){
  42335. var registerComponent = _dereq_('../core/component').registerComponent;
  42336. var bind = _dereq_('../utils/bind');
  42337. var checkControllerPresentAndSetup = _dereq_('../utils/tracked-controls').checkControllerPresentAndSetup;
  42338. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  42339. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  42340. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  42341. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  42342. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  42343. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  42344. var GAMEPAD_ID_PREFIX = 'Daydream Controller';
  42345. /**
  42346. * Daydream controls.
  42347. * Interface with Daydream controller and map Gamepad events to
  42348. * controller buttons: trackpad, menu, system
  42349. * Load a controller model and highlight the pressed buttons.
  42350. */
  42351. module.exports.Component = registerComponent('daydream-controls', {
  42352. schema: {
  42353. hand: {default: ''}, // This informs the degenerate arm model.
  42354. buttonColor: {type: 'color', default: '#000000'},
  42355. buttonTouchedColor: {type: 'color', default: '#777777'},
  42356. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  42357. model: {default: true},
  42358. orientationOffset: {type: 'vec3'},
  42359. armModel: {default: true}
  42360. },
  42361. /**
  42362. * Button IDs:
  42363. * 0 - trackpad
  42364. * 1 - menu (never dispatched on this layer)
  42365. * 2 - system (never dispatched on this layer)
  42366. */
  42367. mapping: {
  42368. axes: {trackpad: [0, 1]},
  42369. buttons: ['trackpad', 'menu', 'system']
  42370. },
  42371. bindMethods: function () {
  42372. this.onModelLoaded = bind(this.onModelLoaded, this);
  42373. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  42374. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  42375. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  42376. this.onAxisMoved = bind(this.onAxisMoved, this);
  42377. },
  42378. init: function () {
  42379. var self = this;
  42380. this.animationActive = 'pointing';
  42381. this.onButtonChanged = bind(this.onButtonChanged, this);
  42382. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  42383. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  42384. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  42385. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  42386. this.onAxisMoved = bind(this.onAxisMoved, this);
  42387. this.controllerPresent = false;
  42388. this.lastControllerCheck = 0;
  42389. this.bindMethods();
  42390. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  42391. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  42392. },
  42393. addEventListeners: function () {
  42394. var el = this.el;
  42395. el.addEventListener('buttonchanged', this.onButtonChanged);
  42396. el.addEventListener('buttondown', this.onButtonDown);
  42397. el.addEventListener('buttonup', this.onButtonUp);
  42398. el.addEventListener('touchstart', this.onButtonTouchStart);
  42399. el.addEventListener('touchend', this.onButtonTouchEnd);
  42400. el.addEventListener('model-loaded', this.onModelLoaded);
  42401. el.addEventListener('axismove', this.onAxisMoved);
  42402. this.controllerEventsActive = true;
  42403. },
  42404. removeEventListeners: function () {
  42405. var el = this.el;
  42406. el.removeEventListener('buttonchanged', this.onButtonChanged);
  42407. el.removeEventListener('buttondown', this.onButtonDown);
  42408. el.removeEventListener('buttonup', this.onButtonUp);
  42409. el.removeEventListener('touchstart', this.onButtonTouchStart);
  42410. el.removeEventListener('touchend', this.onButtonTouchEnd);
  42411. el.removeEventListener('model-loaded', this.onModelLoaded);
  42412. el.removeEventListener('axismove', this.onAxisMoved);
  42413. this.controllerEventsActive = false;
  42414. },
  42415. checkIfControllerPresent: function () {
  42416. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {hand: this.data.hand});
  42417. },
  42418. play: function () {
  42419. this.checkIfControllerPresent();
  42420. this.addControllersUpdateListener();
  42421. },
  42422. pause: function () {
  42423. this.removeEventListeners();
  42424. this.removeControllersUpdateListener();
  42425. },
  42426. injectTrackedControls: function () {
  42427. var el = this.el;
  42428. var data = this.data;
  42429. el.setAttribute('tracked-controls', {
  42430. armModel: data.armModel,
  42431. hand: data.hand,
  42432. idPrefix: GAMEPAD_ID_PREFIX,
  42433. orientationOffset: data.orientationOffset
  42434. });
  42435. if (!this.data.model) { return; }
  42436. this.el.setAttribute('obj-model', {
  42437. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  42438. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  42439. });
  42440. },
  42441. addControllersUpdateListener: function () {
  42442. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  42443. },
  42444. removeControllersUpdateListener: function () {
  42445. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  42446. },
  42447. onControllersUpdate: function () {
  42448. this.checkIfControllerPresent();
  42449. },
  42450. onModelLoaded: function (evt) {
  42451. var controllerObject3D = evt.detail.model;
  42452. var buttonMeshes;
  42453. if (!this.data.model) { return; }
  42454. buttonMeshes = this.buttonMeshes = {};
  42455. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  42456. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  42457. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  42458. // Offset pivot point.
  42459. controllerObject3D.position.set(0, 0, -0.04);
  42460. },
  42461. onAxisMoved: function (evt) {
  42462. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  42463. },
  42464. onButtonChanged: function (evt) {
  42465. var button = this.mapping.buttons[evt.detail.id];
  42466. if (!button) return;
  42467. // Pass along changed event with button state, using button mapping for convenience.
  42468. this.el.emit(button + 'changed', evt.detail.state);
  42469. },
  42470. updateModel: function (buttonName, evtName) {
  42471. if (!this.data.model) { return; }
  42472. this.updateButtonModel(buttonName, evtName);
  42473. },
  42474. updateButtonModel: function (buttonName, state) {
  42475. var buttonMeshes = this.buttonMeshes;
  42476. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  42477. var color;
  42478. switch (state) {
  42479. case 'down':
  42480. color = this.data.buttonHighlightColor;
  42481. break;
  42482. case 'touchstart':
  42483. color = this.data.buttonTouchedColor;
  42484. break;
  42485. default:
  42486. color = this.data.buttonColor;
  42487. }
  42488. buttonMeshes[buttonName].material.color.set(color);
  42489. }
  42490. });
  42491. },{"../core/component":102,"../utils/bind":166,"../utils/tracked-controls":178}],57:[function(_dereq_,module,exports){
  42492. var registerComponent = _dereq_('../core/component').registerComponent;
  42493. var bind = _dereq_('../utils/bind');
  42494. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  42495. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  42496. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  42497. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  42498. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  42499. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  42500. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  42501. var GAMEPAD_ID_PREFIX = 'Gear VR';
  42502. /**
  42503. * Gear VR controls.
  42504. * Interface with Gear VR controller and map Gamepad events to
  42505. * controller buttons: trackpad, trigger
  42506. * Load a controller model and highlight the pressed buttons.
  42507. */
  42508. module.exports.Component = registerComponent('gearvr-controls', {
  42509. schema: {
  42510. hand: {default: ''}, // This informs the degenerate arm model.
  42511. buttonColor: {type: 'color', default: '#000000'},
  42512. buttonTouchedColor: {type: 'color', default: '#777777'},
  42513. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  42514. model: {default: true},
  42515. orientationOffset: {type: 'vec3'},
  42516. armModel: {default: true}
  42517. },
  42518. /**
  42519. * Button IDs:
  42520. * 0 - trackpad
  42521. * 1 - trigger
  42522. */
  42523. mapping: {
  42524. axes: {trackpad: [0, 1]},
  42525. buttons: ['trackpad', 'trigger']
  42526. },
  42527. bindMethods: function () {
  42528. this.onModelLoaded = bind(this.onModelLoaded, this);
  42529. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  42530. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  42531. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  42532. this.onAxisMoved = bind(this.onAxisMoved, this);
  42533. },
  42534. init: function () {
  42535. var self = this;
  42536. this.animationActive = 'pointing';
  42537. this.onButtonChanged = bind(this.onButtonChanged, this);
  42538. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  42539. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  42540. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  42541. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  42542. this.onAxisMoved = bind(this.onAxisMoved, this);
  42543. this.controllerPresent = false;
  42544. this.lastControllerCheck = 0;
  42545. this.bindMethods();
  42546. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  42547. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  42548. },
  42549. addEventListeners: function () {
  42550. var el = this.el;
  42551. el.addEventListener('buttonchanged', this.onButtonChanged);
  42552. el.addEventListener('buttondown', this.onButtonDown);
  42553. el.addEventListener('buttonup', this.onButtonUp);
  42554. el.addEventListener('touchstart', this.onButtonTouchStart);
  42555. el.addEventListener('touchend', this.onButtonTouchEnd);
  42556. el.addEventListener('model-loaded', this.onModelLoaded);
  42557. el.addEventListener('axismove', this.onAxisMoved);
  42558. this.controllerEventsActive = true;
  42559. },
  42560. removeEventListeners: function () {
  42561. var el = this.el;
  42562. el.removeEventListener('buttonchanged', this.onButtonChanged);
  42563. el.removeEventListener('buttondown', this.onButtonDown);
  42564. el.removeEventListener('buttonup', this.onButtonUp);
  42565. el.removeEventListener('touchstart', this.onButtonTouchStart);
  42566. el.removeEventListener('touchend', this.onButtonTouchEnd);
  42567. el.removeEventListener('model-loaded', this.onModelLoaded);
  42568. el.removeEventListener('axismove', this.onAxisMoved);
  42569. this.controllerEventsActive = false;
  42570. },
  42571. checkIfControllerPresent: function () {
  42572. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  42573. this.data.hand ? {hand: this.data.hand} : {});
  42574. },
  42575. play: function () {
  42576. this.checkIfControllerPresent();
  42577. this.addControllersUpdateListener();
  42578. },
  42579. pause: function () {
  42580. this.removeEventListeners();
  42581. this.removeControllersUpdateListener();
  42582. },
  42583. injectTrackedControls: function () {
  42584. var el = this.el;
  42585. var data = this.data;
  42586. el.setAttribute('tracked-controls', {
  42587. armModel: data.armModel,
  42588. idPrefix: GAMEPAD_ID_PREFIX,
  42589. orientationOffset: data.orientationOffset
  42590. });
  42591. if (!this.data.model) { return; }
  42592. this.el.setAttribute('obj-model', {
  42593. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  42594. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  42595. });
  42596. },
  42597. addControllersUpdateListener: function () {
  42598. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  42599. },
  42600. removeControllersUpdateListener: function () {
  42601. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  42602. },
  42603. onControllersUpdate: function () {
  42604. this.checkIfControllerPresent();
  42605. },
  42606. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  42607. onModelLoaded: function (evt) {
  42608. var controllerObject3D = evt.detail.model;
  42609. var buttonMeshes;
  42610. if (!this.data.model) { return; }
  42611. buttonMeshes = this.buttonMeshes = {};
  42612. buttonMeshes.trigger = controllerObject3D.children[2];
  42613. buttonMeshes.trackpad = controllerObject3D.children[1];
  42614. },
  42615. onButtonChanged: function (evt) {
  42616. var button = this.mapping.buttons[evt.detail.id];
  42617. if (!button) return;
  42618. // Pass along changed event with button state, using button mapping for convenience.
  42619. this.el.emit(button + 'changed', evt.detail.state);
  42620. },
  42621. onAxisMoved: function (evt) {
  42622. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  42623. },
  42624. updateModel: function (buttonName, evtName) {
  42625. if (!this.data.model) { return; }
  42626. this.updateButtonModel(buttonName, evtName);
  42627. },
  42628. updateButtonModel: function (buttonName, state) {
  42629. var buttonMeshes = this.buttonMeshes;
  42630. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  42631. var color;
  42632. switch (state) {
  42633. case 'down':
  42634. color = this.data.buttonHighlightColor;
  42635. break;
  42636. case 'touchstart':
  42637. color = this.data.buttonTouchedColor;
  42638. break;
  42639. default:
  42640. color = this.data.buttonColor;
  42641. }
  42642. buttonMeshes[buttonName].material.color.set(color);
  42643. }
  42644. });
  42645. },{"../core/component":102,"../utils/bind":166,"../utils/tracked-controls":178}],58:[function(_dereq_,module,exports){
  42646. var geometries = _dereq_('../core/geometry').geometries;
  42647. var geometryNames = _dereq_('../core/geometry').geometryNames;
  42648. var registerComponent = _dereq_('../core/component').registerComponent;
  42649. var THREE = _dereq_('../lib/three');
  42650. var dummyGeometry = new THREE.Geometry();
  42651. /**
  42652. * Geometry component. Combined with material component to make a mesh in 3D object.
  42653. * Extended with registered geometries.
  42654. */
  42655. module.exports.Component = registerComponent('geometry', {
  42656. schema: {
  42657. buffer: {default: true},
  42658. primitive: {default: 'box', oneOf: geometryNames},
  42659. skipCache: {default: false}
  42660. },
  42661. init: function () {
  42662. this.geometry = null;
  42663. },
  42664. /**
  42665. * Talk to geometry system to get or create geometry.
  42666. */
  42667. update: function (previousData) {
  42668. var data = this.data;
  42669. var el = this.el;
  42670. var mesh;
  42671. var system = this.system;
  42672. // Dispose old geometry if we created one.
  42673. if (this.geometry) {
  42674. system.unuseGeometry(previousData);
  42675. this.geometry = null;
  42676. }
  42677. // Create new geometry.
  42678. this.geometry = system.getOrCreateGeometry(data);
  42679. // Set on mesh. If mesh does not exist, create it.
  42680. mesh = el.getObject3D('mesh');
  42681. if (mesh) {
  42682. mesh.geometry = this.geometry;
  42683. } else {
  42684. mesh = new THREE.Mesh();
  42685. mesh.geometry = this.geometry;
  42686. el.setObject3D('mesh', mesh);
  42687. }
  42688. },
  42689. /**
  42690. * Tell geometry system that entity is no longer using the geometry.
  42691. * Unset the geometry on the mesh
  42692. */
  42693. remove: function () {
  42694. this.system.unuseGeometry(this.data);
  42695. this.el.getObject3D('mesh').geometry = dummyGeometry;
  42696. this.geometry = null;
  42697. },
  42698. /**
  42699. * Update geometry component schema based on geometry type.
  42700. *
  42701. * @param {object} data - New data passed by Component.
  42702. */
  42703. updateSchema: function (data) {
  42704. var newGeometryType = data.primitive;
  42705. var currentGeometryType = this.data && this.data.primitive;
  42706. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  42707. // Geometry has no schema.
  42708. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  42709. // Nothing has changed.
  42710. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  42711. this.extendSchema(schema);
  42712. }
  42713. });
  42714. },{"../core/component":102,"../core/geometry":103,"../lib/three":150}],59:[function(_dereq_,module,exports){
  42715. var registerComponent = _dereq_('../core/component').registerComponent;
  42716. var THREE = _dereq_('../lib/three');
  42717. var utils = _dereq_('../utils/');
  42718. var warn = utils.debug('components:gltf-model:warn');
  42719. /**
  42720. * glTF model loader.
  42721. */
  42722. module.exports.Component = registerComponent('gltf-model', {
  42723. schema: {type: 'model'},
  42724. init: function () {
  42725. this.model = null;
  42726. this.loader = new THREE.GLTFLoader();
  42727. },
  42728. update: function () {
  42729. var self = this;
  42730. var el = this.el;
  42731. var src = this.data;
  42732. if (!src) { return; }
  42733. this.remove();
  42734. this.loader.load(src, function gltfLoaded (gltfModel) {
  42735. self.model = gltfModel.scene || gltfModel.scenes[0];
  42736. self.model.animations = gltfModel.animations;
  42737. el.setObject3D('mesh', self.model);
  42738. el.emit('model-loaded', {format: 'gltf', model: self.model});
  42739. }, undefined /* onProgress */, function gltfFailed (error) {
  42740. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  42741. warn(message);
  42742. el.emit('model-error', {format: 'gltf', src: src});
  42743. });
  42744. },
  42745. remove: function () {
  42746. if (!this.model) { return; }
  42747. this.el.removeObject3D('mesh');
  42748. }
  42749. });
  42750. },{"../core/component":102,"../lib/three":150,"../utils/":172}],60:[function(_dereq_,module,exports){
  42751. /* global THREE */
  42752. var registerComponent = _dereq_('../core/component').registerComponent;
  42753. // Found at https://github.com/aframevr/assets.
  42754. var MODEL_URLS = {
  42755. left: 'https://cdn.aframe.io/controllers/oculus-hands/v2/leftHand.json',
  42756. right: 'https://cdn.aframe.io/controllers/oculus-hands/v2/rightHand.json'
  42757. };
  42758. // Poses.
  42759. var ANIMATIONS = {
  42760. open: 'Open',
  42761. // point: grip active, trackpad surface active, trigger inactive.
  42762. point: 'Point',
  42763. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  42764. pointThumb: 'Point + Thumb',
  42765. // fist: grip active, trigger active, trackpad surface active.
  42766. fist: 'Fist',
  42767. // hold: trigger active, grip inactive.
  42768. hold: 'Hold',
  42769. // thumbUp: grip active, trigger active, trackpad surface inactive.
  42770. thumbUp: 'Thumb Up'
  42771. };
  42772. // Map animation to public events for the API.
  42773. var EVENTS = {};
  42774. EVENTS[ANIMATIONS.fist] = 'grip';
  42775. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  42776. EVENTS[ANIMATIONS.point] = 'pointing';
  42777. EVENTS[ANIMATIONS.thumb] = 'thumb';
  42778. /**
  42779. * Hand controls component that abstracts 6DoF controls:
  42780. * oculus-touch-controls, vive-controls, windows-motion-controls.
  42781. *
  42782. * Originally meant to be a sample implementation of applications-specific controls that
  42783. * abstracts multiple types of controllers.
  42784. *
  42785. * Auto-detect appropriate controller.
  42786. * Handle common events coming from the detected vendor-specific controls.
  42787. * Translate button events to semantic hand-related event names:
  42788. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  42789. * Load hand model with gestures that are applied based on the button pressed.
  42790. *
  42791. * @property {string} Hand mapping (`left`, `right`).
  42792. */
  42793. module.exports.Component = registerComponent('hand-controls', {
  42794. schema: {default: 'left'},
  42795. init: function () {
  42796. var self = this;
  42797. var el = this.el;
  42798. // Current pose.
  42799. this.gesture = ANIMATIONS.open;
  42800. // Active buttons populated by events provided by the attached controls.
  42801. this.pressedButtons = {};
  42802. this.touchedButtons = {};
  42803. this.loader = new THREE.ObjectLoader();
  42804. this.loader.setCrossOrigin('anonymous');
  42805. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  42806. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  42807. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  42808. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  42809. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  42810. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  42811. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  42812. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  42813. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  42814. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  42815. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  42816. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  42817. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  42818. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  42819. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  42820. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  42821. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  42822. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  42823. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  42824. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  42825. this.onControllerConnected = function () { self.setModelVisibility(true); };
  42826. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  42827. el.addEventListener('controllerconnected', this.onControllerConnected);
  42828. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  42829. },
  42830. play: function () {
  42831. this.addEventListeners();
  42832. },
  42833. pause: function () {
  42834. this.removeEventListeners();
  42835. },
  42836. tick: function (time, delta) {
  42837. var mesh = this.el.getObject3D('mesh');
  42838. if (!mesh || !mesh.mixer) { return; }
  42839. mesh.mixer.update(delta / 1000);
  42840. },
  42841. addEventListeners: function () {
  42842. var el = this.el;
  42843. el.addEventListener('gripdown', this.onGripDown);
  42844. el.addEventListener('gripup', this.onGripUp);
  42845. el.addEventListener('trackpaddown', this.onTrackpadDown);
  42846. el.addEventListener('trackpadup', this.onTrackpadUp);
  42847. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  42848. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  42849. el.addEventListener('triggerdown', this.onTriggerDown);
  42850. el.addEventListener('triggerup', this.onTriggerUp);
  42851. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  42852. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  42853. el.addEventListener('griptouchstart', this.onGripTouchStart);
  42854. el.addEventListener('griptouchend', this.onGripTouchEnd);
  42855. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  42856. el.addEventListener('thumbstickup', this.onThumbstickUp);
  42857. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  42858. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  42859. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  42860. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  42861. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  42862. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  42863. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  42864. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  42865. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  42866. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  42867. },
  42868. removeEventListeners: function () {
  42869. var el = this.el;
  42870. el.removeEventListener('gripdown', this.onGripDown);
  42871. el.removeEventListener('gripup', this.onGripUp);
  42872. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  42873. el.removeEventListener('trackpadup', this.onTrackpadUp);
  42874. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  42875. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  42876. el.removeEventListener('triggerdown', this.onTriggerDown);
  42877. el.removeEventListener('triggerup', this.onTriggerUp);
  42878. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  42879. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  42880. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  42881. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  42882. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  42883. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  42884. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  42885. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  42886. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  42887. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  42888. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  42889. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  42890. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  42891. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  42892. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  42893. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  42894. },
  42895. /**
  42896. * Update handler. More like the `init` handler since the only property is the hand, and
  42897. * that won't be changing much.
  42898. */
  42899. update: function (previousHand) {
  42900. var controlConfiguration;
  42901. var el = this.el;
  42902. var hand = this.data;
  42903. // Get common configuration to abstract different vendor controls.
  42904. controlConfiguration = {
  42905. hand: hand,
  42906. model: false,
  42907. orientationOffset: {x: 0, y: 0, z: hand === 'left' ? 90 : -90}
  42908. };
  42909. // Set model.
  42910. if (hand !== previousHand) {
  42911. this.loader.load(MODEL_URLS[hand], function (scene) {
  42912. var mesh = scene.getObjectByName('Hand');
  42913. mesh.material.skinning = true;
  42914. mesh.mixer = new THREE.AnimationMixer(mesh);
  42915. el.setObject3D('mesh', mesh);
  42916. mesh.position.set(0, 0, 0);
  42917. mesh.rotation.set(0, 0, 0);
  42918. // hidden by default
  42919. mesh.visible = false;
  42920. el.setAttribute('vive-controls', controlConfiguration);
  42921. el.setAttribute('oculus-touch-controls', controlConfiguration);
  42922. el.setAttribute('windows-motion-controls', controlConfiguration);
  42923. });
  42924. }
  42925. },
  42926. remove: function () {
  42927. this.el.removeObject3D('mesh');
  42928. },
  42929. /**
  42930. * Play model animation, based on which button was pressed and which kind of event.
  42931. *
  42932. * 1. Process buttons.
  42933. * 2. Determine gesture (this.determineGesture()).
  42934. * 3. Animation gesture (this.animationGesture()).
  42935. * 4. Emit gesture events (this.emitGestureEvents()).
  42936. *
  42937. * @param {string} button - Name of the button.
  42938. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  42939. */
  42940. handleButton: function (button, evt) {
  42941. var lastGesture;
  42942. var isPressed = evt === 'down';
  42943. var isTouched = evt === 'touchstart';
  42944. // Update objects.
  42945. if (evt.indexOf('touch') === 0) {
  42946. // Update touch object.
  42947. if (isTouched === this.touchedButtons[button]) { return; }
  42948. this.touchedButtons[button] = isTouched;
  42949. } else {
  42950. // Update button object.
  42951. if (isPressed === this.pressedButtons[button]) { return; }
  42952. this.pressedButtons[button] = isPressed;
  42953. }
  42954. // Determine the gesture.
  42955. lastGesture = this.gesture;
  42956. this.gesture = this.determineGesture();
  42957. // Same gesture.
  42958. if (this.gesture === lastGesture) { return; }
  42959. // Animate gesture.
  42960. this.animateGesture(this.gesture, lastGesture);
  42961. // Emit events.
  42962. this.emitGestureEvents(this.gesture, lastGesture);
  42963. },
  42964. /**
  42965. * Determine which pose hand should be in considering active and touched buttons.
  42966. */
  42967. determineGesture: function () {
  42968. var gesture;
  42969. var isGripActive = this.pressedButtons['grip'];
  42970. var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
  42971. var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
  42972. var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
  42973. var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
  42974. var isVive = isViveController(this.el.components['tracked-controls']);
  42975. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  42976. if (isGripActive) {
  42977. if (isVive) {
  42978. gesture = ANIMATIONS.fist;
  42979. } else
  42980. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  42981. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  42982. } else {
  42983. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  42984. }
  42985. } else {
  42986. if (isTriggerActive) {
  42987. gesture = !isVive ? ANIMATIONS.hold : ANIMATIONS.fist;
  42988. } else if (isVive && isTrackpadActive) {
  42989. gesture = ANIMATIONS.point;
  42990. }
  42991. }
  42992. return gesture;
  42993. },
  42994. /**
  42995. * Play gesture animation.
  42996. *
  42997. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  42998. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  42999. */
  43000. animateGesture: function (gesture, lastGesture) {
  43001. if (gesture) {
  43002. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  43003. return;
  43004. }
  43005. // If no gesture, then reverse the current gesture back to open pose.
  43006. this.playAnimation(lastGesture, lastGesture, true);
  43007. },
  43008. /**
  43009. * Emit `hand-controls`-specific events.
  43010. */
  43011. emitGestureEvents: function (gesture, lastGesture) {
  43012. var el = this.el;
  43013. var eventName;
  43014. if (lastGesture === gesture) { return; }
  43015. // Emit event for lastGesture not inactive.
  43016. eventName = getGestureEventName(lastGesture, false);
  43017. if (eventName) { el.emit(eventName); }
  43018. // Emit event for current gesture now active.
  43019. eventName = getGestureEventName(gesture, true);
  43020. if (eventName) { el.emit(eventName); }
  43021. },
  43022. /**
  43023. * Play hand animation based on button state.
  43024. *
  43025. * @param {string} gesture - Name of the animation as specified by the model.
  43026. * @param {string} lastGesture - Previous pose.
  43027. * @param {boolean} reverse - Whether animation should play in reverse.
  43028. */
  43029. playAnimation: function (gesture, lastGesture, reverse) {
  43030. var fromAction;
  43031. var mesh = this.el.getObject3D('mesh');
  43032. var toAction;
  43033. if (!mesh) { return; }
  43034. // Grab clip action.
  43035. toAction = mesh.mixer.clipAction(gesture);
  43036. toAction.clampWhenFinished = true;
  43037. toAction.loop = THREE.LoopRepeat;
  43038. toAction.repetitions = 0;
  43039. toAction.timeScale = reverse ? -1 : 1;
  43040. toAction.weight = 1;
  43041. // No gesture to gesture or gesture to no gesture.
  43042. if (!lastGesture || gesture === lastGesture) {
  43043. // Stop all current animations.
  43044. mesh.mixer.stopAllAction();
  43045. // Play animation.
  43046. toAction.play();
  43047. return;
  43048. }
  43049. // Animate or crossfade from gesture to gesture.
  43050. fromAction = mesh.mixer.clipAction(lastGesture);
  43051. mesh.mixer.stopAllAction();
  43052. fromAction.weight = 0.15;
  43053. fromAction.play();
  43054. toAction.play();
  43055. fromAction.crossFadeTo(toAction, 0.15, true);
  43056. },
  43057. setModelVisibility: function (visible) {
  43058. var model = this.el.getObject3D('mesh');
  43059. if (!model) { return; }
  43060. model.visible = visible;
  43061. }
  43062. });
  43063. /**
  43064. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  43065. *
  43066. * @param {string} gesture
  43067. * @param {boolean} active
  43068. */
  43069. function getGestureEventName (gesture, active) {
  43070. var eventName;
  43071. if (!gesture) { return; }
  43072. eventName = EVENTS[gesture];
  43073. if (eventName === 'grip') {
  43074. return eventName + (active ? 'close' : 'open');
  43075. }
  43076. if (eventName === 'point' || eventName === 'thumb') {
  43077. return eventName + (active ? 'up' : 'down');
  43078. }
  43079. if (eventName === 'pointing' || eventName === 'pistol') {
  43080. return eventName + (active ? 'start' : 'end');
  43081. }
  43082. return;
  43083. }
  43084. function isViveController (trackedControls) {
  43085. var controllerId = trackedControls && trackedControls.controller &&
  43086. trackedControls.controller.id;
  43087. return controllerId && controllerId.indexOf('OpenVR ') === 0;
  43088. }
  43089. },{"../core/component":102}],61:[function(_dereq_,module,exports){
  43090. _dereq_('./animation');
  43091. _dereq_('./camera');
  43092. _dereq_('./collada-model');
  43093. _dereq_('./cursor');
  43094. _dereq_('./daydream-controls');
  43095. _dereq_('./gearvr-controls');
  43096. _dereq_('./geometry');
  43097. _dereq_('./gltf-model');
  43098. _dereq_('./hand-controls');
  43099. _dereq_('./laser-controls');
  43100. _dereq_('./light');
  43101. _dereq_('./line');
  43102. _dereq_('./link');
  43103. _dereq_('./look-controls');
  43104. _dereq_('./material');
  43105. _dereq_('./obj-model');
  43106. _dereq_('./oculus-go-controls');
  43107. _dereq_('./oculus-touch-controls');
  43108. _dereq_('./position');
  43109. _dereq_('./raycaster');
  43110. _dereq_('./rotation');
  43111. _dereq_('./scale');
  43112. _dereq_('./shadow');
  43113. _dereq_('./sound');
  43114. _dereq_('./text');
  43115. _dereq_('./tracked-controls');
  43116. _dereq_('./visible');
  43117. _dereq_('./vive-controls');
  43118. _dereq_('./wasd-controls');
  43119. _dereq_('./windows-motion-controls');
  43120. _dereq_('./scene/background');
  43121. _dereq_('./scene/debug');
  43122. _dereq_('./scene/embedded');
  43123. _dereq_('./scene/inspector');
  43124. _dereq_('./scene/fog');
  43125. _dereq_('./scene/keyboard-shortcuts');
  43126. _dereq_('./scene/pool');
  43127. _dereq_('./scene/renderer');
  43128. _dereq_('./scene/screenshot');
  43129. _dereq_('./scene/stats');
  43130. _dereq_('./scene/vr-mode-ui');
  43131. },{"./animation":52,"./camera":53,"./collada-model":54,"./cursor":55,"./daydream-controls":56,"./gearvr-controls":57,"./geometry":58,"./gltf-model":59,"./hand-controls":60,"./laser-controls":62,"./light":63,"./line":64,"./link":65,"./look-controls":66,"./material":67,"./obj-model":68,"./oculus-go-controls":69,"./oculus-touch-controls":70,"./position":71,"./raycaster":72,"./rotation":73,"./scale":74,"./scene/background":75,"./scene/debug":76,"./scene/embedded":77,"./scene/fog":78,"./scene/inspector":79,"./scene/keyboard-shortcuts":80,"./scene/pool":81,"./scene/renderer":82,"./scene/screenshot":83,"./scene/stats":84,"./scene/vr-mode-ui":85,"./shadow":86,"./sound":87,"./text":88,"./tracked-controls":89,"./visible":90,"./vive-controls":91,"./wasd-controls":92,"./windows-motion-controls":93}],62:[function(_dereq_,module,exports){
  43132. var registerComponent = _dereq_('../core/component').registerComponent;
  43133. var utils = _dereq_('../utils/');
  43134. registerComponent('laser-controls', {
  43135. schema: {
  43136. hand: {default: 'right'}
  43137. },
  43138. init: function () {
  43139. var config = this.config;
  43140. var data = this.data;
  43141. var el = this.el;
  43142. var self = this;
  43143. // Set all controller models.
  43144. el.setAttribute('daydream-controls', {hand: data.hand});
  43145. el.setAttribute('gearvr-controls', {hand: data.hand});
  43146. el.setAttribute('oculus-go-controls', {hand: data.hand});
  43147. el.setAttribute('oculus-touch-controls', {hand: data.hand});
  43148. el.setAttribute('vive-controls', {hand: data.hand});
  43149. el.setAttribute('windows-motion-controls', {hand: data.hand});
  43150. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  43151. el.addEventListener('controllerconnected', createRay);
  43152. el.addEventListener('controllerdisconnected', hideRay);
  43153. el.addEventListener('controllermodelready', function (evt) {
  43154. createRay(evt);
  43155. self.modelReady = true;
  43156. });
  43157. function createRay (evt) {
  43158. var controllerConfig = config[evt.detail.name];
  43159. if (!controllerConfig) { return; }
  43160. // Show the line unless a particular config opts to hide it, until a controllermodelready
  43161. // event comes through.
  43162. var raycasterConfig = utils.extend({
  43163. showLine: true
  43164. }, controllerConfig.raycaster || {});
  43165. // The controllermodelready event contains a rayOrigin that takes into account
  43166. // offsets specific to the loaded model.
  43167. if (evt.detail.rayOrigin) {
  43168. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  43169. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  43170. raycasterConfig.showLine = true;
  43171. }
  43172. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  43173. // config applied from a controllermodelready event.
  43174. if (evt.detail.rayOrigin || !self.modelReady) {
  43175. el.setAttribute('raycaster', raycasterConfig);
  43176. } else {
  43177. el.setAttribute('raycaster', 'showLine', true);
  43178. }
  43179. el.setAttribute('cursor', utils.extend({
  43180. fuse: false
  43181. }, controllerConfig.cursor));
  43182. }
  43183. function hideRay () {
  43184. el.setAttribute('raycaster', 'showLine', false);
  43185. }
  43186. },
  43187. config: {
  43188. 'daydream-controls': {
  43189. cursor: {downEvents: ['trackpaddown'], upEvents: ['trackpadup']}
  43190. },
  43191. 'gearvr-controls': {
  43192. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']},
  43193. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  43194. },
  43195. 'oculus-go-controls': {
  43196. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']},
  43197. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  43198. },
  43199. 'oculus-touch-controls': {
  43200. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  43201. raycaster: {origin: {x: 0, y: 0, z: 0}}
  43202. },
  43203. 'vive-controls': {
  43204. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  43205. },
  43206. 'windows-motion-controls': {
  43207. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  43208. raycaster: {showLine: false}
  43209. }
  43210. }
  43211. });
  43212. },{"../core/component":102,"../utils/":172}],63:[function(_dereq_,module,exports){
  43213. var bind = _dereq_('../utils/bind');
  43214. var diff = _dereq_('../utils').diff;
  43215. var debug = _dereq_('../utils/debug');
  43216. var registerComponent = _dereq_('../core/component').registerComponent;
  43217. var THREE = _dereq_('../lib/three');
  43218. var degToRad = THREE.Math.degToRad;
  43219. var warn = debug('components:light:warn');
  43220. /**
  43221. * Light component.
  43222. */
  43223. module.exports.Component = registerComponent('light', {
  43224. schema: {
  43225. angle: {default: 60, if: {type: ['spot']}},
  43226. color: {type: 'color'},
  43227. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  43228. decay: {default: 1, if: {type: ['point', 'spot']}},
  43229. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  43230. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  43231. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  43232. type: {default: 'directional', oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot']},
  43233. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  43234. // Shadows.
  43235. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  43236. shadowBias: {default: 0, if: {castShadow: true}},
  43237. shadowCameraFar: {default: 500, if: {castShadow: true}},
  43238. shadowCameraFov: {default: 90, if: {castShadow: true}},
  43239. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  43240. shadowCameraTop: {default: 5, if: {castShadow: true}},
  43241. shadowCameraRight: {default: 5, if: {castShadow: true}},
  43242. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  43243. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  43244. shadowCameraVisible: {default: false, if: {castShadow: true}},
  43245. shadowMapHeight: {default: 512, if: {castShadow: true}},
  43246. shadowMapWidth: {default: 512, if: {castShadow: true}},
  43247. shadowRadius: {default: 1, if: {castShadow: true}}
  43248. },
  43249. /**
  43250. * Notifies scene a light has been added to remove default lighting.
  43251. */
  43252. init: function () {
  43253. var el = this.el;
  43254. this.light = null;
  43255. this.defaultTarget = null;
  43256. this.system.registerLight(el);
  43257. },
  43258. /**
  43259. * (Re)create or update light.
  43260. */
  43261. update: function (oldData) {
  43262. var data = this.data;
  43263. var diffData = diff(data, oldData);
  43264. var light = this.light;
  43265. var self = this;
  43266. // Existing light.
  43267. if (light && !('type' in diffData)) {
  43268. var shadowsLoaded = false;
  43269. // Light type has not changed. Update light.
  43270. Object.keys(diffData).forEach(function (key) {
  43271. var value = data[key];
  43272. switch (key) {
  43273. case 'color': {
  43274. light.color.set(value);
  43275. break;
  43276. }
  43277. case 'groundColor': {
  43278. light.groundColor.set(value);
  43279. break;
  43280. }
  43281. case 'angle': {
  43282. light.angle = degToRad(value);
  43283. break;
  43284. }
  43285. case 'target': {
  43286. // Reset target if selector is null.
  43287. if (value === null) {
  43288. if (data.type === 'spot' || data.type === 'directional') {
  43289. light.target = self.defaultTarget;
  43290. }
  43291. } else {
  43292. // Target specified, set target to entity's `object3D` when it is loaded.
  43293. if (value.hasLoaded) {
  43294. self.onSetTarget(value, light);
  43295. } else {
  43296. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  43297. }
  43298. }
  43299. break;
  43300. }
  43301. case 'castShadow':
  43302. case 'shadowBias':
  43303. case 'shadowCameraFar':
  43304. case 'shadowCameraFov':
  43305. case 'shadowCameraNear':
  43306. case 'shadowCameraTop':
  43307. case 'shadowCameraRight':
  43308. case 'shadowCameraBottom':
  43309. case 'shadowCameraLeft':
  43310. case 'shadowCameraVisible':
  43311. case 'shadowMapHeight':
  43312. case 'shadowMapWidth':
  43313. case 'shadowRadius':
  43314. if (!shadowsLoaded) {
  43315. self.updateShadow();
  43316. shadowsLoaded = true;
  43317. }
  43318. break;
  43319. default: {
  43320. light[key] = value;
  43321. }
  43322. }
  43323. });
  43324. return;
  43325. }
  43326. // No light yet or light type has changed. Create and add light.
  43327. this.setLight(this.data);
  43328. this.updateShadow();
  43329. },
  43330. setLight: function (data) {
  43331. var el = this.el;
  43332. var newLight = this.getLight(data);
  43333. if (newLight) {
  43334. if (this.light) {
  43335. el.removeObject3D('light');
  43336. }
  43337. this.light = newLight;
  43338. this.light.el = el;
  43339. el.setObject3D('light', this.light);
  43340. // HACK solution for issue #1624
  43341. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  43342. el.getObject3D('light').translateY(-1);
  43343. }
  43344. // set and position default lighttarget as a child to enable spotlight orientation
  43345. if (data.type === 'spot') {
  43346. el.setObject3D('light-target', this.defaultTarget);
  43347. el.getObject3D('light-target').position.set(0, 0, -1);
  43348. }
  43349. }
  43350. },
  43351. /**
  43352. * Updates shadow-related properties on the current light.
  43353. */
  43354. updateShadow: function () {
  43355. var el = this.el;
  43356. var data = this.data;
  43357. var light = this.light;
  43358. light.castShadow = data.castShadow;
  43359. // Shadow camera helper.
  43360. var cameraHelper = el.getObject3D('cameraHelper');
  43361. if (data.shadowCameraVisible && !cameraHelper) {
  43362. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  43363. } else if (!data.shadowCameraVisible && cameraHelper) {
  43364. el.removeObject3D('cameraHelper');
  43365. }
  43366. if (!data.castShadow) { return light; }
  43367. // Shadow appearance.
  43368. light.shadow.bias = data.shadowBias;
  43369. light.shadow.radius = data.shadowRadius;
  43370. light.shadow.mapSize.height = data.shadowMapHeight;
  43371. light.shadow.mapSize.width = data.shadowMapWidth;
  43372. // Shadow camera.
  43373. light.shadow.camera.near = data.shadowCameraNear;
  43374. light.shadow.camera.far = data.shadowCameraFar;
  43375. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  43376. light.shadow.camera.top = data.shadowCameraTop;
  43377. light.shadow.camera.right = data.shadowCameraRight;
  43378. light.shadow.camera.bottom = data.shadowCameraBottom;
  43379. light.shadow.camera.left = data.shadowCameraLeft;
  43380. } else {
  43381. light.shadow.camera.fov = data.shadowCameraFov;
  43382. }
  43383. light.shadow.camera.updateProjectionMatrix();
  43384. if (cameraHelper) { cameraHelper.update(); }
  43385. },
  43386. /**
  43387. * Creates a new three.js light object given data object defining the light.
  43388. *
  43389. * @param {object} data
  43390. */
  43391. getLight: function (data) {
  43392. var angle = data.angle;
  43393. var color = new THREE.Color(data.color).getHex();
  43394. var decay = data.decay;
  43395. var distance = data.distance;
  43396. var groundColor = new THREE.Color(data.groundColor).getHex();
  43397. var intensity = data.intensity;
  43398. var type = data.type;
  43399. var target = data.target;
  43400. var light = null;
  43401. switch (type.toLowerCase()) {
  43402. case 'ambient': {
  43403. return new THREE.AmbientLight(color, intensity);
  43404. }
  43405. case 'directional': {
  43406. light = new THREE.DirectionalLight(color, intensity);
  43407. this.defaultTarget = light.target;
  43408. if (target) {
  43409. if (target.hasLoaded) {
  43410. this.onSetTarget(target, light);
  43411. } else {
  43412. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  43413. }
  43414. }
  43415. return light;
  43416. }
  43417. case 'hemisphere': {
  43418. return new THREE.HemisphereLight(color, groundColor, intensity);
  43419. }
  43420. case 'point': {
  43421. return new THREE.PointLight(color, intensity, distance, decay);
  43422. }
  43423. case 'spot': {
  43424. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  43425. this.defaultTarget = light.target;
  43426. if (target) {
  43427. if (target.hasLoaded) {
  43428. this.onSetTarget(target, light);
  43429. } else {
  43430. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  43431. }
  43432. }
  43433. return light;
  43434. }
  43435. default: {
  43436. warn('%s is not a valid light type. ' +
  43437. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  43438. }
  43439. }
  43440. },
  43441. onSetTarget: function (targetEl, light) {
  43442. light.target = targetEl.object3D;
  43443. },
  43444. /**
  43445. * Remove light on remove (callback).
  43446. */
  43447. remove: function () {
  43448. var el = this.el;
  43449. el.removeObject3D('light');
  43450. if (el.getObject3D('cameraHelper')) {
  43451. el.removeObject3D('cameraHelper');
  43452. }
  43453. }
  43454. });
  43455. },{"../core/component":102,"../lib/three":150,"../utils":172,"../utils/bind":166,"../utils/debug":168}],64:[function(_dereq_,module,exports){
  43456. /* global THREE */
  43457. var registerComponent = _dereq_('../core/component').registerComponent;
  43458. module.exports.Component = registerComponent('line', {
  43459. schema: {
  43460. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  43461. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  43462. color: {type: 'color', default: '#74BEC1'},
  43463. opacity: {type: 'number', default: 1},
  43464. visible: {default: true}
  43465. },
  43466. multiple: true,
  43467. init: function () {
  43468. var data = this.data;
  43469. var geometry;
  43470. var material;
  43471. material = this.material = new THREE.LineBasicMaterial({
  43472. color: data.color,
  43473. opacity: data.opacity,
  43474. transparent: data.opacity < 1,
  43475. visible: data.visible
  43476. });
  43477. geometry = this.geometry = new THREE.BufferGeometry();
  43478. geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  43479. this.line = new THREE.Line(geometry, material);
  43480. this.el.setObject3D(this.attrName, this.line);
  43481. },
  43482. update: function (oldData) {
  43483. var data = this.data;
  43484. var geometry = this.geometry;
  43485. var geoNeedsUpdate = false;
  43486. var material = this.material;
  43487. var positionArray = geometry.attributes.position.array;
  43488. // Update geometry.
  43489. if (!isEqualVec3(data.start, oldData.start)) {
  43490. positionArray[0] = data.start.x;
  43491. positionArray[1] = data.start.y;
  43492. positionArray[2] = data.start.z;
  43493. geoNeedsUpdate = true;
  43494. }
  43495. if (!isEqualVec3(data.end, oldData.end)) {
  43496. positionArray[3] = data.end.x;
  43497. positionArray[4] = data.end.y;
  43498. positionArray[5] = data.end.z;
  43499. geoNeedsUpdate = true;
  43500. }
  43501. if (geoNeedsUpdate) {
  43502. geometry.attributes.position.needsUpdate = true;
  43503. geometry.computeBoundingSphere();
  43504. }
  43505. material.color.setStyle(data.color);
  43506. material.opacity = data.opacity;
  43507. material.transparent = data.opacity < 1;
  43508. material.visible = data.visible;
  43509. },
  43510. remove: function () {
  43511. this.el.removeObject3D('line', this.line);
  43512. }
  43513. });
  43514. function isEqualVec3 (a, b) {
  43515. if (!a || !b) { return false; }
  43516. return (a.x === b.x && a.y === b.y && a.z === b.z);
  43517. }
  43518. },{"../core/component":102}],65:[function(_dereq_,module,exports){
  43519. var registerComponent = _dereq_('../core/component').registerComponent;
  43520. var registerShader = _dereq_('../core/shader').registerShader;
  43521. var THREE = _dereq_('../lib/three');
  43522. /**
  43523. * Link component. Connect experiences and traverse between them in VR
  43524. *
  43525. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  43526. */
  43527. module.exports.Component = registerComponent('link', {
  43528. schema: {
  43529. backgroundColor: {default: 'red', type: 'color'},
  43530. borderColor: {default: 'white', type: 'color'},
  43531. highlighted: {default: false},
  43532. highlightedColor: {default: '#24CAFF', type: 'color'},
  43533. href: {default: ''},
  43534. image: {type: 'asset'},
  43535. on: {default: 'click'},
  43536. peekMode: {default: false},
  43537. title: {default: ''},
  43538. titleColor: {default: 'white', type: 'color'},
  43539. visualAspectEnabled: {default: false}
  43540. },
  43541. init: function () {
  43542. this.navigate = this.navigate.bind(this);
  43543. this.previousQuaternion = undefined;
  43544. this.quaternionClone = new THREE.Quaternion();
  43545. // Store hidden elements during peek mode so we can show them again later.
  43546. this.hiddenEls = [];
  43547. },
  43548. update: function (oldData) {
  43549. var data = this.data;
  43550. var el = this.el;
  43551. var backgroundColor;
  43552. var strokeColor;
  43553. if (!data.visualAspectEnabled) { return; }
  43554. this.initVisualAspect();
  43555. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  43556. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  43557. el.setAttribute('material', 'backgroundColor', backgroundColor);
  43558. el.setAttribute('material', 'strokeColor', strokeColor);
  43559. if (data.on !== oldData.on) { this.updateEventListener(); }
  43560. if (oldData.peekMode !== undefined &&
  43561. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  43562. if (!data.image || oldData.image === data.image) { return; }
  43563. el.setAttribute('material', 'pano',
  43564. typeof data.image === 'string' ? data.image : data.image.src);
  43565. },
  43566. /*
  43567. * Toggle all elements and full 360 preview of the linked page.
  43568. */
  43569. updatePeekMode: function () {
  43570. var el = this.el;
  43571. var sphereEl = this.sphereEl;
  43572. if (this.data.peekMode) {
  43573. this.hideAll();
  43574. el.getObject3D('mesh').visible = false;
  43575. sphereEl.setAttribute('visible', true);
  43576. } else {
  43577. this.showAll();
  43578. el.getObject3D('mesh').visible = true;
  43579. sphereEl.setAttribute('visible', false);
  43580. }
  43581. },
  43582. play: function () {
  43583. this.updateEventListener();
  43584. },
  43585. pause: function () {
  43586. this.removeEventListener();
  43587. },
  43588. updateEventListener: function () {
  43589. var el = this.el;
  43590. if (!el.isPlaying) { return; }
  43591. this.removeEventListener();
  43592. el.addEventListener(this.data.on, this.navigate);
  43593. },
  43594. removeEventListener: function () {
  43595. var on = this.data.on;
  43596. if (!on) { return; }
  43597. this.el.removeEventListener(on, this.navigate);
  43598. },
  43599. initVisualAspect: function () {
  43600. var el = this.el;
  43601. var semiSphereEl;
  43602. var sphereEl;
  43603. var textEl;
  43604. if (!this.data.visualAspectEnabled || this.visualAspectInitialized) { return; }
  43605. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  43606. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  43607. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  43608. // Set portal.
  43609. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  43610. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  43611. // Set text that displays the link title and URL.
  43612. textEl.setAttribute('text', {
  43613. color: this.data.titleColor,
  43614. align: 'center',
  43615. font: 'kelsonsans',
  43616. value: this.data.title || this.data.href,
  43617. width: 4
  43618. });
  43619. textEl.setAttribute('position', '0 1.5 0');
  43620. el.appendChild(textEl);
  43621. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  43622. semiSphereEl.setAttribute('geometry', {
  43623. primitive: 'sphere',
  43624. radius: 1.0,
  43625. phiStart: 0,
  43626. segmentsWidth: 64,
  43627. segmentsHeight: 64,
  43628. phiLength: 180,
  43629. thetaStart: 0,
  43630. thetaLength: 360
  43631. });
  43632. semiSphereEl.setAttribute('material', {
  43633. shader: 'portal',
  43634. borderEnabled: 0.0,
  43635. pano: this.data.image,
  43636. side: 'back'
  43637. });
  43638. semiSphereEl.setAttribute('rotation', '0 180 0');
  43639. semiSphereEl.setAttribute('position', '0 0 0');
  43640. semiSphereEl.setAttribute('visible', false);
  43641. el.appendChild(semiSphereEl);
  43642. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  43643. sphereEl.setAttribute('geometry', {
  43644. primitive: 'sphere',
  43645. radius: 10,
  43646. segmentsWidth: 64,
  43647. segmentsHeight: 64
  43648. });
  43649. sphereEl.setAttribute('material', {
  43650. shader: 'portal',
  43651. borderEnabled: 0.0,
  43652. pano: this.data.image,
  43653. side: 'back'
  43654. });
  43655. sphereEl.setAttribute('visible', false);
  43656. el.appendChild(sphereEl);
  43657. this.visualAspectInitialized = true;
  43658. },
  43659. navigate: function () {
  43660. window.location = this.data.href;
  43661. },
  43662. /**
  43663. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  43664. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  43665. * from where user enters.
  43666. * 2. Place the url/title above or inside portal depending on distance to camera.
  43667. * 3. Face portal to camera when far away from user.
  43668. */
  43669. tick: (function () {
  43670. var cameraWorldPosition = new THREE.Vector3();
  43671. var elWorldPosition = new THREE.Vector3();
  43672. var quaternion = new THREE.Quaternion();
  43673. var scale = new THREE.Vector3();
  43674. return function () {
  43675. var el = this.el;
  43676. var object3D = el.object3D;
  43677. var camera = el.sceneEl.camera;
  43678. var cameraPortalOrientation;
  43679. var distance;
  43680. var textEl = this.textEl;
  43681. if (!this.data.visualAspectEnabled) { return; }
  43682. // Update matrices
  43683. object3D.updateMatrixWorld();
  43684. camera.parent.updateMatrixWorld();
  43685. camera.updateMatrixWorld();
  43686. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  43687. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  43688. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  43689. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  43690. if (distance > 20) {
  43691. // Store original orientation to be restored when the portal stops facing the camera.
  43692. if (!this.previousQuaternion) {
  43693. this.quaternionClone.copy(quaternion);
  43694. this.previousQuaternion = this.quaternionClone;
  43695. }
  43696. // If the portal is far away from the user, face portal to camera.
  43697. object3D.lookAt(cameraWorldPosition);
  43698. } else {
  43699. // When portal is close to the user/camera.
  43700. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  43701. // If user gets very close to portal, replace with holed sphere they can peek in.
  43702. if (distance < 0.5) {
  43703. // Configure text size and sphere orientation depending side user approaches portal.
  43704. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  43705. textEl.setAttribute('text', 'width', 1.5);
  43706. if (cameraPortalOrientation <= 0.0) {
  43707. textEl.setAttribute('position', '0 0 0.75');
  43708. textEl.setAttribute('rotation', '0 180 0');
  43709. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  43710. } else {
  43711. textEl.setAttribute('position', '0 0 -0.75');
  43712. textEl.setAttribute('rotation', '0 0 0');
  43713. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  43714. }
  43715. el.getObject3D('mesh').visible = false;
  43716. this.semiSphereEl.setAttribute('visible', true);
  43717. this.peekCameraPortalOrientation = cameraPortalOrientation;
  43718. } else {
  43719. // Calculate wich side the camera is approaching the camera (back / front).
  43720. // Adjust text orientation based on camera position.
  43721. if (cameraPortalOrientation <= 0.0) {
  43722. textEl.setAttribute('rotation', '0 180 0');
  43723. } else {
  43724. textEl.setAttribute('rotation', '0 0 0');
  43725. }
  43726. textEl.setAttribute('text', 'width', 5);
  43727. textEl.setAttribute('position', '0 1.5 0');
  43728. el.getObject3D('mesh').visible = true;
  43729. this.semiSphereEl.setAttribute('visible', false);
  43730. this.peekCameraPortalOrientation = undefined;
  43731. }
  43732. if (this.previousQuaternion) {
  43733. object3D.quaternion.copy(this.previousQuaternion);
  43734. this.previousQuaternion = undefined;
  43735. }
  43736. }
  43737. };
  43738. })(),
  43739. hideAll: function () {
  43740. var el = this.el;
  43741. var hiddenEls = this.hiddenEls;
  43742. var self = this;
  43743. if (hiddenEls.length > 0) { return; }
  43744. el.sceneEl.object3D.traverse(function (object) {
  43745. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  43746. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  43747. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  43748. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  43749. object.el === self.semiSphereEl) {
  43750. return;
  43751. }
  43752. object.el.setAttribute('visible', false);
  43753. hiddenEls.push(object.el);
  43754. });
  43755. },
  43756. showAll: function () {
  43757. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  43758. this.hiddenEls = [];
  43759. },
  43760. /**
  43761. * Calculate whether the camera faces the front or back face of the portal.
  43762. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  43763. */
  43764. calculateCameraPortalOrientation: (function () {
  43765. var mat4 = new THREE.Matrix4();
  43766. var cameraPosition = new THREE.Vector3();
  43767. var portalNormal = new THREE.Vector3(0, 0, 1);
  43768. var portalPosition = new THREE.Vector3(0, 0, 0);
  43769. return function () {
  43770. var el = this.el;
  43771. var camera = el.sceneEl.camera;
  43772. // Reset tmp variables.
  43773. cameraPosition.set(0, 0, 0);
  43774. portalNormal.set(0, 0, 1);
  43775. portalPosition.set(0, 0, 0);
  43776. // Apply portal orientation to the normal.
  43777. el.object3D.matrixWorld.extractRotation(mat4);
  43778. portalNormal.applyMatrix4(mat4);
  43779. // Calculate portal world position.
  43780. el.object3D.updateMatrixWorld();
  43781. el.object3D.localToWorld(portalPosition);
  43782. // Calculate camera world position.
  43783. camera.parent.parent.updateMatrixWorld();
  43784. camera.parent.updateMatrixWorld();
  43785. camera.updateMatrixWorld();
  43786. camera.localToWorld(cameraPosition);
  43787. // Calculate vector from portal to camera.
  43788. // (portal) -------> (camera)
  43789. cameraPosition.sub(portalPosition).normalize();
  43790. portalNormal.normalize();
  43791. // Side where camera approaches portal is given by sign of dot product of portal normal
  43792. // and portal to camera vectors.
  43793. return Math.sign(portalNormal.dot(cameraPosition));
  43794. };
  43795. })(),
  43796. remove: function () {
  43797. this.removeEventListener();
  43798. }
  43799. });
  43800. /* eslint-disable */
  43801. registerShader('portal', {
  43802. schema: {
  43803. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  43804. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  43805. pano: {type: 'map', is: 'uniform'},
  43806. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  43807. },
  43808. vertexShader: [
  43809. 'vec3 portalPosition;',
  43810. 'varying vec3 vWorldPosition;',
  43811. 'varying float vDistanceToCenter;',
  43812. 'varying float vDistance;',
  43813. 'void main() {',
  43814. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  43815. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  43816. 'vDistance = length(portalPosition - cameraPosition);',
  43817. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  43818. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  43819. '}'
  43820. ].join('\n'),
  43821. fragmentShader: [
  43822. '#define RECIPROCAL_PI2 0.15915494',
  43823. 'uniform sampler2D pano;',
  43824. 'uniform vec3 strokeColor;',
  43825. 'uniform vec3 backgroundColor;',
  43826. 'uniform float borderEnabled;',
  43827. 'varying float vDistanceToCenter;',
  43828. 'varying float vDistance;',
  43829. 'varying vec3 vWorldPosition;',
  43830. 'void main() {',
  43831. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  43832. 'vec2 sampleUV;',
  43833. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  43834. 'sampleUV.y = saturate(direction.y * 0.5 + 0.5);',
  43835. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  43836. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  43837. 'gl_FragColor = vec4(strokeColor, 1.0);',
  43838. '} else {',
  43839. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  43840. '}',
  43841. '}'
  43842. ].join('\n')
  43843. });
  43844. /* eslint-enable */
  43845. },{"../core/component":102,"../core/shader":111,"../lib/three":150}],66:[function(_dereq_,module,exports){
  43846. var registerComponent = _dereq_('../core/component').registerComponent;
  43847. var THREE = _dereq_('../lib/three');
  43848. var utils = _dereq_('../utils/');
  43849. var bind = utils.bind;
  43850. var PolyfillControls = _dereq_('../utils').device.PolyfillControls;
  43851. // To avoid recalculation at every mouse movement tick
  43852. var GRABBING_CLASS = 'a-grabbing';
  43853. var PI_2 = Math.PI / 2;
  43854. var checkHasPositionalTracking = utils.device.checkHasPositionalTracking;
  43855. /**
  43856. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  43857. */
  43858. module.exports.Component = registerComponent('look-controls', {
  43859. dependencies: ['position', 'rotation'],
  43860. schema: {
  43861. enabled: {default: true},
  43862. hmdEnabled: {default: true},
  43863. pointerLockEnabled: {default: false},
  43864. reverseMouseDrag: {default: false},
  43865. touchEnabled: {default: true}
  43866. },
  43867. init: function () {
  43868. this.previousHMDPosition = new THREE.Vector3();
  43869. this.hmdQuaternion = new THREE.Quaternion();
  43870. this.hmdEuler = new THREE.Euler();
  43871. this.position = new THREE.Vector3();
  43872. // To save / restore camera pose
  43873. this.savedRotation = new THREE.Vector3();
  43874. this.savedPosition = new THREE.Vector3();
  43875. this.polyfillObject = new THREE.Object3D();
  43876. this.polyfillControls = new PolyfillControls(this.polyfillObject);
  43877. this.rotation = {};
  43878. this.deltaRotation = {};
  43879. this.savedPose = null;
  43880. this.pointerLocked = false;
  43881. this.setupMouseControls();
  43882. this.bindMethods();
  43883. this.savedPose = {
  43884. position: new THREE.Vector3(),
  43885. rotation: new THREE.Euler()
  43886. };
  43887. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  43888. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  43889. },
  43890. update: function (oldData) {
  43891. var data = this.data;
  43892. // Disable grab cursor classes if no longer enabled.
  43893. if (data.enabled !== oldData.enabled) {
  43894. this.updateGrabCursor(data.enabled);
  43895. }
  43896. // Reset pitch and yaw if disabling HMD.
  43897. if (oldData && !data.hmdEnabled && !oldData.hmdEnabled) {
  43898. this.pitchObject.rotation.set(0, 0, 0);
  43899. this.yawObject.rotation.set(0, 0, 0);
  43900. }
  43901. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  43902. this.removeEventListeners();
  43903. this.addEventListeners();
  43904. if (this.pointerLocked) { document.exitPointerLock(); }
  43905. }
  43906. },
  43907. tick: function (t) {
  43908. var data = this.data;
  43909. if (!data.enabled) { return; }
  43910. this.updateOrientation();
  43911. },
  43912. play: function () {
  43913. this.addEventListeners();
  43914. },
  43915. pause: function () {
  43916. this.removeEventListeners();
  43917. },
  43918. remove: function () {
  43919. this.removeEventListeners();
  43920. },
  43921. bindMethods: function () {
  43922. this.onMouseDown = bind(this.onMouseDown, this);
  43923. this.onMouseMove = bind(this.onMouseMove, this);
  43924. this.onMouseUp = bind(this.onMouseUp, this);
  43925. this.onTouchStart = bind(this.onTouchStart, this);
  43926. this.onTouchMove = bind(this.onTouchMove, this);
  43927. this.onTouchEnd = bind(this.onTouchEnd, this);
  43928. this.onEnterVR = bind(this.onEnterVR, this);
  43929. this.onExitVR = bind(this.onExitVR, this);
  43930. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  43931. this.onPointerLockError = bind(this.onPointerLockError, this);
  43932. },
  43933. /**
  43934. * Set up states and Object3Ds needed to store rotation data.
  43935. */
  43936. setupMouseControls: function () {
  43937. this.mouseDown = false;
  43938. this.pitchObject = new THREE.Object3D();
  43939. this.yawObject = new THREE.Object3D();
  43940. this.yawObject.position.y = 10;
  43941. this.yawObject.add(this.pitchObject);
  43942. },
  43943. /**
  43944. * Add mouse and touch event listeners to canvas.
  43945. */
  43946. addEventListeners: function () {
  43947. var sceneEl = this.el.sceneEl;
  43948. var canvasEl = sceneEl.canvas;
  43949. // Wait for canvas to load.
  43950. if (!canvasEl) {
  43951. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  43952. return;
  43953. }
  43954. // Mouse events.
  43955. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  43956. window.addEventListener('mousemove', this.onMouseMove, false);
  43957. window.addEventListener('mouseup', this.onMouseUp, false);
  43958. // Touch events.
  43959. canvasEl.addEventListener('touchstart', this.onTouchStart);
  43960. window.addEventListener('touchmove', this.onTouchMove);
  43961. window.addEventListener('touchend', this.onTouchEnd);
  43962. // sceneEl events.
  43963. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  43964. sceneEl.addEventListener('exit-vr', this.onExitVR);
  43965. // Pointer Lock events.
  43966. if (this.data.pointerLockEnabled) {
  43967. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  43968. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  43969. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  43970. }
  43971. },
  43972. /**
  43973. * Remove mouse and touch event listeners from canvas.
  43974. */
  43975. removeEventListeners: function () {
  43976. var sceneEl = this.el.sceneEl;
  43977. var canvasEl = sceneEl && sceneEl.canvas;
  43978. if (!canvasEl) { return; }
  43979. // Mouse events.
  43980. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  43981. window.removeEventListener('mousemove', this.onMouseMove);
  43982. window.removeEventListener('mouseup', this.onMouseUp);
  43983. // Touch events.
  43984. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  43985. window.removeEventListener('touchmove', this.onTouchMove);
  43986. window.removeEventListener('touchend', this.onTouchEnd);
  43987. // sceneEl events.
  43988. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  43989. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  43990. // Pointer Lock events.
  43991. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  43992. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  43993. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  43994. },
  43995. /**
  43996. * Update orientation for mobile, mouse drag, and headset.
  43997. * Mouse-drag only enabled if HMD is not active.
  43998. */
  43999. updateOrientation: function () {
  44000. var el = this.el;
  44001. var hmdEuler = this.hmdEuler;
  44002. var pitchObject = this.pitchObject;
  44003. var yawObject = this.yawObject;
  44004. var sceneEl = this.el.sceneEl;
  44005. // In VR mode, THREE is in charge of updating the camera rotation.
  44006. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) { return; }
  44007. // Calculate polyfilled HMD quaternion.
  44008. this.polyfillControls.update();
  44009. hmdEuler.setFromQuaternion(this.polyfillObject.quaternion, 'YXZ');
  44010. // On mobile, do camera rotation with touch events and sensors.
  44011. el.object3D.rotation.x = hmdEuler.x + pitchObject.rotation.x;
  44012. el.object3D.rotation.y = hmdEuler.y + yawObject.rotation.y;
  44013. },
  44014. /**
  44015. * Translate mouse drag into rotation.
  44016. *
  44017. * Dragging up and down rotates the camera around the X-axis (yaw).
  44018. * Dragging left and right rotates the camera around the Y-axis (pitch).
  44019. */
  44020. onMouseMove: function (event) {
  44021. var direction;
  44022. var movementX;
  44023. var movementY;
  44024. var pitchObject = this.pitchObject;
  44025. var previousMouseEvent = this.previousMouseEvent;
  44026. var yawObject = this.yawObject;
  44027. // Not dragging or not enabled.
  44028. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  44029. // Calculate delta.
  44030. if (this.pointerLocked) {
  44031. movementX = event.movementX || event.mozMovementX || 0;
  44032. movementY = event.movementY || event.mozMovementY || 0;
  44033. } else {
  44034. movementX = event.screenX - previousMouseEvent.screenX;
  44035. movementY = event.screenY - previousMouseEvent.screenY;
  44036. }
  44037. this.previousMouseEvent = event;
  44038. // Calculate rotation.
  44039. direction = this.data.reverseMouseDrag ? 1 : -1;
  44040. yawObject.rotation.y += movementX * 0.002 * direction;
  44041. pitchObject.rotation.x += movementY * 0.002 * direction;
  44042. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  44043. },
  44044. /**
  44045. * Register mouse down to detect mouse drag.
  44046. */
  44047. onMouseDown: function (evt) {
  44048. if (!this.data.enabled) { return; }
  44049. // Handle only primary button.
  44050. if (evt.button !== 0) { return; }
  44051. var sceneEl = this.el.sceneEl;
  44052. var canvasEl = sceneEl && sceneEl.canvas;
  44053. this.mouseDown = true;
  44054. this.previousMouseEvent = evt;
  44055. document.body.classList.add(GRABBING_CLASS);
  44056. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  44057. if (canvasEl.requestPointerLock) {
  44058. canvasEl.requestPointerLock();
  44059. } else if (canvasEl.mozRequestPointerLock) {
  44060. canvasEl.mozRequestPointerLock();
  44061. }
  44062. }
  44063. },
  44064. /**
  44065. * Register mouse up to detect release of mouse drag.
  44066. */
  44067. onMouseUp: function () {
  44068. this.mouseDown = false;
  44069. document.body.classList.remove(GRABBING_CLASS);
  44070. },
  44071. /**
  44072. * Register touch down to detect touch drag.
  44073. */
  44074. onTouchStart: function (evt) {
  44075. if (evt.touches.length !== 1 || !this.data.touchEnabled) { return; }
  44076. this.touchStart = {
  44077. x: evt.touches[0].pageX,
  44078. y: evt.touches[0].pageY
  44079. };
  44080. this.touchStarted = true;
  44081. },
  44082. /**
  44083. * Translate touch move to Y-axis rotation.
  44084. */
  44085. onTouchMove: function (evt) {
  44086. var canvas = this.el.sceneEl.canvas;
  44087. var deltaY;
  44088. var yawObject = this.yawObject;
  44089. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  44090. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  44091. // Limit touch orientaion to to yaw (y axis).
  44092. yawObject.rotation.y -= deltaY * 0.5;
  44093. this.touchStart = {
  44094. x: evt.touches[0].pageX,
  44095. y: evt.touches[0].pageY
  44096. };
  44097. },
  44098. /**
  44099. * Register touch end to detect release of touch drag.
  44100. */
  44101. onTouchEnd: function () {
  44102. this.touchStarted = false;
  44103. },
  44104. /**
  44105. * Save pose.
  44106. */
  44107. onEnterVR: function () {
  44108. this.saveCameraPose();
  44109. },
  44110. /**
  44111. * Restore the pose.
  44112. */
  44113. onExitVR: function () {
  44114. this.restoreCameraPose();
  44115. this.previousHMDPosition.set(0, 0, 0);
  44116. },
  44117. /**
  44118. * Update Pointer Lock state.
  44119. */
  44120. onPointerLockChange: function () {
  44121. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  44122. },
  44123. /**
  44124. * Recover from Pointer Lock error.
  44125. */
  44126. onPointerLockError: function () {
  44127. this.pointerLocked = false;
  44128. },
  44129. /**
  44130. * Toggle the feature of showing/hiding the grab cursor.
  44131. */
  44132. updateGrabCursor: function (enabled) {
  44133. var sceneEl = this.el.sceneEl;
  44134. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  44135. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  44136. if (!sceneEl.canvas) {
  44137. if (enabled) {
  44138. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  44139. } else {
  44140. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  44141. }
  44142. return;
  44143. }
  44144. if (enabled) {
  44145. enableGrabCursor();
  44146. return;
  44147. }
  44148. disableGrabCursor();
  44149. },
  44150. /**
  44151. * Save camera pose before entering VR to restore later if exiting.
  44152. */
  44153. saveCameraPose: function () {
  44154. var el = this.el;
  44155. var hasPositionalTracking = this.hasPositionalTracking !== undefined
  44156. ? this.hasPositionalTracking
  44157. : checkHasPositionalTracking();
  44158. if (this.hasSavedPose || !hasPositionalTracking) { return; }
  44159. this.savedPose.position.copy(el.object3D.position);
  44160. this.savedPose.rotation.copy(el.object3D.rotation);
  44161. this.hasSavedPose = true;
  44162. },
  44163. /**
  44164. * Reset camera pose to before entering VR.
  44165. */
  44166. restoreCameraPose: function () {
  44167. var el = this.el;
  44168. var savedPose = this.savedPose;
  44169. var hasPositionalTracking = this.hasPositionalTracking !== undefined
  44170. ? this.hasPositionalTracking
  44171. : checkHasPositionalTracking();
  44172. if (!this.hasSavedPose || !hasPositionalTracking) { return; }
  44173. // Reset camera orientation.
  44174. el.object3D.position.copy(savedPose.position);
  44175. el.object3D.rotation.copy(savedPose.rotation);
  44176. this.hasSavedPose = false;
  44177. }
  44178. });
  44179. },{"../core/component":102,"../lib/three":150,"../utils":172,"../utils/":172}],67:[function(_dereq_,module,exports){
  44180. /* global Promise */
  44181. var utils = _dereq_('../utils/');
  44182. var component = _dereq_('../core/component');
  44183. var THREE = _dereq_('../lib/three');
  44184. var shader = _dereq_('../core/shader');
  44185. var error = utils.debug('components:material:error');
  44186. var registerComponent = component.registerComponent;
  44187. var shaders = shader.shaders;
  44188. var shaderNames = shader.shaderNames;
  44189. /**
  44190. * Material component.
  44191. *
  44192. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  44193. * three.js's implementation of PBR. Another standard shading model is `flat` which
  44194. * uses MeshBasicMaterial.
  44195. */
  44196. module.exports.Component = registerComponent('material', {
  44197. schema: {
  44198. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  44199. depthTest: {default: true},
  44200. depthWrite: {default: true},
  44201. flatShading: {default: false},
  44202. npot: {default: false},
  44203. offset: {type: 'vec2', default: {x: 0, y: 0}},
  44204. opacity: {default: 1.0, min: 0.0, max: 1.0},
  44205. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  44206. shader: {default: 'standard', oneOf: shaderNames},
  44207. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  44208. transparent: {default: false},
  44209. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  44210. visible: {default: true},
  44211. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']}
  44212. },
  44213. init: function () {
  44214. this.material = null;
  44215. },
  44216. /**
  44217. * Update or create material.
  44218. *
  44219. * @param {object|null} oldData
  44220. */
  44221. update: function (oldData) {
  44222. var data = this.data;
  44223. if (!this.shader || data.shader !== oldData.shader) {
  44224. this.updateShader(data.shader);
  44225. }
  44226. this.shader.update(this.data);
  44227. this.updateMaterial(oldData);
  44228. },
  44229. updateSchema: function (data) {
  44230. var newShader = data.shader;
  44231. var currentShader = this.data && this.data.shader;
  44232. var shader = newShader || currentShader;
  44233. var schema = shaders[shader] && shaders[shader].schema;
  44234. if (!schema) { error('Unknown shader schema ' + shader); }
  44235. if (currentShader && newShader === currentShader) { return; }
  44236. this.extendSchema(schema);
  44237. this.updateBehavior();
  44238. },
  44239. updateBehavior: function () {
  44240. var schema = this.schema;
  44241. var self = this;
  44242. var sceneEl = this.el.sceneEl;
  44243. var tickProperties = {};
  44244. var tick = function (time, delta) {
  44245. Object.keys(tickProperties).forEach(function update (key) {
  44246. tickProperties[key] = time;
  44247. });
  44248. self.shader.update(tickProperties);
  44249. };
  44250. this.tick = undefined;
  44251. Object.keys(schema).forEach(function (key) {
  44252. if (schema[key].type === 'time') {
  44253. self.tick = tick;
  44254. tickProperties[key] = true;
  44255. }
  44256. });
  44257. if (!sceneEl) { return; }
  44258. if (!this.tick) {
  44259. sceneEl.removeBehavior(this);
  44260. } else {
  44261. sceneEl.addBehavior(this);
  44262. }
  44263. },
  44264. updateShader: function (shaderName) {
  44265. var data = this.data;
  44266. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  44267. var shaderInstance;
  44268. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  44269. // Get material from A-Frame shader.
  44270. shaderInstance = this.shader = new Shader();
  44271. shaderInstance.el = this.el;
  44272. shaderInstance.init(data);
  44273. this.setMaterial(shaderInstance.material);
  44274. this.updateSchema(data);
  44275. },
  44276. /**
  44277. * Set and update base material properties.
  44278. * Set `needsUpdate` when needed.
  44279. */
  44280. updateMaterial: function (oldData) {
  44281. var data = this.data;
  44282. var material = this.material;
  44283. // Base material properties.
  44284. material.alphaTest = data.alphaTest;
  44285. material.depthTest = data.depthTest !== false;
  44286. material.depthWrite = data.depthWrite !== false;
  44287. material.opacity = data.opacity;
  44288. material.flatShading = data.flatShading;
  44289. material.side = parseSide(data.side);
  44290. material.transparent = data.transparent !== false || data.opacity < 1.0;
  44291. material.vertexColors = parseVertexColors(data.vertexColors);
  44292. material.visible = data.visible;
  44293. material.blending = parseBlending(data.blending);
  44294. // Check if material needs update.
  44295. if (Object.keys(oldData).length &&
  44296. (oldData.alphaTest !== data.alphaTest ||
  44297. oldData.side !== data.side ||
  44298. oldData.vertexColors !== data.vertexColors)) {
  44299. material.needsUpdate = true;
  44300. }
  44301. },
  44302. /**
  44303. * Remove material on remove (callback).
  44304. * Dispose of it from memory and unsubscribe from scene updates.
  44305. */
  44306. remove: function () {
  44307. var defaultMaterial = new THREE.MeshBasicMaterial();
  44308. var material = this.material;
  44309. var object3D = this.el.getObject3D('mesh');
  44310. if (object3D) { object3D.material = defaultMaterial; }
  44311. disposeMaterial(material, this.system);
  44312. },
  44313. /**
  44314. * (Re)create new material. Has side-effects of setting `this.material` and updating
  44315. * material registration in scene.
  44316. *
  44317. * @param {object} data - Material component data.
  44318. * @param {object} type - Material type to create.
  44319. * @returns {object} Material.
  44320. */
  44321. setMaterial: function (material) {
  44322. var el = this.el;
  44323. var mesh;
  44324. var system = this.system;
  44325. if (this.material) { disposeMaterial(this.material, system); }
  44326. this.material = material;
  44327. system.registerMaterial(material);
  44328. // Set on mesh. If mesh does not exist, wait for it.
  44329. mesh = el.getObject3D('mesh');
  44330. if (mesh) {
  44331. mesh.material = material;
  44332. } else {
  44333. el.addEventListener('object3dset', function waitForMesh (evt) {
  44334. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  44335. el.getObject3D('mesh').material = material;
  44336. el.removeEventListener('object3dset', waitForMesh);
  44337. });
  44338. }
  44339. }
  44340. });
  44341. /**
  44342. * Return a three.js constant determining which material face sides to render
  44343. * based on the side parameter (passed as a component property).
  44344. *
  44345. * @param {string} [side=front] - `front`, `back`, or `double`.
  44346. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  44347. */
  44348. function parseSide (side) {
  44349. switch (side) {
  44350. case 'back': {
  44351. return THREE.BackSide;
  44352. }
  44353. case 'double': {
  44354. return THREE.DoubleSide;
  44355. }
  44356. default: {
  44357. // Including case `front`.
  44358. return THREE.FrontSide;
  44359. }
  44360. }
  44361. }
  44362. /**
  44363. * Return a three.js constant determining vertex coloring.
  44364. */
  44365. function parseVertexColors (coloring) {
  44366. switch (coloring) {
  44367. case 'face': {
  44368. return THREE.FaceColors;
  44369. }
  44370. case 'vertex': {
  44371. return THREE.VertexColors;
  44372. }
  44373. default: {
  44374. return THREE.NoColors;
  44375. }
  44376. }
  44377. }
  44378. /**
  44379. * Return a three.js constant determining blending
  44380. *
  44381. * @param {string} [blending=normal]
  44382. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  44383. * @returns {number}
  44384. */
  44385. function parseBlending (blending) {
  44386. switch (blending) {
  44387. case 'none': {
  44388. return THREE.NoBlending;
  44389. }
  44390. case 'additive': {
  44391. return THREE.AdditiveBlending;
  44392. }
  44393. case 'subtractive': {
  44394. return THREE.SubtractiveBlending;
  44395. }
  44396. case 'multiply': {
  44397. return THREE.MultiplyBlending;
  44398. }
  44399. default: {
  44400. return THREE.NormalBlending;
  44401. }
  44402. }
  44403. }
  44404. /**
  44405. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  44406. */
  44407. function disposeMaterial (material, system) {
  44408. material.dispose();
  44409. system.unregisterMaterial(material);
  44410. }
  44411. },{"../core/component":102,"../core/shader":111,"../lib/three":150,"../utils/":172}],68:[function(_dereq_,module,exports){
  44412. var debug = _dereq_('../utils/debug');
  44413. var registerComponent = _dereq_('../core/component').registerComponent;
  44414. var THREE = _dereq_('../lib/three');
  44415. var warn = debug('components:obj-model:warn');
  44416. module.exports.Component = registerComponent('obj-model', {
  44417. schema: {
  44418. mtl: {type: 'model'},
  44419. obj: {type: 'model'}
  44420. },
  44421. init: function () {
  44422. this.model = null;
  44423. this.objLoader = new THREE.OBJLoader();
  44424. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  44425. // Allow cross-origin images to be loaded.
  44426. this.mtlLoader.crossOrigin = '';
  44427. },
  44428. update: function () {
  44429. var data = this.data;
  44430. if (!data.obj) { return; }
  44431. this.remove();
  44432. this.loadObj(data.obj, data.mtl);
  44433. },
  44434. remove: function () {
  44435. if (!this.model) { return; }
  44436. this.el.removeObject3D('mesh');
  44437. },
  44438. loadObj: function (objUrl, mtlUrl) {
  44439. var self = this;
  44440. var el = this.el;
  44441. var mtlLoader = this.mtlLoader;
  44442. var objLoader = this.objLoader;
  44443. if (mtlUrl) {
  44444. // .OBJ with an .MTL.
  44445. if (el.hasAttribute('material')) {
  44446. warn('Material component properties are ignored when a .MTL is provided');
  44447. }
  44448. mtlLoader.setTexturePath(mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1));
  44449. mtlLoader.load(mtlUrl, function (materials) {
  44450. materials.preload();
  44451. objLoader.setMaterials(materials);
  44452. objLoader.load(objUrl, function (objModel) {
  44453. self.model = objModel;
  44454. el.setObject3D('mesh', objModel);
  44455. el.emit('model-loaded', {format: 'obj', model: objModel});
  44456. });
  44457. });
  44458. return;
  44459. }
  44460. // .OBJ only.
  44461. objLoader.load(objUrl, function loadObjOnly (objModel) {
  44462. // Apply material.
  44463. var material = el.components.material;
  44464. if (material) {
  44465. objModel.traverse(function (child) {
  44466. if (child instanceof THREE.Mesh) {
  44467. child.material = material.material;
  44468. }
  44469. });
  44470. }
  44471. self.model = objModel;
  44472. el.setObject3D('mesh', objModel);
  44473. el.emit('model-loaded', {format: 'obj', model: objModel});
  44474. });
  44475. }
  44476. });
  44477. },{"../core/component":102,"../lib/three":150,"../utils/debug":168}],69:[function(_dereq_,module,exports){
  44478. var registerComponent = _dereq_('../core/component').registerComponent;
  44479. var bind = _dereq_('../utils/bind');
  44480. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  44481. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  44482. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  44483. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  44484. var GAMEPAD_ID_PREFIX = 'Oculus Go';
  44485. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  44486. /**
  44487. * Oculus Go controls.
  44488. * Interface with Oculus Go controller and map Gamepad events to
  44489. * controller buttons: trackpad, trigger
  44490. * Load a controller model and highlight the pressed buttons.
  44491. */
  44492. module.exports.Component = registerComponent('oculus-go-controls', {
  44493. schema: {
  44494. hand: {default: ''}, // This informs the degenerate arm model.
  44495. buttonColor: {type: 'color', default: '#FFFFFF'},
  44496. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  44497. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  44498. model: {default: true},
  44499. rotationOffset: {default: 0},
  44500. armModel: {default: true}
  44501. },
  44502. /**
  44503. * Button IDs:
  44504. * 0 - trackpad
  44505. * 1 - trigger
  44506. */
  44507. mapping: {
  44508. axes: {trackpad: [0, 1]},
  44509. buttons: ['trackpad', 'trigger']
  44510. },
  44511. bindMethods: function () {
  44512. this.onModelLoaded = bind(this.onModelLoaded, this);
  44513. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  44514. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  44515. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  44516. this.onAxisMoved = bind(this.onAxisMoved, this);
  44517. },
  44518. init: function () {
  44519. var self = this;
  44520. this.animationActive = 'pointing';
  44521. this.onButtonChanged = bind(this.onButtonChanged, this);
  44522. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  44523. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  44524. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  44525. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  44526. this.onAxisMoved = bind(this.onAxisMoved, this);
  44527. this.controllerPresent = false;
  44528. this.lastControllerCheck = 0;
  44529. this.bindMethods();
  44530. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  44531. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  44532. },
  44533. addEventListeners: function () {
  44534. var el = this.el;
  44535. el.addEventListener('buttonchanged', this.onButtonChanged);
  44536. el.addEventListener('buttondown', this.onButtonDown);
  44537. el.addEventListener('buttonup', this.onButtonUp);
  44538. el.addEventListener('touchstart', this.onButtonTouchStart);
  44539. el.addEventListener('touchend', this.onButtonTouchEnd);
  44540. el.addEventListener('model-loaded', this.onModelLoaded);
  44541. el.addEventListener('axismove', this.onAxisMoved);
  44542. this.controllerEventsActive = true;
  44543. },
  44544. removeEventListeners: function () {
  44545. var el = this.el;
  44546. el.removeEventListener('buttonchanged', this.onButtonChanged);
  44547. el.removeEventListener('buttondown', this.onButtonDown);
  44548. el.removeEventListener('buttonup', this.onButtonUp);
  44549. el.removeEventListener('touchstart', this.onButtonTouchStart);
  44550. el.removeEventListener('touchend', this.onButtonTouchEnd);
  44551. el.removeEventListener('model-loaded', this.onModelLoaded);
  44552. el.removeEventListener('axismove', this.onAxisMoved);
  44553. this.controllerEventsActive = false;
  44554. },
  44555. checkIfControllerPresent: function () {
  44556. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  44557. this.data.hand ? {hand: this.data.hand} : {});
  44558. },
  44559. play: function () {
  44560. this.checkIfControllerPresent();
  44561. this.addControllersUpdateListener();
  44562. },
  44563. pause: function () {
  44564. this.removeEventListeners();
  44565. this.removeControllersUpdateListener();
  44566. },
  44567. injectTrackedControls: function () {
  44568. var el = this.el;
  44569. var data = this.data;
  44570. el.setAttribute('tracked-controls', {
  44571. armModel: data.armModel,
  44572. idPrefix: GAMEPAD_ID_PREFIX,
  44573. rotationOffset: data.rotationOffset
  44574. });
  44575. if (!this.data.model) { return; }
  44576. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  44577. },
  44578. addControllersUpdateListener: function () {
  44579. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  44580. },
  44581. removeControllersUpdateListener: function () {
  44582. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  44583. },
  44584. onControllersUpdate: function () {
  44585. this.checkIfControllerPresent();
  44586. },
  44587. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  44588. onModelLoaded: function (evt) {
  44589. var controllerObject3D = evt.detail.model;
  44590. var buttonMeshes;
  44591. if (!this.data.model) { return; }
  44592. buttonMeshes = this.buttonMeshes = {};
  44593. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  44594. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  44595. },
  44596. onButtonChanged: function (evt) {
  44597. var button = this.mapping.buttons[evt.detail.id];
  44598. if (!button) return;
  44599. // Pass along changed event with button state, using button mapping for convenience.
  44600. this.el.emit(button + 'changed', evt.detail.state);
  44601. },
  44602. onAxisMoved: function (evt) {
  44603. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  44604. },
  44605. updateModel: function (buttonName, evtName) {
  44606. if (!this.data.model) { return; }
  44607. this.updateButtonModel(buttonName, evtName);
  44608. },
  44609. updateButtonModel: function (buttonName, state) {
  44610. var buttonMeshes = this.buttonMeshes;
  44611. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  44612. var color;
  44613. switch (state) {
  44614. case 'down':
  44615. color = this.data.buttonHighlightColor;
  44616. break;
  44617. case 'touchstart':
  44618. color = this.data.buttonTouchedColor;
  44619. break;
  44620. default:
  44621. color = this.data.buttonColor;
  44622. }
  44623. buttonMeshes[buttonName].material.color.set(color);
  44624. }
  44625. });
  44626. },{"../core/component":102,"../utils/bind":166,"../utils/tracked-controls":178}],70:[function(_dereq_,module,exports){
  44627. var bind = _dereq_('../utils/bind');
  44628. var registerComponent = _dereq_('../core/component').registerComponent;
  44629. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  44630. var THREE = _dereq_('../lib/three');
  44631. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  44632. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  44633. var TOUCH_CONTROLLER_MODEL_URL = {
  44634. left: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  44635. right: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf'
  44636. };
  44637. var GAMEPAD_ID_PREFIX = 'Oculus Touch';
  44638. var DEFAULT_MODEL_PIVOT_OFFSET = new THREE.Vector3(0, 0, -0.053);
  44639. var RAY_ORIGIN = {
  44640. left: {origin: {x: 0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  44641. right: {origin: {x: -0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}}
  44642. };
  44643. /**
  44644. * Oculus Touch controls.
  44645. * Interface with Oculus Touch controllers and map Gamepad events to
  44646. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  44647. * Load a controller model and highlight the pressed buttons.
  44648. */
  44649. module.exports.Component = registerComponent('oculus-touch-controls', {
  44650. schema: {
  44651. hand: {default: 'left'},
  44652. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  44653. buttonTouchColor: {type: 'color', default: '#8AB'},
  44654. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  44655. model: {default: true},
  44656. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  44657. },
  44658. /**
  44659. * Button IDs:
  44660. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  44661. * 1 - trigger (with analog value, which goes up to 1)
  44662. * 2 - grip (with analog value, which goes up to 1)
  44663. * 3 - X (left) or A (right)
  44664. * 4 - Y (left) or B (right)
  44665. * 5 - surface (touch only)
  44666. */
  44667. mapping: {
  44668. left: {
  44669. axes: {thumbstick: [0, 1]},
  44670. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  44671. },
  44672. right: {
  44673. axes: {thumbstick: [0, 1]},
  44674. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  44675. }
  44676. },
  44677. bindMethods: function () {
  44678. this.onModelLoaded = bind(this.onModelLoaded, this);
  44679. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  44680. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  44681. this.onAxisMoved = bind(this.onAxisMoved, this);
  44682. },
  44683. init: function () {
  44684. var self = this;
  44685. this.onButtonChanged = bind(this.onButtonChanged, this);
  44686. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  44687. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  44688. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  44689. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  44690. this.controllerPresent = false;
  44691. this.lastControllerCheck = 0;
  44692. this.previousButtonValues = {};
  44693. this.bindMethods();
  44694. // Allow mock.
  44695. this.emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  44696. this.checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  44697. },
  44698. addEventListeners: function () {
  44699. var el = this.el;
  44700. el.addEventListener('buttonchanged', this.onButtonChanged);
  44701. el.addEventListener('buttondown', this.onButtonDown);
  44702. el.addEventListener('buttonup', this.onButtonUp);
  44703. el.addEventListener('touchstart', this.onButtonTouchStart);
  44704. el.addEventListener('touchend', this.onButtonTouchEnd);
  44705. el.addEventListener('axismove', this.onAxisMoved);
  44706. el.addEventListener('model-loaded', this.onModelLoaded);
  44707. this.controllerEventsActive = true;
  44708. },
  44709. removeEventListeners: function () {
  44710. var el = this.el;
  44711. el.removeEventListener('buttonchanged', this.onButtonChanged);
  44712. el.removeEventListener('buttondown', this.onButtonDown);
  44713. el.removeEventListener('buttonup', this.onButtonUp);
  44714. el.removeEventListener('touchstart', this.onButtonTouchStart);
  44715. el.removeEventListener('touchend', this.onButtonTouchEnd);
  44716. el.removeEventListener('axismove', this.onAxisMoved);
  44717. el.removeEventListener('model-loaded', this.onModelLoaded);
  44718. this.controllerEventsActive = false;
  44719. },
  44720. checkIfControllerPresent: function () {
  44721. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  44722. hand: this.data.hand
  44723. });
  44724. },
  44725. play: function () {
  44726. this.checkIfControllerPresent();
  44727. this.addControllersUpdateListener();
  44728. },
  44729. pause: function () {
  44730. this.removeEventListeners();
  44731. this.removeControllersUpdateListener();
  44732. },
  44733. loadModel: function () {
  44734. var data = this.data;
  44735. if (!data.model) { return; }
  44736. this.el.setAttribute('gltf-model', 'url(' + TOUCH_CONTROLLER_MODEL_URL[data.hand] + ')');
  44737. },
  44738. injectTrackedControls: function () {
  44739. var data = this.data;
  44740. this.el.setAttribute('tracked-controls', {
  44741. id: data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)',
  44742. controller: 0,
  44743. orientationOffset: data.orientationOffset
  44744. });
  44745. this.loadModel();
  44746. },
  44747. addControllersUpdateListener: function () {
  44748. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  44749. },
  44750. removeControllersUpdateListener: function () {
  44751. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  44752. },
  44753. onControllersUpdate: function () {
  44754. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  44755. this.checkIfControllerPresent();
  44756. },
  44757. onButtonChanged: function (evt) {
  44758. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  44759. var buttonMeshes = this.buttonMeshes;
  44760. var analogValue;
  44761. if (!button) { return; }
  44762. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  44763. // Update trigger and/or grip meshes, if any.
  44764. if (buttonMeshes) {
  44765. if (button === 'trigger' && buttonMeshes.trigger) {
  44766. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 24);
  44767. }
  44768. if (button === 'grip' && buttonMeshes.grip) {
  44769. buttonMeshes.grip.rotation.y = (this.data.hand === 'left' ? -1 : 1) * analogValue * (Math.PI / 60);
  44770. }
  44771. }
  44772. // Pass along changed event with button state, using the buttom mapping for convenience.
  44773. this.el.emit(button + 'changed', evt.detail.state);
  44774. },
  44775. onModelLoaded: function (evt) {
  44776. var controllerObject3D = evt.detail.model;
  44777. var buttonMeshes;
  44778. if (!this.data.model) { return; }
  44779. var leftHand = this.data.hand === 'left';
  44780. buttonMeshes = this.buttonMeshes = {};
  44781. buttonMeshes.grip = controllerObject3D.getObjectByName(leftHand ? 'buttonHand_oculus-touch-controller-left.004' : 'buttonHand_oculus-touch-controller-right.005');
  44782. buttonMeshes.thumbstick = controllerObject3D.getObjectByName(leftHand ? 'stick_oculus-touch-controller-left.007' : 'stick_oculus-touch-controller-right.004');
  44783. buttonMeshes.trigger = controllerObject3D.getObjectByName(leftHand ? 'buttonTrigger_oculus-touch-controller-left.005' : 'buttonTrigger_oculus-touch-controller-right.006');
  44784. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX_oculus-touch-controller-left.002');
  44785. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA_oculus-touch-controller-right.002');
  44786. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY_oculus-touch-controller-left.001');
  44787. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB_oculus-touch-controller-right.003');
  44788. // Offset pivot point
  44789. controllerObject3D.position.copy(DEFAULT_MODEL_PIVOT_OFFSET);
  44790. this.el.emit('controllermodelready', {
  44791. name: 'oculus-touch-controls',
  44792. model: this.data.model,
  44793. rayOrigin: RAY_ORIGIN[this.data.hand]
  44794. });
  44795. },
  44796. onAxisMoved: function (evt) {
  44797. this.emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  44798. },
  44799. updateModel: function (buttonName, evtName) {
  44800. if (!this.data.model) { return; }
  44801. this.updateButtonModel(buttonName, evtName);
  44802. },
  44803. updateButtonModel: function (buttonName, state) {
  44804. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  44805. var buttonMeshes = this.buttonMeshes;
  44806. if (!this.data.model) { return; }
  44807. if (buttonMeshes && buttonMeshes[buttonName]) {
  44808. buttonMeshes[buttonName].material.color.set(color);
  44809. }
  44810. }
  44811. });
  44812. },{"../core/component":102,"../lib/three":150,"../utils/bind":166,"../utils/tracked-controls":178}],71:[function(_dereq_,module,exports){
  44813. var registerComponent = _dereq_('../core/component').registerComponent;
  44814. module.exports.Component = registerComponent('position', {
  44815. schema: {type: 'vec3'},
  44816. update: function () {
  44817. var object3D = this.el.object3D;
  44818. var data = this.data;
  44819. object3D.position.set(data.x, data.y, data.z);
  44820. },
  44821. remove: function () {
  44822. // Pretty much for mixins.
  44823. this.el.object3D.position.set(0, 0, 0);
  44824. }
  44825. });
  44826. },{"../core/component":102}],72:[function(_dereq_,module,exports){
  44827. /* global MutationObserver */
  44828. var registerComponent = _dereq_('../core/component').registerComponent;
  44829. var THREE = _dereq_('../lib/three');
  44830. var utils = _dereq_('../utils/');
  44831. var warn = utils.debug('components:raycaster:warn');
  44832. // Defines selectors that should be 'safe' for the MutationObserver used to
  44833. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  44834. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  44835. // reliably detected and are therefore disallowed.
  44836. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  44837. // Configuration for the MutationObserver used to refresh the whitelist.
  44838. // Listens for addition/removal of elements and attributes within the scene.
  44839. var OBSERVER_CONFIG = {
  44840. childList: true,
  44841. attributes: true,
  44842. subtree: true
  44843. };
  44844. var EVENTS = {
  44845. INTERSECT: 'raycaster-intersected',
  44846. INTERSECTION: 'raycaster-intersection',
  44847. INTERSECT_CLEAR: 'raycaster-intersected-cleared',
  44848. INTERSECTION_CLEAR: 'raycaster-intersection-cleared'
  44849. };
  44850. /**
  44851. * Raycaster component.
  44852. *
  44853. * Pass options to three.js Raycaster including which objects to test.
  44854. * Poll for intersections.
  44855. * Emit event on origin entity and on target entity on intersect.
  44856. *
  44857. * @member {array} intersectedEls - List of currently intersected entities.
  44858. * @member {array} objects - Cached list of meshes to intersect.
  44859. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  44860. * @member {object} raycaster - three.js Raycaster.
  44861. */
  44862. module.exports.Component = registerComponent('raycaster', {
  44863. schema: {
  44864. autoRefresh: {default: true},
  44865. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  44866. enabled: {default: true},
  44867. far: {default: 1000},
  44868. interval: {default: 0},
  44869. near: {default: 0},
  44870. objects: {default: ''},
  44871. origin: {type: 'vec3'},
  44872. recursive: {default: true},
  44873. showLine: {default: false},
  44874. useWorldCoordinates: {default: false}
  44875. },
  44876. init: function () {
  44877. this.clearedIntersectedEls = [];
  44878. this.unitLineEndVec3 = new THREE.Vector3();
  44879. this.intersectedEls = [];
  44880. this.intersections = [];
  44881. this.newIntersectedEls = [];
  44882. this.newIntersections = [];
  44883. this.objects = [];
  44884. this.prevCheckTime = undefined;
  44885. this.prevIntersectedEls = [];
  44886. this.rawIntersections = [];
  44887. this.raycaster = new THREE.Raycaster();
  44888. this.updateOriginDirection();
  44889. this.setDirty = this.setDirty.bind(this);
  44890. this.updateLine = this.updateLine.bind(this);
  44891. this.observer = new MutationObserver(this.setDirty);
  44892. this.dirty = true;
  44893. this.lineEndVec3 = new THREE.Vector3();
  44894. this.otherLineEndVec3 = new THREE.Vector3();
  44895. this.lineData = {end: this.lineEndVec3};
  44896. this.getIntersection = this.getIntersection.bind(this);
  44897. this.intersectedDetail = {el: this.el, getIntersection: this.getIntersection};
  44898. this.intersectedClearedDetail = {el: this.el};
  44899. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  44900. this.intersectionDetail = {};
  44901. },
  44902. /**
  44903. * Create or update raycaster object.
  44904. */
  44905. update: function (oldData) {
  44906. var data = this.data;
  44907. var el = this.el;
  44908. var raycaster = this.raycaster;
  44909. // Set raycaster properties.
  44910. raycaster.far = data.far;
  44911. raycaster.near = data.near;
  44912. // Draw line.
  44913. if (data.showLine &&
  44914. (data.far !== oldData.far || data.origin !== oldData.origin ||
  44915. data.direction !== oldData.direction || !oldData.showLine)) {
  44916. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  44917. // adjust line length.
  44918. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  44919. this.drawLine();
  44920. }
  44921. if (!data.showLine && oldData.showLine) {
  44922. el.removeAttribute('line');
  44923. }
  44924. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  44925. warn('Selector "' + data.objects + '" may not update automatically with DOM changes.');
  44926. }
  44927. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  44928. data.autoRefresh
  44929. ? this.addEventListeners()
  44930. : this.removeEventListeners();
  44931. }
  44932. if (oldData.enabled && !data.enabled) { this.clearAllIntersections(); }
  44933. this.setDirty();
  44934. },
  44935. play: function () {
  44936. this.addEventListeners();
  44937. },
  44938. pause: function () {
  44939. this.removeEventListeners();
  44940. },
  44941. remove: function () {
  44942. if (this.data.showLine) {
  44943. this.el.removeAttribute('line');
  44944. }
  44945. this.clearAllIntersections();
  44946. },
  44947. addEventListeners: function () {
  44948. if (!this.data.autoRefresh) { return; }
  44949. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  44950. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  44951. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  44952. },
  44953. removeEventListeners: function () {
  44954. this.observer.disconnect();
  44955. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  44956. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  44957. },
  44958. /**
  44959. * Mark the object list as dirty, to be refreshed before next raycast.
  44960. */
  44961. setDirty: function () {
  44962. this.dirty = true;
  44963. },
  44964. /**
  44965. * Update list of objects to test for intersection.
  44966. */
  44967. refreshObjects: function () {
  44968. var data = this.data;
  44969. var els;
  44970. // If objects not defined, intersect with everything.
  44971. els = data.objects
  44972. ? this.el.sceneEl.querySelectorAll(data.objects)
  44973. : this.el.sceneEl.children;
  44974. this.objects = this.flattenObject3DMaps(els);
  44975. this.dirty = false;
  44976. },
  44977. /**
  44978. * Check for intersections and cleared intersections on an interval.
  44979. */
  44980. tick: function (time) {
  44981. var data = this.data;
  44982. var prevCheckTime = this.prevCheckTime;
  44983. // Only check for intersection if interval time has passed.
  44984. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  44985. // Update check time.
  44986. this.prevCheckTime = time;
  44987. this.checkIntersections();
  44988. },
  44989. /**
  44990. * Raycast for intersections and emit events for current and cleared inersections.
  44991. */
  44992. checkIntersections: function () {
  44993. var clearedIntersectedEls = this.clearedIntersectedEls;
  44994. var el = this.el;
  44995. var data = this.data;
  44996. var i;
  44997. var intersectedEls = this.intersectedEls;
  44998. var intersection;
  44999. var intersections = this.intersections;
  45000. var newIntersectedEls = this.newIntersectedEls;
  45001. var newIntersections = this.newIntersections;
  45002. var prevIntersectedEls = this.prevIntersectedEls;
  45003. var rawIntersections = this.rawIntersections;
  45004. if (!this.data.enabled) { return; }
  45005. // Refresh the object whitelist if needed.
  45006. if (this.dirty) { this.refreshObjects(); }
  45007. // Store old previously intersected entities.
  45008. copyArray(this.prevIntersectedEls, this.intersectedEls);
  45009. // Raycast.
  45010. this.updateOriginDirection();
  45011. rawIntersections.length = 0;
  45012. this.raycaster.intersectObjects(this.objects, data.recursive, rawIntersections);
  45013. // Only keep intersections against objects that have a reference to an entity.
  45014. intersections.length = 0;
  45015. intersectedEls.length = 0;
  45016. for (i = 0; i < rawIntersections.length; i++) {
  45017. intersection = rawIntersections[i];
  45018. // Don't intersect with own line.
  45019. if (data.showLine && intersection.object === el.getObject3D('line')) {
  45020. continue;
  45021. }
  45022. if (intersection.object.el) {
  45023. intersections.push(intersection);
  45024. intersectedEls.push(intersection.object.el);
  45025. }
  45026. }
  45027. // Get newly intersected entities.
  45028. newIntersections.length = 0;
  45029. newIntersectedEls.length = 0;
  45030. for (i = 0; i < intersections.length; i++) {
  45031. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  45032. newIntersections.push(intersections[i]);
  45033. newIntersectedEls.push(intersections[i].object.el);
  45034. }
  45035. }
  45036. // Emit intersection cleared on both entities per formerly intersected entity.
  45037. clearedIntersectedEls.length = 0;
  45038. for (i = 0; i < prevIntersectedEls.length; i++) {
  45039. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  45040. prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  45041. this.intersectedClearedDetail);
  45042. clearedIntersectedEls.push(prevIntersectedEls[i]);
  45043. }
  45044. if (clearedIntersectedEls.length) {
  45045. el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  45046. }
  45047. // Emit intersected on intersected entity per intersected entity.
  45048. for (i = 0; i < newIntersectedEls.length; i++) {
  45049. newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
  45050. }
  45051. // Emit all intersections at once on raycasting entity.
  45052. if (newIntersections.length) {
  45053. this.intersectionDetail.els = newIntersectedEls;
  45054. this.intersectionDetail.intersections = newIntersections;
  45055. el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
  45056. }
  45057. // Update line length.
  45058. setTimeout(this.updateLine);
  45059. },
  45060. updateLine: function () {
  45061. var el = this.el;
  45062. var intersections = this.intersections;
  45063. var lineLength;
  45064. if (this.data.showLine) {
  45065. if (intersections.length) {
  45066. if (intersections[0].object.el === el && intersections[1]) {
  45067. lineLength = intersections[1].distance;
  45068. } else {
  45069. lineLength = intersections[0].distance;
  45070. }
  45071. }
  45072. this.drawLine(lineLength);
  45073. }
  45074. },
  45075. /**
  45076. * Return the most recent intersection details for a given entity, if any.
  45077. * @param {AEntity} el
  45078. * @return {Object}
  45079. */
  45080. getIntersection: function (el) {
  45081. var i;
  45082. var intersection;
  45083. for (i = 0; i < this.intersections.length; i++) {
  45084. intersection = this.intersections[i];
  45085. if (intersection.object.el === el) { return intersection; }
  45086. }
  45087. return null;
  45088. },
  45089. /**
  45090. * Update origin and direction of raycaster using entity transforms and supplied origin or
  45091. * direction offsets.
  45092. */
  45093. updateOriginDirection: (function () {
  45094. var direction = new THREE.Vector3();
  45095. var originVec3 = new THREE.Vector3();
  45096. // Closure to make quaternion/vector3 objects private.
  45097. return function updateOriginDirection () {
  45098. var el = this.el;
  45099. var data = this.data;
  45100. if (data.useWorldCoordinates) {
  45101. this.raycaster.set(data.origin, data.direction);
  45102. return;
  45103. }
  45104. // Grab the position and rotation. (As a side effect, this updates el.object3D.matrixWorld.)
  45105. el.object3D.getWorldPosition(originVec3);
  45106. // If non-zero origin, translate the origin into world space.
  45107. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  45108. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  45109. }
  45110. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  45111. // provide. Apply the offset to the direction, then rotation from the object,
  45112. // and normalize.
  45113. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  45114. // Apply offset and direction, in world coordinates.
  45115. this.raycaster.set(originVec3, direction);
  45116. };
  45117. })(),
  45118. /**
  45119. * Create or update line to give raycaster visual representation.
  45120. * Customize the line through through line component.
  45121. * We draw the line in the raycaster component to customize the line to the
  45122. * raycaster's origin, direction, and far.
  45123. *
  45124. * Unlike the raycaster, we create the line as a child of the object. The line will
  45125. * be affected by the transforms of the objects, so we don't have to calculate transforms
  45126. * like we do with the raycaster.
  45127. *
  45128. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  45129. * point. If not provided, length will default to the max length, `raycaster.far`.
  45130. */
  45131. drawLine: function (length) {
  45132. var data = this.data;
  45133. var el = this.el;
  45134. var endVec3;
  45135. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  45136. endVec3 = this.lineData.end === this.lineEndVec3
  45137. ? this.otherLineEndVec3
  45138. : this.lineEndVec3;
  45139. // Treat Infinity as 1000m for the line.
  45140. if (length === undefined) {
  45141. length = data.far === Infinity ? 1000 : data.far;
  45142. }
  45143. // Update the length of the line if given. `unitLineEndVec3` is the direction
  45144. // given by data.direction, then we apply a scalar to give it a length.
  45145. this.lineData.start = data.origin;
  45146. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  45147. el.setAttribute('line', this.lineData);
  45148. },
  45149. /**
  45150. * Return A-Frame attachments of each element's object3D group (e.g., mesh).
  45151. * Children are flattened by one level, removing the THREE.Group wrapper,
  45152. * so that non-recursive raycasting remains useful.
  45153. *
  45154. * Only push children defined as component attachemnts (e.g., setObject3D),
  45155. * not actual children in the scene graph hierarchy.
  45156. *
  45157. * @param {Array<Element>} els
  45158. * @return {Array<THREE.Object3D>}
  45159. */
  45160. flattenObject3DMaps: function (els) {
  45161. var key;
  45162. var i;
  45163. var objects = this.objects;
  45164. // Push meshes and other attachments onto list of objects to intersect.
  45165. objects.length = 0;
  45166. for (i = 0; i < els.length; i++) {
  45167. if (els[i].object3D) {
  45168. for (key in els[i].object3DMap) {
  45169. objects.push(els[i].getObject3D(key));
  45170. }
  45171. }
  45172. }
  45173. return objects;
  45174. },
  45175. clearAllIntersections: function () {
  45176. var i;
  45177. for (i = 0; i < this.intersectedEls.length; i++) {
  45178. this.intersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  45179. this.intersectedClearedDetail);
  45180. }
  45181. copyArray(this.clearedIntersectedEls, this.intersectedEls);
  45182. this.intersectedEls.length = 0;
  45183. this.intersections.length = 0;
  45184. this.el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  45185. }
  45186. });
  45187. /**
  45188. * Copy contents of one array to another without allocating new array.
  45189. */
  45190. function copyArray (a, b) {
  45191. var i;
  45192. a.length = b.length;
  45193. for (i = 0; i < b.length; i++) {
  45194. a[i] = b[i];
  45195. }
  45196. }
  45197. },{"../core/component":102,"../lib/three":150,"../utils/":172}],73:[function(_dereq_,module,exports){
  45198. var degToRad = _dereq_('../lib/three').Math.degToRad;
  45199. var registerComponent = _dereq_('../core/component').registerComponent;
  45200. module.exports.Component = registerComponent('rotation', {
  45201. schema: {type: 'vec3'},
  45202. /**
  45203. * Updates object3D rotation.
  45204. */
  45205. update: function () {
  45206. var data = this.data;
  45207. var object3D = this.el.object3D;
  45208. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  45209. object3D.rotation.order = 'YXZ';
  45210. },
  45211. remove: function () {
  45212. // Pretty much for mixins.
  45213. this.el.object3D.rotation.set(0, 0, 0);
  45214. }
  45215. });
  45216. },{"../core/component":102,"../lib/three":150}],74:[function(_dereq_,module,exports){
  45217. var registerComponent = _dereq_('../core/component').registerComponent;
  45218. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  45219. var zeroScale = 0.00001;
  45220. module.exports.Component = registerComponent('scale', {
  45221. schema: {
  45222. type: 'vec3',
  45223. default: {x: 1, y: 1, z: 1}
  45224. },
  45225. update: function () {
  45226. var data = this.data;
  45227. var object3D = this.el.object3D;
  45228. var x = data.x === 0 ? zeroScale : data.x;
  45229. var y = data.y === 0 ? zeroScale : data.y;
  45230. var z = data.z === 0 ? zeroScale : data.z;
  45231. object3D.scale.set(x, y, z);
  45232. },
  45233. remove: function () {
  45234. // Pretty much for mixins.
  45235. this.el.object3D.scale.set(1, 1, 1);
  45236. }
  45237. });
  45238. },{"../core/component":102}],75:[function(_dereq_,module,exports){
  45239. /* global THREE */
  45240. var register = _dereq_('../../core/component').registerComponent;
  45241. module.exports.Component = register('background', {
  45242. schema: {
  45243. color: {type: 'color', default: 'black'},
  45244. transparent: {default: false}
  45245. },
  45246. update: function () {
  45247. var data = this.data;
  45248. var object3D = this.el.object3D;
  45249. if (data.transparent) {
  45250. object3D.background = null;
  45251. return;
  45252. }
  45253. object3D.background = new THREE.Color(data.color);
  45254. }
  45255. });
  45256. },{"../../core/component":102}],76:[function(_dereq_,module,exports){
  45257. var register = _dereq_('../../core/component').registerComponent;
  45258. module.exports.Component = register('debug', {
  45259. schema: {default: true}
  45260. });
  45261. },{"../../core/component":102}],77:[function(_dereq_,module,exports){
  45262. var registerComponent = _dereq_('../../core/component').registerComponent;
  45263. /**
  45264. * Component to embed an a-frame scene within the layout of a 2D page.
  45265. */
  45266. module.exports.Component = registerComponent('embedded', {
  45267. dependencies: ['vr-mode-ui'],
  45268. schema: {default: true},
  45269. update: function () {
  45270. var sceneEl = this.el;
  45271. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  45272. if (this.data === true) {
  45273. if (enterVREl) { enterVREl.classList.add('embedded'); }
  45274. sceneEl.removeFullScreenStyles();
  45275. } else {
  45276. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  45277. sceneEl.addFullScreenStyles();
  45278. }
  45279. }
  45280. });
  45281. },{"../../core/component":102}],78:[function(_dereq_,module,exports){
  45282. var register = _dereq_('../../core/component').registerComponent;
  45283. var THREE = _dereq_('../../lib/three');
  45284. var debug = _dereq_('../../utils/debug');
  45285. var warn = debug('components:fog:warn');
  45286. /**
  45287. * Fog component.
  45288. * Applies only to the scene entity.
  45289. */
  45290. module.exports.Component = register('fog', {
  45291. schema: {
  45292. color: {type: 'color', default: '#000'},
  45293. density: {default: 0.00025},
  45294. far: {default: 1000, min: 0},
  45295. near: {default: 1, min: 0},
  45296. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  45297. },
  45298. update: function () {
  45299. var data = this.data;
  45300. var el = this.el;
  45301. var fog = this.el.object3D.fog;
  45302. if (!el.isScene) {
  45303. warn('Fog component can only be applied to <a-scene>');
  45304. return;
  45305. }
  45306. // (Re)create fog if fog doesn't exist or fog type changed.
  45307. if (!fog || data.type !== fog.name) {
  45308. el.object3D.fog = getFog(data);
  45309. el.systems.material.updateMaterials();
  45310. return;
  45311. }
  45312. // Fog data changed. Update fog.
  45313. Object.keys(this.schema).forEach(function (key) {
  45314. var value = data[key];
  45315. if (key === 'color') { value = new THREE.Color(value); }
  45316. fog[key] = value;
  45317. });
  45318. },
  45319. /**
  45320. * Remove fog on remove (callback).
  45321. */
  45322. remove: function () {
  45323. var fog = this.el.object3D.fog;
  45324. if (!fog) { return; }
  45325. fog.far = 0;
  45326. fog.near = 0.1;
  45327. }
  45328. });
  45329. /**
  45330. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  45331. *
  45332. * @param {object} data - Fog data.
  45333. * @returns {object} fog
  45334. */
  45335. function getFog (data) {
  45336. var fog;
  45337. if (data.type === 'exponential') {
  45338. fog = new THREE.FogExp2(data.color, data.density);
  45339. } else {
  45340. fog = new THREE.Fog(data.color, data.near, data.far);
  45341. }
  45342. fog.name = data.type;
  45343. return fog;
  45344. }
  45345. },{"../../core/component":102,"../../lib/three":150,"../../utils/debug":168}],79:[function(_dereq_,module,exports){
  45346. (function (process){
  45347. /* global AFRAME */
  45348. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  45349. var bind = _dereq_('../../utils/bind');
  45350. var pkg = _dereq_('../../../package');
  45351. var registerComponent = _dereq_('../../core/component').registerComponent;
  45352. /**
  45353. * 0.4.2 to 0.4.x
  45354. * Will need to update this when A-Frame goes to 1.x.x.
  45355. */
  45356. function getFuzzyPatchVersion (version) {
  45357. var split = version.split('.');
  45358. split[2] = 'x';
  45359. return split.join('.');
  45360. }
  45361. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  45362. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  45363. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  45364. var LOADING_MESSAGE = 'Loading Inspector';
  45365. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  45366. module.exports.Component = registerComponent('inspector', {
  45367. schema: {
  45368. url: {default: INSPECTOR_URL}
  45369. },
  45370. init: function () {
  45371. this.onKeydown = bind(this.onKeydown, this);
  45372. this.onMessage = bind(this.onMessage, this);
  45373. this.initOverlay();
  45374. window.addEventListener('keydown', this.onKeydown);
  45375. window.addEventListener('message', this.onMessage);
  45376. },
  45377. initOverlay: function () {
  45378. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  45379. this.loadingMessageEl = document.createElement('div');
  45380. this.loadingMessageEl.classList.add('a-inspector-loader');
  45381. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  45382. },
  45383. remove: function () {
  45384. this.removeEventListeners();
  45385. },
  45386. /**
  45387. * <ctrl> + <alt> + i keyboard shortcut.
  45388. */
  45389. onKeydown: function (evt) {
  45390. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  45391. if (!this.data || !shortcutPressed) { return; }
  45392. this.injectInspector();
  45393. },
  45394. showLoader: function () {
  45395. document.body.appendChild(this.loadingMessageEl);
  45396. },
  45397. hideLoader: function () {
  45398. document.body.removeChild(this.loadingMessageEl);
  45399. },
  45400. /**
  45401. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  45402. */
  45403. onMessage: function (evt) {
  45404. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.injectInspector(); }
  45405. },
  45406. injectInspector: function () {
  45407. var self = this;
  45408. var script;
  45409. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) { return; }
  45410. this.showLoader();
  45411. // Inject.
  45412. script = document.createElement('script');
  45413. script.src = this.data.url;
  45414. script.setAttribute('data-name', 'aframe-inspector');
  45415. script.setAttribute(AFRAME_INJECTED, '');
  45416. script.onload = function () {
  45417. AFRAME.INSPECTOR.open();
  45418. self.hideLoader();
  45419. self.removeEventListeners();
  45420. };
  45421. script.onerror = function () {
  45422. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  45423. };
  45424. document.head.appendChild(script);
  45425. AFRAME.inspectorInjected = true;
  45426. },
  45427. removeEventListeners: function () {
  45428. window.removeEventListener('keydown', this.onKeydown);
  45429. window.removeEventListener('message', this.onMessage);
  45430. }
  45431. });
  45432. }).call(this,_dereq_('_process'))
  45433. },{"../../../package":51,"../../constants":94,"../../core/component":102,"../../utils/bind":166,"_process":32}],80:[function(_dereq_,module,exports){
  45434. var registerComponent = _dereq_('../../core/component').registerComponent;
  45435. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  45436. module.exports.Component = registerComponent('keyboard-shortcuts', {
  45437. schema: {
  45438. enterVR: {default: true},
  45439. exitVR: {default: true}
  45440. },
  45441. init: function () {
  45442. this.onKeyup = this.onKeyup.bind(this);
  45443. },
  45444. update: function (oldData) {
  45445. var data = this.data;
  45446. this.enterVREnabled = data.enterVR;
  45447. },
  45448. play: function () {
  45449. window.addEventListener('keyup', this.onKeyup, false);
  45450. },
  45451. pause: function () {
  45452. window.removeEventListener('keyup', this.onKeyup);
  45453. },
  45454. onKeyup: function (evt) {
  45455. var scene = this.el;
  45456. if (!shouldCaptureKeyEvent(evt)) { return; }
  45457. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  45458. scene.enterVR();
  45459. }
  45460. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  45461. scene.exitVR();
  45462. }
  45463. }
  45464. });
  45465. },{"../../core/component":102,"../../utils/":172}],81:[function(_dereq_,module,exports){
  45466. var debug = _dereq_('../../utils/debug');
  45467. var registerComponent = _dereq_('../../core/component').registerComponent;
  45468. var warn = debug('components:pool:warn');
  45469. /**
  45470. * Pool component to reuse entities.
  45471. * Avoids creating and destroying the same kind of entities.
  45472. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  45473. *
  45474. * @member {array} availableEls - Available entities in the pool.
  45475. * @member {array} usedEls - Entities of the pool in use.
  45476. */
  45477. module.exports.Component = registerComponent('pool', {
  45478. schema: {
  45479. container: {default: ''},
  45480. mixin: {default: ''},
  45481. size: {default: 0},
  45482. dynamic: {default: false}
  45483. },
  45484. multiple: true,
  45485. initPool: function () {
  45486. var i;
  45487. this.availableEls = [];
  45488. this.usedEls = [];
  45489. if (!this.data.mixin) {
  45490. warn('No mixin provided for pool component.');
  45491. }
  45492. if (this.data.container) {
  45493. this.container = document.querySelector(this.data.container);
  45494. if (!this.container) {
  45495. warn('Container ' + this.data.container + ' not found.');
  45496. }
  45497. }
  45498. this.container = this.container || this.el;
  45499. for (i = 0; i < this.data.size; ++i) {
  45500. this.createEntity();
  45501. }
  45502. },
  45503. update: function (oldData) {
  45504. var data = this.data;
  45505. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  45506. this.initPool();
  45507. }
  45508. },
  45509. /**
  45510. * Add a new entity to the list of available entities.
  45511. */
  45512. createEntity: function () {
  45513. var el;
  45514. el = document.createElement('a-entity');
  45515. el.play = this.wrapPlay(el.play);
  45516. el.setAttribute('mixin', this.data.mixin);
  45517. el.object3D.visible = false;
  45518. el.pause();
  45519. this.container.appendChild(el);
  45520. this.availableEls.push(el);
  45521. },
  45522. /**
  45523. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  45524. * entities that are not in use.
  45525. */
  45526. wrapPlay: function (playMethod) {
  45527. var usedEls = this.usedEls;
  45528. return function () {
  45529. if (usedEls.indexOf(this) === -1) { return; }
  45530. playMethod.call(this);
  45531. };
  45532. },
  45533. /**
  45534. * Used to request one of the available entities of the pool.
  45535. */
  45536. requestEntity: function () {
  45537. var el;
  45538. if (this.availableEls.length === 0) {
  45539. if (this.data.dynamic === false) {
  45540. warn('Requested entity from empty pool: ' + this.name);
  45541. return;
  45542. } else {
  45543. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  45544. 'automatically. You might want to increase its initial size: ' + this.name);
  45545. }
  45546. this.createEntity();
  45547. }
  45548. el = this.availableEls.shift();
  45549. this.usedEls.push(el);
  45550. el.object3D.visible = true;
  45551. return el;
  45552. },
  45553. /**
  45554. * Used to return a used entity to the pool.
  45555. */
  45556. returnEntity: function (el) {
  45557. var index = this.usedEls.indexOf(el);
  45558. if (index === -1) {
  45559. warn('The returned entity was not previously pooled from ' + this.name);
  45560. return;
  45561. }
  45562. this.usedEls.splice(index, 1);
  45563. this.availableEls.push(el);
  45564. el.object3D.visible = false;
  45565. el.pause();
  45566. return el;
  45567. }
  45568. });
  45569. },{"../../core/component":102,"../../utils/debug":168}],82:[function(_dereq_,module,exports){
  45570. var register = _dereq_('../../core/component').registerComponent;
  45571. var debug = _dereq_('../../utils/debug');
  45572. var warn = debug('components:renderer:warn');
  45573. /**
  45574. * Determines state of various renderer properties.
  45575. *
  45576. * NOTE: Because the `renderer` component is not added to the scene
  45577. * automatically, changing default values here has no effect unless
  45578. * the same changes are included in `a-scene.js`.
  45579. */
  45580. module.exports.Component = register('renderer', {
  45581. schema: {
  45582. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  45583. logarithmicDepthBuffer: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  45584. maxCanvasWidth: {default: 1920},
  45585. maxCanvasHeight: {default: 1920},
  45586. gammaOutput: {default: false},
  45587. physicallyCorrectLights: {default: false},
  45588. sortObjects: {default: false}
  45589. },
  45590. init: function () {
  45591. var el = this.el;
  45592. if (!el.isScene) {
  45593. warn('Renderer component can only be applied to <a-scene>');
  45594. }
  45595. // TODO: Uncomment these lines and deprecate 'antialias' for v0.9.0.
  45596. // if (el.hasAttribute('antialias')) {
  45597. // warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  45598. // }
  45599. },
  45600. update: function (prevData) {
  45601. var data = this.data;
  45602. var sceneEl = this.el;
  45603. var renderer = sceneEl.renderer;
  45604. var needsShaderUpdate = false;
  45605. if (sceneEl.time > 0 && data.antialias !== prevData.antialias) {
  45606. warn('Property "antialias" cannot be changed after scene initialization');
  45607. }
  45608. if (sceneEl.time > 0 && data.logarithmicDepthBuffer !== prevData.logarithmicDepthBuffer) {
  45609. warn('Property "logarithmicDepthBuffer" cannot be changed after scene initialization');
  45610. }
  45611. if (data.sortObjects !== prevData.sortObjects) {
  45612. renderer.sortObjects = data.sortObjects;
  45613. }
  45614. if (data.gammaOutput !== prevData.gammaOutput) {
  45615. renderer.gammaOutput = data.gammaOutput;
  45616. needsShaderUpdate = true;
  45617. }
  45618. if (data.physicallyCorrectLights !== prevData.physicallyCorrectLights) {
  45619. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  45620. needsShaderUpdate = true;
  45621. }
  45622. if (!needsShaderUpdate || sceneEl.time === 0) { return; }
  45623. warn('Modifying renderer properties at runtime requires shader update and may drop frames.');
  45624. sceneEl.object3D.traverse(function (node) {
  45625. if (!node.isMesh) { return; }
  45626. if (Array.isArray(node.material)) {
  45627. node.material.forEach(function (material) {
  45628. material.needsUpdate = true;
  45629. });
  45630. } else {
  45631. node.material.needsUpdate = true;
  45632. }
  45633. });
  45634. }
  45635. });
  45636. },{"../../core/component":102,"../../utils/debug":168}],83:[function(_dereq_,module,exports){
  45637. /* global ImageData, URL */
  45638. var registerComponent = _dereq_('../../core/component').registerComponent;
  45639. var THREE = _dereq_('../../lib/three');
  45640. var VERTEX_SHADER = [
  45641. 'attribute vec3 position;',
  45642. 'attribute vec2 uv;',
  45643. 'uniform mat4 projectionMatrix;',
  45644. 'uniform mat4 modelViewMatrix;',
  45645. 'varying vec2 vUv;',
  45646. 'void main() {',
  45647. ' vUv = vec2( 1.- uv.x, uv.y );',
  45648. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  45649. '}'
  45650. ].join('\n');
  45651. var FRAGMENT_SHADER = [
  45652. 'precision mediump float;',
  45653. 'uniform samplerCube map;',
  45654. 'varying vec2 vUv;',
  45655. '#define M_PI 3.141592653589793238462643383279',
  45656. 'void main() {',
  45657. ' vec2 uv = vUv;',
  45658. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  45659. ' float latitude = uv.y * M_PI;',
  45660. ' vec3 dir = vec3(',
  45661. ' - sin( longitude ) * sin( latitude ),',
  45662. ' cos( latitude ),',
  45663. ' - cos( longitude ) * sin( latitude )',
  45664. ' );',
  45665. ' normalize( dir );',
  45666. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  45667. '}'
  45668. ].join('\n');
  45669. /**
  45670. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  45671. * It can be configured to either take 360&deg; captures (`equirectangular`)
  45672. * or regular screenshots (`projection`)
  45673. *
  45674. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  45675. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  45676. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  45677. * WebGLRenderTarget with an ortographic camera.
  45678. */
  45679. module.exports.Component = registerComponent('screenshot', {
  45680. schema: {
  45681. width: {default: 4096},
  45682. height: {default: 2048},
  45683. camera: {type: 'selector'}
  45684. },
  45685. init: function () {
  45686. var el = this.el;
  45687. var self = this;
  45688. if (el.renderer) {
  45689. setup();
  45690. } else {
  45691. el.addEventListener('render-target-loaded', setup);
  45692. }
  45693. function setup () {
  45694. var gl = el.renderer.getContext();
  45695. if (!gl) { return; }
  45696. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  45697. self.material = new THREE.RawShaderMaterial({
  45698. uniforms: {map: {type: 't', value: null}},
  45699. vertexShader: VERTEX_SHADER,
  45700. fragmentShader: FRAGMENT_SHADER,
  45701. side: THREE.DoubleSide
  45702. });
  45703. self.quad = new THREE.Mesh(
  45704. new THREE.PlaneBufferGeometry(1, 1),
  45705. self.material
  45706. );
  45707. self.quad.visible = false;
  45708. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  45709. self.canvas = document.createElement('canvas');
  45710. self.ctx = self.canvas.getContext('2d');
  45711. if (el.camera) { el.camera.add(self.quad); }
  45712. self.onKeyDown = self.onKeyDown.bind(self);
  45713. self.onCameraActive = self.onCameraActive.bind(self);
  45714. el.addEventListener('camera-set-active', self.onCameraActive);
  45715. }
  45716. },
  45717. getRenderTarget: function (width, height) {
  45718. return new THREE.WebGLRenderTarget(width, height, {
  45719. minFilter: THREE.LinearFilter,
  45720. magFilter: THREE.LinearFilter,
  45721. wrapS: THREE.ClampToEdgeWrapping,
  45722. wrapT: THREE.ClampToEdgeWrapping,
  45723. format: THREE.RGBAFormat,
  45724. type: THREE.UnsignedByteType
  45725. });
  45726. },
  45727. resize: function (width, height) {
  45728. // Resize quad.
  45729. this.quad.scale.set(width, height, 1);
  45730. // Resize camera.
  45731. this.camera.left = -1 * width / 2;
  45732. this.camera.right = width / 2;
  45733. this.camera.top = height / 2;
  45734. this.camera.bottom = -1 * height / 2;
  45735. this.camera.updateProjectionMatrix();
  45736. // Resize canvas.
  45737. this.canvas.width = width;
  45738. this.canvas.height = height;
  45739. },
  45740. play: function () {
  45741. window.addEventListener('keydown', this.onKeyDown);
  45742. },
  45743. onCameraActive: function (evt) {
  45744. var cameraParent = this.quad.parent;
  45745. if (cameraParent) { cameraParent.remove(this.quad); }
  45746. evt.detail.cameraEl.getObject3D('camera').add(this.quad);
  45747. },
  45748. /**
  45749. * <ctrl> + <alt> + s = Regular screenshot.
  45750. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  45751. */
  45752. onKeyDown: function (evt) {
  45753. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  45754. if (!this.data || !shortcutPressed) { return; }
  45755. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  45756. this.capture(projection);
  45757. },
  45758. /**
  45759. * Capture a screenshot of the scene.
  45760. *
  45761. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  45762. */
  45763. setCapture: function (projection) {
  45764. var el = this.el;
  45765. var size;
  45766. var camera;
  45767. var cubeCamera;
  45768. // Configure camera.
  45769. if (projection === 'perspective') {
  45770. // Quad is only used in equirectangular mode. Hide it in this case.
  45771. this.quad.visible = false;
  45772. // Use scene camera.
  45773. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  45774. size = {width: this.data.width, height: this.data.height};
  45775. } else {
  45776. // Use ortho camera.
  45777. camera = this.camera;
  45778. // Copy position and rotation of scene camera into the ortho one.
  45779. el.camera.getWorldPosition(camera.position);
  45780. el.camera.getWorldRotation(camera.rotation);
  45781. // Create cube camera and copy position from scene camera.
  45782. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  45783. Math.min(this.cubeMapSize, 2048));
  45784. el.camera.getWorldPosition(cubeCamera.position);
  45785. el.camera.getWorldRotation(cubeCamera.rotation);
  45786. // Render scene with cube camera.
  45787. cubeCamera.updateCubeMap(el.renderer, el.object3D);
  45788. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  45789. size = {width: this.data.width, height: this.data.height};
  45790. // Use quad to project image taken by the cube camera.
  45791. this.quad.visible = true;
  45792. }
  45793. return {
  45794. camera: camera,
  45795. size: size,
  45796. projection: projection
  45797. };
  45798. },
  45799. /**
  45800. * Maintained for backwards compatibility.
  45801. */
  45802. capture: function (projection) {
  45803. var params = this.setCapture(projection);
  45804. this.renderCapture(params.camera, params.size, params.projection);
  45805. // Trigger file download.
  45806. this.saveCapture();
  45807. },
  45808. /**
  45809. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  45810. */
  45811. getCanvas: function (projection) {
  45812. var params = this.setCapture(projection);
  45813. this.renderCapture(params.camera, params.size, params.projection);
  45814. return this.canvas;
  45815. },
  45816. renderCapture: function (camera, size, projection) {
  45817. var autoClear = this.el.renderer.autoClear;
  45818. var el = this.el;
  45819. var imageData;
  45820. var output;
  45821. var pixels;
  45822. var renderer = this.el.renderer;
  45823. // Create rendering target and buffer to store the read pixels.
  45824. output = this.getRenderTarget(size.width, size.height);
  45825. pixels = new Uint8Array(4 * size.width * size.height);
  45826. // Resize quad, camera, and canvas.
  45827. this.resize(size.width, size.height);
  45828. // Render scene to render target.
  45829. renderer.autoClear = true;
  45830. renderer.render(el.object3D, camera, output, true);
  45831. renderer.autoClear = autoClear;
  45832. // Read image pizels back.
  45833. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  45834. if (projection === 'perspective') {
  45835. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  45836. }
  45837. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  45838. // Hide quad after projecting the image.
  45839. this.quad.visible = false;
  45840. // Copy pixels into canvas.
  45841. this.ctx.putImageData(imageData, 0, 0);
  45842. },
  45843. flipPixelsVertically: function (pixels, width, height) {
  45844. var flippedPixels = pixels.slice(0);
  45845. for (var x = 0; x < width; ++x) {
  45846. for (var y = 0; y < height; ++y) {
  45847. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  45848. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  45849. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  45850. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  45851. }
  45852. }
  45853. return flippedPixels;
  45854. },
  45855. /**
  45856. * Download capture to file.
  45857. */
  45858. saveCapture: function () {
  45859. this.canvas.toBlob(function (blob) {
  45860. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  45861. var linkEl = document.createElement('a');
  45862. var url = URL.createObjectURL(blob);
  45863. linkEl.href = url;
  45864. linkEl.setAttribute('download', fileName);
  45865. linkEl.innerHTML = 'downloading...';
  45866. linkEl.style.display = 'none';
  45867. document.body.appendChild(linkEl);
  45868. setTimeout(function () {
  45869. linkEl.click();
  45870. document.body.removeChild(linkEl);
  45871. }, 1);
  45872. }, 'image/png');
  45873. }
  45874. });
  45875. },{"../../core/component":102,"../../lib/three":150}],84:[function(_dereq_,module,exports){
  45876. var registerComponent = _dereq_('../../core/component').registerComponent;
  45877. var RStats = _dereq_('../../../vendor/rStats');
  45878. var utils = _dereq_('../../utils');
  45879. _dereq_('../../../vendor/rStats.extras');
  45880. _dereq_('../../lib/rStatsAframe');
  45881. var AFrameStats = window.aframeStats;
  45882. var bind = utils.bind;
  45883. var HIDDEN_CLASS = 'a-hidden';
  45884. var ThreeStats = window.threeStats;
  45885. /**
  45886. * Stats appended to document.body by RStats.
  45887. */
  45888. module.exports.Component = registerComponent('stats', {
  45889. schema: {default: true},
  45890. init: function () {
  45891. var scene = this.el;
  45892. if (utils.getUrlParameter('stats') === 'false') { return; }
  45893. this.stats = createStats(scene);
  45894. this.statsEl = document.querySelector('.rs-base');
  45895. this.hideBound = bind(this.hide, this);
  45896. this.showBound = bind(this.show, this);
  45897. scene.addEventListener('enter-vr', this.hideBound);
  45898. scene.addEventListener('exit-vr', this.showBound);
  45899. },
  45900. update: function () {
  45901. if (!this.stats) { return; }
  45902. return (!this.data) ? this.hide() : this.show();
  45903. },
  45904. remove: function () {
  45905. this.el.removeEventListener('enter-vr', this.hideBound);
  45906. this.el.removeEventListener('exit-vr', this.showBound);
  45907. if (!this.statsEl) { return; } // Scene detached.
  45908. this.statsEl.parentNode.removeChild(this.statsEl);
  45909. },
  45910. tick: function () {
  45911. var stats = this.stats;
  45912. if (!stats) { return; }
  45913. stats('rAF').tick();
  45914. stats('FPS').frame();
  45915. stats().update();
  45916. },
  45917. hide: function () {
  45918. this.statsEl.classList.add(HIDDEN_CLASS);
  45919. },
  45920. show: function () {
  45921. this.statsEl.classList.remove(HIDDEN_CLASS);
  45922. }
  45923. });
  45924. function createStats (scene) {
  45925. var threeStats = new ThreeStats(scene.renderer);
  45926. var aframeStats = new AFrameStats(scene);
  45927. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  45928. return new RStats({
  45929. css: [], // Our stylesheet is injected from `src/index.js`.
  45930. values: {
  45931. fps: {caption: 'fps', below: 30}
  45932. },
  45933. groups: [
  45934. {caption: 'Framerate', values: ['fps', 'raf']}
  45935. ],
  45936. plugins: plugins
  45937. });
  45938. }
  45939. },{"../../../vendor/rStats":180,"../../../vendor/rStats.extras":179,"../../core/component":102,"../../lib/rStatsAframe":149,"../../utils":172}],85:[function(_dereq_,module,exports){
  45940. var registerComponent = _dereq_('../../core/component').registerComponent;
  45941. var constants = _dereq_('../../constants/');
  45942. var utils = _dereq_('../../utils/');
  45943. var bind = utils.bind;
  45944. var ENTER_VR_CLASS = 'a-enter-vr';
  45945. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  45946. var HIDDEN_CLASS = 'a-hidden';
  45947. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  45948. /**
  45949. * UI for entering VR mode.
  45950. */
  45951. module.exports.Component = registerComponent('vr-mode-ui', {
  45952. dependencies: ['canvas'],
  45953. schema: {
  45954. enabled: {default: true},
  45955. enterVRButton: {default: ''}
  45956. },
  45957. init: function () {
  45958. var self = this;
  45959. var sceneEl = this.el;
  45960. if (utils.getUrlParameter('ui') === 'false') { return; }
  45961. this.insideLoader = false;
  45962. this.enterVREl = null;
  45963. this.orientationModalEl = null;
  45964. this.bindMethods();
  45965. // Hide/show VR UI when entering/exiting VR mode.
  45966. sceneEl.addEventListener('enter-vr', this.updateEnterVRInterface);
  45967. sceneEl.addEventListener('exit-vr', this.updateEnterVRInterface);
  45968. window.addEventListener('message', function (event) {
  45969. if (event.data.type === 'loaderReady') {
  45970. self.insideLoader = true;
  45971. self.remove();
  45972. }
  45973. });
  45974. // Modal that tells the user to change orientation if in portrait.
  45975. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  45976. },
  45977. bindMethods: function () {
  45978. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  45979. this.onModalClick = bind(this.onModalClick, this);
  45980. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  45981. this.updateEnterVRInterface = bind(this.updateEnterVRInterface, this);
  45982. },
  45983. /**
  45984. * Exit VR when modal clicked.
  45985. */
  45986. onModalClick: function () {
  45987. this.el.exitVR();
  45988. },
  45989. /**
  45990. * Enter VR when modal clicked.
  45991. */
  45992. onEnterVRButtonClick: function () {
  45993. this.el.enterVR();
  45994. },
  45995. update: function () {
  45996. var data = this.data;
  45997. var sceneEl = this.el;
  45998. if (!data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  45999. return this.remove();
  46000. }
  46001. if (this.enterVREl || this.orientationModalEl) { return; }
  46002. // Add UI if enabled and not already present.
  46003. if (data.enterVRButton) {
  46004. // Custom button.
  46005. this.enterVREl = document.querySelector(data.enterVRButton);
  46006. this.enterVREl.addEventListener('click', this.onEnterVRButtonClick);
  46007. } else {
  46008. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  46009. sceneEl.appendChild(this.enterVREl);
  46010. }
  46011. this.orientationModalEl = createOrientationModal(this.onModalClick);
  46012. sceneEl.appendChild(this.orientationModalEl);
  46013. this.updateEnterVRInterface();
  46014. },
  46015. remove: function () {
  46016. [this.enterVREl, this.orientationModalEl].forEach(function (uiElement) {
  46017. if (uiElement && uiElement.parentNode) {
  46018. uiElement.parentNode.removeChild(uiElement);
  46019. }
  46020. });
  46021. },
  46022. updateEnterVRInterface: function () {
  46023. this.toggleEnterVRButtonIfNeeded();
  46024. this.toggleOrientationModalIfNeeded();
  46025. },
  46026. toggleEnterVRButtonIfNeeded: function () {
  46027. var sceneEl = this.el;
  46028. if (!this.enterVREl) { return; }
  46029. if (sceneEl.is('vr-mode')) {
  46030. this.enterVREl.classList.add(HIDDEN_CLASS);
  46031. } else {
  46032. this.enterVREl.classList.remove(HIDDEN_CLASS);
  46033. }
  46034. },
  46035. toggleOrientationModalIfNeeded: function () {
  46036. var sceneEl = this.el;
  46037. var orientationModalEl = this.orientationModalEl;
  46038. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  46039. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  46040. // Show if in VR mode on portrait.
  46041. orientationModalEl.classList.remove(HIDDEN_CLASS);
  46042. } else {
  46043. orientationModalEl.classList.add(HIDDEN_CLASS);
  46044. }
  46045. }
  46046. });
  46047. /**
  46048. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  46049. *
  46050. * Structure: <div><button></div>
  46051. *
  46052. * @param {function} onClick - click event handler
  46053. * @returns {Element} Wrapper <div>.
  46054. */
  46055. function createEnterVRButton (onClick) {
  46056. var vrButton;
  46057. var wrapper;
  46058. // Create elements.
  46059. wrapper = document.createElement('div');
  46060. wrapper.classList.add(ENTER_VR_CLASS);
  46061. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  46062. vrButton = document.createElement('button');
  46063. vrButton.className = ENTER_VR_BTN_CLASS;
  46064. vrButton.setAttribute('title',
  46065. 'Enter VR mode with a headset or fullscreen mode on a desktop. ' +
  46066. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  46067. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  46068. // Insert elements.
  46069. wrapper.appendChild(vrButton);
  46070. vrButton.addEventListener('click', function (evt) {
  46071. onClick();
  46072. evt.stopPropagation();
  46073. });
  46074. return wrapper;
  46075. }
  46076. /**
  46077. * Creates a modal dialog to request the user to switch to landscape orientation.
  46078. *
  46079. * @param {function} onClick - click event handler
  46080. * @returns {Element} Wrapper <div>.
  46081. */
  46082. function createOrientationModal (onClick) {
  46083. var modal = document.createElement('div');
  46084. modal.className = ORIENTATION_MODAL_CLASS;
  46085. modal.classList.add(HIDDEN_CLASS);
  46086. modal.setAttribute(constants.AFRAME_INJECTED, '');
  46087. var exit = document.createElement('button');
  46088. exit.setAttribute(constants.AFRAME_INJECTED, '');
  46089. exit.innerHTML = 'Exit VR';
  46090. // Exit VR on close.
  46091. exit.addEventListener('click', onClick);
  46092. modal.appendChild(exit);
  46093. return modal;
  46094. }
  46095. },{"../../constants/":94,"../../core/component":102,"../../utils/":172}],86:[function(_dereq_,module,exports){
  46096. var component = _dereq_('../core/component');
  46097. var THREE = _dereq_('../lib/three');
  46098. var bind = _dereq_('../utils/bind');
  46099. var registerComponent = component.registerComponent;
  46100. /**
  46101. * Shadow component.
  46102. *
  46103. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  46104. * shadows as specified by the `cast` and `receive` properties.
  46105. */
  46106. module.exports.Component = registerComponent('shadow', {
  46107. schema: {
  46108. cast: {default: true},
  46109. receive: {default: true}
  46110. },
  46111. init: function () {
  46112. this.onMeshChanged = bind(this.update, this);
  46113. this.el.addEventListener('object3dset', this.onMeshChanged);
  46114. this.system.setShadowMapEnabled(true);
  46115. },
  46116. update: function () {
  46117. var data = this.data;
  46118. this.updateDescendants(data.cast, data.receive);
  46119. },
  46120. remove: function () {
  46121. var el = this.el;
  46122. el.removeEventListener('object3dset', this.onMeshChanged);
  46123. this.updateDescendants(false, false);
  46124. },
  46125. updateDescendants: function (cast, receive) {
  46126. var sceneEl = this.el.sceneEl;
  46127. this.el.object3D.traverse(function (node) {
  46128. if (!(node instanceof THREE.Mesh)) { return; }
  46129. node.castShadow = cast;
  46130. node.receiveShadow = receive;
  46131. // If scene has already rendered, materials must be updated.
  46132. if (sceneEl.hasLoaded && node.material) {
  46133. var materials = Array.isArray(node.material) ? node.material : [node.material];
  46134. for (var i = 0; i < materials.length; i++) {
  46135. materials[i].needsUpdate = true;
  46136. }
  46137. }
  46138. });
  46139. }
  46140. });
  46141. },{"../core/component":102,"../lib/three":150,"../utils/bind":166}],87:[function(_dereq_,module,exports){
  46142. var registerComponent = _dereq_('../core/component').registerComponent;
  46143. var debug = _dereq_('../utils/debug');
  46144. var bind = _dereq_('../utils/bind');
  46145. var THREE = _dereq_('../lib/three');
  46146. var warn = debug('components:sound:warn');
  46147. /**
  46148. * Sound component.
  46149. */
  46150. module.exports.Component = registerComponent('sound', {
  46151. schema: {
  46152. autoplay: {default: false},
  46153. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  46154. loop: {default: false},
  46155. maxDistance: {default: 10000},
  46156. on: {default: ''},
  46157. poolSize: {default: 1},
  46158. positional: {default: true},
  46159. refDistance: {default: 1},
  46160. rolloffFactor: {default: 1},
  46161. src: {type: 'audio'},
  46162. volume: {default: 1}
  46163. },
  46164. multiple: true,
  46165. init: function () {
  46166. this.listener = null;
  46167. this.audioLoader = new THREE.AudioLoader();
  46168. this.pool = new THREE.Group();
  46169. this.loaded = false;
  46170. this.mustPlay = false;
  46171. this.playSound = bind(this.playSound, this);
  46172. },
  46173. update: function (oldData) {
  46174. var data = this.data;
  46175. var srcChanged = data.src !== oldData.src;
  46176. // Create new sound if not yet created or changing `src`.
  46177. if (srcChanged) {
  46178. if (!data.src) {
  46179. warn('Audio source was not specified with `src`');
  46180. return;
  46181. }
  46182. this.setupSound();
  46183. }
  46184. this.pool.children.forEach(function (sound) {
  46185. if (data.positional) {
  46186. sound.setDistanceModel(data.distanceModel);
  46187. sound.setMaxDistance(data.maxDistance);
  46188. sound.setRefDistance(data.refDistance);
  46189. sound.setRolloffFactor(data.rolloffFactor);
  46190. }
  46191. sound.setLoop(data.loop);
  46192. sound.setVolume(data.volume);
  46193. sound.isPaused = false;
  46194. });
  46195. if (data.on !== oldData.on) {
  46196. this.updateEventListener(oldData.on);
  46197. }
  46198. // All sound values set. Load in `src`.
  46199. if (srcChanged) {
  46200. var self = this;
  46201. this.loaded = false;
  46202. this.audioLoader.load(data.src, function (buffer) {
  46203. self.pool.children.forEach(function (sound) {
  46204. sound.setBuffer(buffer);
  46205. });
  46206. self.loaded = true;
  46207. // Remove this key from cache, otherwise we can't play it again
  46208. THREE.Cache.remove(data.src);
  46209. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  46210. self.el.emit('sound-loaded', self.evtDetail);
  46211. });
  46212. }
  46213. },
  46214. pause: function () {
  46215. this.stopSound();
  46216. this.removeEventListener();
  46217. },
  46218. play: function () {
  46219. if (this.data.autoplay) { this.playSound(); }
  46220. this.updateEventListener();
  46221. },
  46222. remove: function () {
  46223. this.removeEventListener();
  46224. this.el.removeObject3D(this.attrName);
  46225. try {
  46226. this.pool.children.forEach(function (sound) {
  46227. sound.disconnect();
  46228. });
  46229. } catch (e) {
  46230. // disconnect() will throw if it was never connected initially.
  46231. warn('Audio source not properly disconnected');
  46232. }
  46233. },
  46234. /**
  46235. * Update listener attached to the user defined on event.
  46236. */
  46237. updateEventListener: function (oldEvt) {
  46238. var el = this.el;
  46239. if (oldEvt) { el.removeEventListener(oldEvt, this.playSound); }
  46240. el.addEventListener(this.data.on, this.playSound);
  46241. },
  46242. removeEventListener: function () {
  46243. this.el.removeEventListener(this.data.on, this.playSound);
  46244. },
  46245. /**
  46246. * Removes current sound object, creates new sound object, adds to entity.
  46247. *
  46248. * @returns {object} sound
  46249. */
  46250. setupSound: function () {
  46251. var self = this;
  46252. var el = this.el;
  46253. var sceneEl = el.sceneEl;
  46254. if (this.pool.children.length > 0) {
  46255. this.stopSound();
  46256. el.removeObject3D('sound');
  46257. }
  46258. // Only want one AudioListener. Cache it on the scene.
  46259. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  46260. sceneEl.audioListener = listener;
  46261. if (sceneEl.camera) {
  46262. sceneEl.camera.add(listener);
  46263. }
  46264. // Wait for camera if necessary.
  46265. sceneEl.addEventListener('camera-set-active', function (evt) {
  46266. evt.detail.cameraEl.getObject3D('camera').add(listener);
  46267. });
  46268. // Create [poolSize] audio instances and attach them to pool
  46269. this.pool = new THREE.Group();
  46270. for (var i = 0; i < this.data.poolSize; i++) {
  46271. var sound = this.data.positional ? new THREE.PositionalAudio(listener) : new THREE.Audio(listener);
  46272. this.pool.add(sound);
  46273. }
  46274. el.setObject3D(this.attrName, this.pool);
  46275. this.pool.children.forEach(function (sound) {
  46276. sound.onEnded = function () {
  46277. sound.isPlaying = false;
  46278. el.emit('sound-ended', self.evtDetail);
  46279. };
  46280. });
  46281. },
  46282. /**
  46283. * Pause all the sounds in the pool.
  46284. */
  46285. pauseSound: function () {
  46286. this.isPlaying = false;
  46287. this.pool.children.forEach(function (sound) {
  46288. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) { return; }
  46289. sound.isPaused = true;
  46290. sound.pause();
  46291. });
  46292. },
  46293. /**
  46294. * Look for an unused sound in the pool and play it if found.
  46295. */
  46296. playSound: function () {
  46297. if (!this.loaded) {
  46298. warn('Sound not loaded yet. It will be played once it finished loading');
  46299. this.mustPlay = true;
  46300. return;
  46301. }
  46302. var found = false;
  46303. this.isPlaying = true;
  46304. this.pool.children.forEach(function (sound) {
  46305. if (!sound.isPlaying && sound.buffer && !found) {
  46306. sound.play();
  46307. sound.isPaused = false;
  46308. found = true;
  46309. return;
  46310. }
  46311. });
  46312. if (!found) {
  46313. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  46314. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  46315. return;
  46316. }
  46317. this.mustPlay = false;
  46318. },
  46319. /**
  46320. * Stop all the sounds in the pool.
  46321. */
  46322. stopSound: function () {
  46323. this.isPlaying = false;
  46324. this.pool.children.forEach(function (sound) {
  46325. if (!sound.source || !sound.source.buffer) { return; }
  46326. sound.stop();
  46327. });
  46328. }
  46329. });
  46330. },{"../core/component":102,"../lib/three":150,"../utils/bind":166,"../utils/debug":168}],88:[function(_dereq_,module,exports){
  46331. var createTextGeometry = _dereq_('three-bmfont-text');
  46332. var loadBMFont = _dereq_('load-bmfont');
  46333. var registerComponent = _dereq_('../core/component').registerComponent;
  46334. var coreShader = _dereq_('../core/shader');
  46335. var THREE = _dereq_('../lib/three');
  46336. var utils = _dereq_('../utils/');
  46337. var error = utils.debug('components:text:error');
  46338. var shaders = coreShader.shaders;
  46339. var warn = utils.debug('components:text:warn');
  46340. // 1 to match other A-Frame default widths.
  46341. var DEFAULT_WIDTH = 1;
  46342. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  46343. var MAX_ANISOTROPY = 16;
  46344. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  46345. var FONTS = {
  46346. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  46347. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  46348. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  46349. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  46350. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  46351. monoid: FONT_BASE_URL + 'Monoid.fnt',
  46352. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  46353. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  46354. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  46355. };
  46356. var MSDF_FONTS = ['roboto'];
  46357. var DEFAULT_FONT = 'roboto';
  46358. module.exports.FONTS = FONTS;
  46359. var cache = new PromiseCache();
  46360. var fontWidthFactors = {};
  46361. var textures = {};
  46362. // Regular expression for detecting a URLs with a protocol prefix.
  46363. var protocolRe = /^\w+:/;
  46364. /**
  46365. * SDF-based text component.
  46366. * Based on https://github.com/Jam3/three-bmfont-text.
  46367. *
  46368. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  46369. * original `sdf` shader.
  46370. */
  46371. module.exports.Component = registerComponent('text', {
  46372. multiple: true,
  46373. schema: {
  46374. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  46375. alphaTest: {default: 0.5},
  46376. // `anchor` defaults to center to match geometries.
  46377. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  46378. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  46379. color: {type: 'color', default: '#FFF'},
  46380. font: {type: 'string', default: DEFAULT_FONT},
  46381. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  46382. fontImage: {type: 'string'},
  46383. // `height` has no default, will be populated at layout.
  46384. height: {type: 'number'},
  46385. letterSpacing: {type: 'number', default: 0},
  46386. // `lineHeight` defaults to font's `lineHeight` value.
  46387. lineHeight: {type: 'number'},
  46388. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  46389. negate: {type: 'boolean', default: true},
  46390. opacity: {type: 'number', default: 1.0},
  46391. shader: {default: 'sdf', oneOf: shaders},
  46392. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  46393. tabSize: {default: 4},
  46394. transparent: {default: true},
  46395. value: {type: 'string'},
  46396. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  46397. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  46398. width: {type: 'number'},
  46399. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  46400. wrapCount: {type: 'number', default: 40},
  46401. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  46402. wrapPixels: {type: 'number'},
  46403. // `xOffset` to add padding.
  46404. xOffset: {type: 'number', default: 0},
  46405. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  46406. yOffset: {type: 'number', default: 0},
  46407. // `zOffset` will provide a small z offset to avoid z-fighting.
  46408. zOffset: {type: 'number', default: 0.001}
  46409. },
  46410. init: function () {
  46411. this.shaderData = {};
  46412. this.geometry = createTextGeometry();
  46413. this.createOrUpdateMaterial();
  46414. this.mesh = new THREE.Mesh(this.geometry, this.material);
  46415. this.el.setObject3D(this.attrName, this.mesh);
  46416. },
  46417. update: function (oldData) {
  46418. var data = coerceData(this.data);
  46419. var font = this.currentFont;
  46420. if (textures[data.font]) {
  46421. this.texture = textures[data.font];
  46422. } else {
  46423. // Create texture per font.
  46424. this.texture = textures[data.font] = new THREE.Texture();
  46425. this.texture.anisotropy = MAX_ANISOTROPY;
  46426. }
  46427. // Update material.
  46428. this.createOrUpdateMaterial();
  46429. // New font. `updateFont` will later change data and layout.
  46430. if (oldData.font !== data.font) {
  46431. this.updateFont();
  46432. return;
  46433. }
  46434. // Update geometry and layout.
  46435. if (font) {
  46436. this.updateGeometry(this.geometry, data, font);
  46437. this.updateLayout(data);
  46438. }
  46439. },
  46440. /**
  46441. * Clean up geometry, material, texture, mesh, objects.
  46442. */
  46443. remove: function () {
  46444. this.geometry.dispose();
  46445. this.geometry = null;
  46446. this.el.removeObject3D(this.attrName);
  46447. this.material.dispose();
  46448. this.material = null;
  46449. this.texture.dispose();
  46450. this.texture = null;
  46451. if (this.shaderObject) {
  46452. delete this.shaderObject;
  46453. }
  46454. },
  46455. /**
  46456. * Update the shader of the material.
  46457. */
  46458. createOrUpdateMaterial: function () {
  46459. var data = this.data;
  46460. var hasChangedShader;
  46461. var material = this.material;
  46462. var NewShader;
  46463. var shaderData = this.shaderData;
  46464. var shaderName;
  46465. // Infer shader if using a stock font (or from `-msdf` filename convention).
  46466. shaderName = data.shader;
  46467. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  46468. shaderName = 'msdf';
  46469. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  46470. shaderName = 'sdf';
  46471. }
  46472. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  46473. shaderData.alphaTest = data.alphaTest;
  46474. shaderData.color = data.color;
  46475. shaderData.map = this.texture;
  46476. shaderData.opacity = data.opacity;
  46477. shaderData.side = parseSide(data.side);
  46478. shaderData.transparent = data.transparent;
  46479. shaderData.negate = data.negate;
  46480. // Shader has not changed, do an update.
  46481. if (!hasChangedShader) {
  46482. // Update shader material.
  46483. this.shaderObject.update(shaderData);
  46484. // Apparently, was not set on `init` nor `update`.
  46485. material.transparent = shaderData.transparent;
  46486. material.side = shaderData.side;
  46487. return;
  46488. }
  46489. // Shader has changed. Create a shader material.
  46490. NewShader = createShader(this.el, shaderName, shaderData);
  46491. this.material = NewShader.material;
  46492. this.shaderObject = NewShader.shader;
  46493. // Set new shader material.
  46494. this.material.side = shaderData.side;
  46495. if (this.mesh) { this.mesh.material = this.material; }
  46496. },
  46497. /**
  46498. * Load font for geometry, load font image for material, and apply.
  46499. */
  46500. updateFont: function () {
  46501. var data = this.data;
  46502. var el = this.el;
  46503. var fontSrc;
  46504. var geometry = this.geometry;
  46505. var self = this;
  46506. if (!data.font) { warn('No font specified. Using the default font.'); }
  46507. // Make invisible during font swap.
  46508. this.mesh.visible = false;
  46509. // Look up font URL to use, and perform cached load.
  46510. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  46511. cache.get(fontSrc, function doLoadFont () {
  46512. return loadFont(fontSrc, data.yOffset);
  46513. }).then(function setFont (font) {
  46514. var coercedData;
  46515. var fontImgSrc;
  46516. if (font.pages.length !== 1) {
  46517. throw new Error('Currently only single-page bitmap fonts are supported.');
  46518. }
  46519. if (!fontWidthFactors[fontSrc]) {
  46520. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  46521. }
  46522. // Update geometry given font metrics.
  46523. coercedData = coerceData(data);
  46524. self.updateGeometry(geometry, self.data, font);
  46525. // Set font and update layout.
  46526. self.currentFont = font;
  46527. self.updateLayout(coercedData);
  46528. // Look up font image URL to use, and perform cached load.
  46529. fontImgSrc = self.getFontImageSrc();
  46530. cache.get(fontImgSrc, function () {
  46531. return loadTexture(fontImgSrc);
  46532. }).then(function (image) {
  46533. // Make mesh visible and apply font image as texture.
  46534. var texture = self.texture;
  46535. texture.image = image;
  46536. texture.needsUpdate = true;
  46537. textures[data.font] = texture;
  46538. self.texture = texture;
  46539. self.mesh.visible = true;
  46540. el.emit('textfontset', {font: data.font, fontObj: font});
  46541. }).catch(function (err) {
  46542. error(err);
  46543. throw err;
  46544. });
  46545. }).catch(function (err) {
  46546. error(err);
  46547. throw err;
  46548. });
  46549. },
  46550. getFontImageSrc: function () {
  46551. if (this.data.fontImage) { return this.data.fontImage; }
  46552. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  46553. var imageSrc = this.currentFont.pages[0];
  46554. // If the image URL contains a non-HTTP(S) protocol, assume it's an absolute
  46555. // path on disk and try to infer the path from the font source instead.
  46556. if (imageSrc.match(protocolRe) && imageSrc.indexOf('http') !== 0) {
  46557. return fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  46558. }
  46559. return THREE.LoaderUtils.extractUrlBase(fontSrc) + imageSrc;
  46560. },
  46561. /**
  46562. * Update layout with anchor, alignment, baseline, and considering any meshes.
  46563. */
  46564. updateLayout: function (data) {
  46565. var anchor;
  46566. var baseline;
  46567. var el = this.el;
  46568. var geometry = this.geometry;
  46569. var geometryComponent;
  46570. var height;
  46571. var layout;
  46572. var mesh = this.mesh;
  46573. var textRenderWidth;
  46574. var textScale;
  46575. var width;
  46576. var x;
  46577. var y;
  46578. if (!geometry.layout) { return; }
  46579. // Determine width to use (defined width, geometry's width, or default width).
  46580. geometryComponent = el.getAttribute('geometry');
  46581. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  46582. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  46583. // Note that experimental factor will never be correct for variable width fonts.
  46584. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  46585. this.currentFont.widthFactor);
  46586. textScale = width / textRenderWidth;
  46587. // Determine height to use.
  46588. layout = geometry.layout;
  46589. height = textScale * (layout.height + layout.descender);
  46590. // Update geometry dimensions to match text layout if width and height are set to 0.
  46591. // For example, scales a plane to fit text.
  46592. if (geometryComponent) {
  46593. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  46594. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  46595. }
  46596. // Calculate X position to anchor text left, center, or right.
  46597. anchor = data.anchor === 'align' ? data.align : data.anchor;
  46598. if (anchor === 'left') {
  46599. x = 0;
  46600. } else if (anchor === 'right') {
  46601. x = -1 * layout.width;
  46602. } else if (anchor === 'center') {
  46603. x = -1 * layout.width / 2;
  46604. } else {
  46605. throw new TypeError('Invalid text.anchor property value', anchor);
  46606. }
  46607. // Calculate Y position to anchor text top, center, or bottom.
  46608. baseline = data.baseline;
  46609. if (baseline === 'bottom') {
  46610. y = 0;
  46611. } else if (baseline === 'top') {
  46612. y = -1 * layout.height + layout.ascender;
  46613. } else if (baseline === 'center') {
  46614. y = -1 * layout.height / 2;
  46615. } else {
  46616. throw new TypeError('Invalid text.baseline property value', baseline);
  46617. }
  46618. // Position and scale mesh to apply layout.
  46619. mesh.position.x = x * textScale + data.xOffset;
  46620. mesh.position.y = y * textScale;
  46621. // Place text slightly in front to avoid Z-fighting.
  46622. mesh.position.z = data.zOffset;
  46623. mesh.scale.set(textScale, -1 * textScale, textScale);
  46624. this.geometry.computeBoundingSphere();
  46625. },
  46626. /**
  46627. * Grab font from the constant.
  46628. * Set as a method for test stubbing purposes.
  46629. */
  46630. lookupFont: function (key) {
  46631. return FONTS[key];
  46632. },
  46633. /**
  46634. * Update the text geometry using `three-bmfont-text.update`.
  46635. */
  46636. updateGeometry: function (geometry, data, font) {
  46637. geometry.update(utils.extend({}, data, {
  46638. font: font,
  46639. width: computeWidth(data.wrapPixels, data.wrapCount, font.widthFactor),
  46640. text: data.value.toString().replace(/\\n/g, '\n').replace(/\\t/g, '\t'),
  46641. lineHeight: data.lineHeight || font.common.lineHeight
  46642. }));
  46643. }
  46644. });
  46645. /**
  46646. * Due to using negative scale, we return the opposite side specified.
  46647. * https://github.com/mrdoob/three.js/pull/12787/
  46648. */
  46649. function parseSide (side) {
  46650. switch (side) {
  46651. case 'back': {
  46652. return THREE.FrontSide;
  46653. }
  46654. case 'double': {
  46655. return THREE.DoubleSide;
  46656. }
  46657. default: {
  46658. return THREE.BackSide;
  46659. }
  46660. }
  46661. }
  46662. /**
  46663. * Coerce some data to numbers.
  46664. * as they will be passed directly into text creation and update
  46665. */
  46666. function coerceData (data) {
  46667. data = utils.clone(data);
  46668. if (data.lineHeight !== undefined) {
  46669. data.lineHeight = parseFloat(data.lineHeight);
  46670. if (!isFinite(data.lineHeight)) { data.lineHeight = undefined; }
  46671. }
  46672. if (data.width !== undefined) {
  46673. data.width = parseFloat(data.width);
  46674. if (!isFinite(data.width)) { data.width = undefined; }
  46675. }
  46676. return data;
  46677. }
  46678. /**
  46679. * @returns {Promise}
  46680. */
  46681. function loadFont (src, yOffset) {
  46682. return new Promise(function (resolve, reject) {
  46683. loadBMFont(src, function (err, font) {
  46684. if (err) {
  46685. error('Error loading font', src);
  46686. reject(err);
  46687. return;
  46688. }
  46689. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  46690. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  46691. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  46692. resolve(font);
  46693. });
  46694. });
  46695. }
  46696. /**
  46697. * @returns {Promise}
  46698. */
  46699. function loadTexture (src) {
  46700. return new Promise(function (resolve, reject) {
  46701. new THREE.ImageLoader().load(src, function (image) {
  46702. resolve(image);
  46703. }, undefined, function () {
  46704. error('Error loading font image', src);
  46705. reject(null);
  46706. });
  46707. });
  46708. }
  46709. function createShader (el, shaderName, data) {
  46710. var shader;
  46711. var shaderObject;
  46712. // Set up Shader.
  46713. shaderObject = new shaders[shaderName].Shader();
  46714. shaderObject.el = el;
  46715. shaderObject.init(data);
  46716. shaderObject.update(data);
  46717. // Get material.
  46718. shader = shaderObject.material;
  46719. // Apparently, was not set on `init` nor `update`.
  46720. shader.transparent = data.transparent;
  46721. return {
  46722. material: shader,
  46723. shader: shaderObject
  46724. };
  46725. }
  46726. /**
  46727. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  46728. * Note that experimental factor will never be correct for variable width fonts.
  46729. */
  46730. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  46731. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  46732. }
  46733. /**
  46734. * Compute default font width factor to use.
  46735. */
  46736. function computeFontWidthFactor (font) {
  46737. var sum = 0;
  46738. var digitsum = 0;
  46739. var digits = 0;
  46740. font.chars.map(function (ch) {
  46741. sum += ch.xadvance;
  46742. if (ch.id >= 48 && ch.id <= 57) {
  46743. digits++;
  46744. digitsum += ch.xadvance;
  46745. }
  46746. });
  46747. return digits ? digitsum / digits : sum / font.chars.length;
  46748. }
  46749. /**
  46750. * Get or create a promise given a key and promise generator.
  46751. * @todo Move to a utility and use in other parts of A-Frame.
  46752. */
  46753. function PromiseCache () {
  46754. var cache = this.cache = {};
  46755. this.get = function (key, promiseGenerator) {
  46756. if (key in cache) {
  46757. return cache[key];
  46758. }
  46759. cache[key] = promiseGenerator();
  46760. return cache[key];
  46761. };
  46762. }
  46763. },{"../core/component":102,"../core/shader":111,"../lib/three":150,"../utils/":172,"load-bmfont":23,"three-bmfont-text":36}],89:[function(_dereq_,module,exports){
  46764. var registerComponent = _dereq_('../core/component').registerComponent;
  46765. var controllerUtils = _dereq_('../utils/tracked-controls');
  46766. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  46767. var THREE = _dereq_('../lib/three');
  46768. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  46769. // Vector from eyes to elbow (divided by user height).
  46770. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  46771. // Vector from eyes to elbow (divided by user height).
  46772. var FOREARM = {x: 0, y: 0, z: -0.175};
  46773. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  46774. var EMPTY_DAYDREAM_TOUCHES = {touches: []};
  46775. var EVENTS = {
  46776. AXISMOVE: 'axismove',
  46777. BUTTONCHANGED: 'buttonchanged',
  46778. BUTTONDOWN: 'buttondown',
  46779. BUTTONUP: 'buttonup',
  46780. TOUCHSTART: 'touchstart',
  46781. TOUCHEND: 'touchend'
  46782. };
  46783. /**
  46784. * Tracked controls component.
  46785. * Wrap the gamepad API for pose and button states.
  46786. * Select the appropriate controller and apply pose to the entity.
  46787. * Observe button states and emit appropriate events.
  46788. *
  46789. * @property {number} controller - Index of controller in array returned by Gamepad API.
  46790. * Only used if hand property is not set.
  46791. * @property {string} id - Selected controller among those returned by Gamepad API.
  46792. * @property {number} hand - If multiple controllers found with id, choose the one with the
  46793. * given value for hand. If set, we ignore 'controller' property
  46794. */
  46795. module.exports.Component = registerComponent('tracked-controls', {
  46796. schema: {
  46797. controller: {default: 0},
  46798. id: {type: 'string', default: ''},
  46799. hand: {type: 'string', default: ''},
  46800. idPrefix: {type: 'string', default: ''},
  46801. orientationOffset: {type: 'vec3'},
  46802. // Arm model parameters when not 6DoF.
  46803. armModel: {default: true},
  46804. headElement: {type: 'selector'}
  46805. },
  46806. init: function () {
  46807. this.axis = [0, 0, 0];
  46808. this.buttonStates = {};
  46809. this.changedAxes = [];
  46810. this.targetControllerNumber = this.data.controller;
  46811. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  46812. this.deltaControllerPosition = new THREE.Vector3();
  46813. this.controllerQuaternion = new THREE.Quaternion();
  46814. this.controllerEuler = new THREE.Euler();
  46815. this.updateGamepad();
  46816. this.buttonEventDetails = {};
  46817. },
  46818. tick: function (time, delta) {
  46819. var mesh = this.el.getObject3D('mesh');
  46820. // Update mesh animations.
  46821. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  46822. this.updateGamepad();
  46823. this.updatePose();
  46824. this.updateButtons();
  46825. },
  46826. /**
  46827. * Return default user height to use for non-6DOF arm model.
  46828. */
  46829. defaultUserHeight: function () {
  46830. return DEFAULT_CAMERA_HEIGHT;
  46831. },
  46832. /**
  46833. * Return head element to use for non-6DOF arm model.
  46834. */
  46835. getHeadElement: function () {
  46836. return this.data.headElement || this.el.sceneEl.camera.el;
  46837. },
  46838. /**
  46839. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  46840. */
  46841. updateGamepad: function () {
  46842. var data = this.data;
  46843. var controller = controllerUtils.findMatchingController(
  46844. this.system.controllers,
  46845. data.id,
  46846. data.idPrefix,
  46847. data.hand,
  46848. data.controller
  46849. );
  46850. this.controller = controller;
  46851. },
  46852. /**
  46853. * Applies an artificial arm model to simulate elbow to wrist positioning
  46854. * based on the orientation of the controller.
  46855. *
  46856. * @param {object} controllerPosition - Existing vector to update with controller position.
  46857. */
  46858. applyArmModel: function (controllerPosition) {
  46859. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  46860. var controller = this.controller;
  46861. var controllerEuler = this.controllerEuler;
  46862. var controllerQuaternion = this.controllerQuaternion;
  46863. var deltaControllerPosition = this.deltaControllerPosition;
  46864. var hand;
  46865. var headEl;
  46866. var headObject3D;
  46867. var pose;
  46868. var userHeight;
  46869. headEl = this.getHeadElement();
  46870. headObject3D = headEl.object3D;
  46871. userHeight = this.defaultUserHeight();
  46872. pose = controller.pose;
  46873. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  46874. // Use camera position as head position.
  46875. controllerPosition.copy(headObject3D.position);
  46876. // Set offset for degenerate "arm model" to elbow.
  46877. deltaControllerPosition.set(
  46878. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  46879. EYES_TO_ELBOW.y, // Lower than our eyes.
  46880. EYES_TO_ELBOW.z); // Slightly out in front.
  46881. // Scale offset by user height.
  46882. deltaControllerPosition.multiplyScalar(userHeight);
  46883. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  46884. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  46885. // Apply rotated offset to position.
  46886. controllerPosition.add(deltaControllerPosition);
  46887. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  46888. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  46889. // Scale offset by user height.
  46890. deltaControllerPosition.multiplyScalar(userHeight);
  46891. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  46892. if (pose.orientation) {
  46893. controllerQuaternion.fromArray(pose.orientation);
  46894. } else {
  46895. controllerQuaternion.copy(headObject3D.quaternion);
  46896. }
  46897. controllerEuler.setFromQuaternion(controllerQuaternion);
  46898. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  46899. deltaControllerPosition.applyEuler(controllerEuler);
  46900. // Apply rotated offset to position.
  46901. controllerPosition.add(deltaControllerPosition);
  46902. },
  46903. /**
  46904. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  46905. */
  46906. updatePose: function () {
  46907. var controller = this.controller;
  46908. var data = this.data;
  46909. var object3D = this.el.object3D;
  46910. var pose;
  46911. var vrDisplay = this.system.vrDisplay;
  46912. var standingMatrix;
  46913. if (!controller) { return; }
  46914. // Compose pose from Gamepad.
  46915. pose = controller.pose;
  46916. if (pose.position) {
  46917. object3D.position.fromArray(pose.position);
  46918. } else {
  46919. // Controller not 6DOF, apply arm model.
  46920. if (data.armModel) { this.applyArmModel(object3D.position); }
  46921. }
  46922. if (pose.orientation) {
  46923. object3D.quaternion.fromArray(pose.orientation);
  46924. }
  46925. // Apply transforms, if 6DOF and in VR.
  46926. if (vrDisplay && pose.position) {
  46927. standingMatrix = this.el.sceneEl.renderer.vr.getStandingMatrix();
  46928. object3D.matrixAutoUpdate = false;
  46929. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  46930. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  46931. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  46932. }
  46933. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  46934. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  46935. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  46936. object3D.updateMatrix();
  46937. object3D.matrixWorldNeedsUpdate = true;
  46938. },
  46939. /**
  46940. * Handle button changes including axes, presses, touches, values.
  46941. */
  46942. updateButtons: function () {
  46943. var buttonState;
  46944. var controller = this.controller;
  46945. var id;
  46946. if (!controller) { return; }
  46947. // Check every button.
  46948. for (id = 0; id < controller.buttons.length; ++id) {
  46949. // Initialize button state.
  46950. if (!this.buttonStates[id]) {
  46951. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  46952. }
  46953. if (!this.buttonEventDetails[id]) {
  46954. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  46955. }
  46956. buttonState = controller.buttons[id];
  46957. this.handleButton(id, buttonState);
  46958. }
  46959. // Check axes.
  46960. this.handleAxes();
  46961. },
  46962. /**
  46963. * Handle presses and touches for a single button.
  46964. *
  46965. * @param {number} id - Index of button in Gamepad button array.
  46966. * @param {number} buttonState - Value of button state from 0 to 1.
  46967. * @returns {boolean} Whether button has changed in any way.
  46968. */
  46969. handleButton: function (id, buttonState) {
  46970. var changed;
  46971. changed = this.handlePress(id, buttonState) |
  46972. this.handleTouch(id, buttonState) |
  46973. this.handleValue(id, buttonState);
  46974. if (!changed) { return false; }
  46975. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  46976. return true;
  46977. },
  46978. /**
  46979. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  46980. * Compare each component of the axis to the previous value to determine change.
  46981. *
  46982. * @returns {boolean} Whether axes changed.
  46983. */
  46984. handleAxes: function () {
  46985. var changed = false;
  46986. var controllerAxes = this.controller.axes;
  46987. var i;
  46988. var previousAxis = this.axis;
  46989. var changedAxes = this.changedAxes;
  46990. // Check if axis changed.
  46991. this.changedAxes.length = 0;
  46992. for (i = 0; i < controllerAxes.length; ++i) {
  46993. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  46994. if (changedAxes[i]) { changed = true; }
  46995. }
  46996. if (!changed) { return false; }
  46997. this.axis.length = 0;
  46998. for (i = 0; i < controllerAxes.length; i++) {
  46999. this.axis.push(controllerAxes[i]);
  47000. }
  47001. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  47002. return true;
  47003. },
  47004. /**
  47005. * Determine whether a button press has occured and emit events as appropriate.
  47006. *
  47007. * @param {string} id - ID of the button to check.
  47008. * @param {object} buttonState - State of the button to check.
  47009. * @returns {boolean} Whether button press state changed.
  47010. */
  47011. handlePress: function (id, buttonState) {
  47012. var evtName;
  47013. var previousButtonState = this.buttonStates[id];
  47014. // Not changed.
  47015. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  47016. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  47017. this.el.emit(evtName, this.buttonEventDetails[id], false);
  47018. previousButtonState.pressed = buttonState.pressed;
  47019. return true;
  47020. },
  47021. /**
  47022. * Determine whether a button touch has occured and emit events as appropriate.
  47023. *
  47024. * @param {string} id - ID of the button to check.
  47025. * @param {object} buttonState - State of the button to check.
  47026. * @returns {boolean} Whether button touch state changed.
  47027. */
  47028. handleTouch: function (id, buttonState) {
  47029. var evtName;
  47030. var previousButtonState = this.buttonStates[id];
  47031. // Not changed.
  47032. if (buttonState.touched === previousButtonState.touched) { return false; }
  47033. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  47034. this.el.emit(evtName, this.buttonEventDetails[id], false, EMPTY_DAYDREAM_TOUCHES);
  47035. previousButtonState.touched = buttonState.touched;
  47036. return true;
  47037. },
  47038. /**
  47039. * Determine whether a button value has changed.
  47040. *
  47041. * @param {string} id - Id of the button to check.
  47042. * @param {object} buttonState - State of the button to check.
  47043. * @returns {boolean} Whether button value changed.
  47044. */
  47045. handleValue: function (id, buttonState) {
  47046. var previousButtonState = this.buttonStates[id];
  47047. // Not changed.
  47048. if (buttonState.value === previousButtonState.value) { return false; }
  47049. previousButtonState.value = buttonState.value;
  47050. return true;
  47051. }
  47052. });
  47053. },{"../constants":94,"../core/component":102,"../lib/three":150,"../utils/tracked-controls":178}],90:[function(_dereq_,module,exports){
  47054. var registerComponent = _dereq_('../core/component').registerComponent;
  47055. /**
  47056. * Visibility component.
  47057. */
  47058. module.exports.Component = registerComponent('visible', {
  47059. schema: {default: true},
  47060. update: function () {
  47061. this.el.object3D.visible = this.data;
  47062. }
  47063. });
  47064. },{"../core/component":102}],91:[function(_dereq_,module,exports){
  47065. var registerComponent = _dereq_('../core/component').registerComponent;
  47066. var utils = _dereq_('../utils/');
  47067. var bind = utils.bind;
  47068. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47069. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47070. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47071. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47072. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  47073. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  47074. var GAMEPAD_ID_PREFIX = 'OpenVR ';
  47075. /**
  47076. * Vive controls.
  47077. * Interface with Vive controllers and map Gamepad events to controller buttons:
  47078. * trackpad, trigger, grip, menu, system
  47079. * Load a controller model and highlight the pressed buttons.
  47080. */
  47081. module.exports.Component = registerComponent('vive-controls', {
  47082. schema: {
  47083. hand: {default: 'left'},
  47084. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  47085. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  47086. model: {default: true},
  47087. orientationOffset: {type: 'vec3'}
  47088. },
  47089. /**
  47090. * Button IDs:
  47091. * 0 - trackpad
  47092. * 1 - trigger (intensity value from 0.5 to 1)
  47093. * 2 - grip
  47094. * 3 - menu (dispatch but better for menu options)
  47095. * 4 - system (never dispatched on this layer)
  47096. */
  47097. mapping: {
  47098. axes: {trackpad: [0, 1]},
  47099. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  47100. },
  47101. init: function () {
  47102. var self = this;
  47103. this.animationActive = 'pointing';
  47104. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  47105. this.controllerPresent = false;
  47106. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  47107. this.lastControllerCheck = 0;
  47108. this.onButtonChanged = bind(this.onButtonChanged, this);
  47109. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47110. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47111. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47112. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47113. this.onAxisMoved = bind(this.onAxisMoved, this);
  47114. this.previousButtonValues = {};
  47115. this.bindMethods();
  47116. },
  47117. play: function () {
  47118. this.checkIfControllerPresent();
  47119. this.addControllersUpdateListener();
  47120. },
  47121. pause: function () {
  47122. this.removeEventListeners();
  47123. this.removeControllersUpdateListener();
  47124. },
  47125. bindMethods: function () {
  47126. this.onModelLoaded = bind(this.onModelLoaded, this);
  47127. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47128. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47129. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47130. this.onAxisMoved = bind(this.onAxisMoved, this);
  47131. },
  47132. addEventListeners: function () {
  47133. var el = this.el;
  47134. el.addEventListener('buttonchanged', this.onButtonChanged);
  47135. el.addEventListener('buttondown', this.onButtonDown);
  47136. el.addEventListener('buttonup', this.onButtonUp);
  47137. el.addEventListener('touchend', this.onButtonTouchEnd);
  47138. el.addEventListener('touchstart', this.onButtonTouchStart);
  47139. el.addEventListener('model-loaded', this.onModelLoaded);
  47140. el.addEventListener('axismove', this.onAxisMoved);
  47141. this.controllerEventsActive = true;
  47142. },
  47143. removeEventListeners: function () {
  47144. var el = this.el;
  47145. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47146. el.removeEventListener('buttondown', this.onButtonDown);
  47147. el.removeEventListener('buttonup', this.onButtonUp);
  47148. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47149. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47150. el.removeEventListener('model-loaded', this.onModelLoaded);
  47151. el.removeEventListener('axismove', this.onAxisMoved);
  47152. this.controllerEventsActive = false;
  47153. },
  47154. /**
  47155. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  47156. * var isPresent = this.checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  47157. { hand: data.hand });
  47158. * Until then, use hardcoded index.
  47159. */
  47160. checkIfControllerPresent: function () {
  47161. var data = this.data;
  47162. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47163. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex});
  47164. },
  47165. injectTrackedControls: function () {
  47166. var el = this.el;
  47167. var data = this.data;
  47168. // If we have an OpenVR Gamepad, use the fixed mapping.
  47169. el.setAttribute('tracked-controls', {
  47170. idPrefix: GAMEPAD_ID_PREFIX,
  47171. // Hand IDs: 0 = right, 1 = left, 2 = anything else.
  47172. controller: data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2,
  47173. orientationOffset: data.orientationOffset
  47174. });
  47175. // Load model.
  47176. if (!this.data.model) { return; }
  47177. this.el.setAttribute('obj-model', {
  47178. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  47179. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  47180. });
  47181. },
  47182. addControllersUpdateListener: function () {
  47183. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47184. },
  47185. removeControllersUpdateListener: function () {
  47186. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47187. },
  47188. onControllersUpdate: function () {
  47189. this.checkIfControllerPresent();
  47190. },
  47191. /**
  47192. * Rotate the trigger button based on how hard the trigger is pressed.
  47193. */
  47194. onButtonChanged: function (evt) {
  47195. var button = this.mapping.buttons[evt.detail.id];
  47196. var buttonMeshes = this.buttonMeshes;
  47197. var analogValue;
  47198. if (!button) { return; }
  47199. if (button === 'trigger') {
  47200. analogValue = evt.detail.state.value;
  47201. // Update trigger rotation depending on button value.
  47202. if (buttonMeshes && buttonMeshes.trigger) {
  47203. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  47204. }
  47205. }
  47206. // Pass along changed event with button state, using button mapping for convenience.
  47207. this.el.emit(button + 'changed', evt.detail.state);
  47208. },
  47209. onModelLoaded: function (evt) {
  47210. var buttonMeshes;
  47211. var controllerObject3D = evt.detail.model;
  47212. var self = this;
  47213. if (!this.data.model) { return; }
  47214. // Store button meshes object to be able to change their colors.
  47215. buttonMeshes = this.buttonMeshes = {};
  47216. buttonMeshes.grip = {
  47217. left: controllerObject3D.getObjectByName('leftgrip'),
  47218. right: controllerObject3D.getObjectByName('rightgrip')
  47219. };
  47220. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  47221. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  47222. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  47223. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  47224. // Set default colors.
  47225. Object.keys(buttonMeshes).forEach(function (buttonName) {
  47226. self.setButtonColor(buttonName, self.data.buttonColor);
  47227. });
  47228. // Offset pivot point.
  47229. controllerObject3D.position.set(0, -0.015, 0.04);
  47230. },
  47231. onAxisMoved: function (evt) {
  47232. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  47233. },
  47234. updateModel: function (buttonName, evtName) {
  47235. var color;
  47236. var isTouch;
  47237. if (!this.data.model) { return; }
  47238. isTouch = evtName.indexOf('touch') !== -1;
  47239. // Don't change color for trackpad touch.
  47240. if (isTouch) { return; }
  47241. // Update colors.
  47242. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  47243. this.setButtonColor(buttonName, color);
  47244. },
  47245. setButtonColor: function (buttonName, color) {
  47246. var buttonMeshes = this.buttonMeshes;
  47247. if (!buttonMeshes) { return; }
  47248. // Need to do both left and right sides for grip.
  47249. if (buttonName === 'grip') {
  47250. buttonMeshes.grip.left.material.color.set(color);
  47251. buttonMeshes.grip.right.material.color.set(color);
  47252. return;
  47253. }
  47254. buttonMeshes[buttonName].material.color.set(color);
  47255. }
  47256. });
  47257. },{"../core/component":102,"../utils/":172,"../utils/tracked-controls":178}],92:[function(_dereq_,module,exports){
  47258. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  47259. var registerComponent = _dereq_('../core/component').registerComponent;
  47260. var THREE = _dereq_('../lib/three');
  47261. var utils = _dereq_('../utils/');
  47262. var bind = utils.bind;
  47263. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  47264. var CLAMP_VELOCITY = 0.00001;
  47265. var MAX_DELTA = 0.2;
  47266. var KEYS = [
  47267. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  47268. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  47269. ];
  47270. /**
  47271. * WASD component to control entities using WASD keys.
  47272. */
  47273. module.exports.Component = registerComponent('wasd-controls', {
  47274. schema: {
  47275. acceleration: {default: 65},
  47276. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  47277. adEnabled: {default: true},
  47278. adInverted: {default: false},
  47279. easing: {default: 20},
  47280. enabled: {default: true},
  47281. fly: {default: false},
  47282. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  47283. wsEnabled: {default: true},
  47284. wsInverted: {default: false}
  47285. },
  47286. init: function () {
  47287. // To keep track of the pressed keys.
  47288. this.keys = {};
  47289. this.position = {};
  47290. this.velocity = new THREE.Vector3();
  47291. // Bind methods and add event listeners.
  47292. this.onBlur = bind(this.onBlur, this);
  47293. this.onFocus = bind(this.onFocus, this);
  47294. this.onKeyDown = bind(this.onKeyDown, this);
  47295. this.onKeyUp = bind(this.onKeyUp, this);
  47296. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  47297. this.attachVisibilityEventListeners();
  47298. },
  47299. tick: function (time, delta) {
  47300. var currentPosition;
  47301. var data = this.data;
  47302. var el = this.el;
  47303. var movementVector;
  47304. var position = this.position;
  47305. var velocity = this.velocity;
  47306. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  47307. isEmptyObject(this.keys)) { return; }
  47308. // Update velocity.
  47309. delta = delta / 1000;
  47310. this.updateVelocity(delta);
  47311. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  47312. // Get movement vector and translate position.
  47313. currentPosition = el.getAttribute('position');
  47314. movementVector = this.getMovementVector(delta);
  47315. position.x = currentPosition.x + movementVector.x;
  47316. position.y = currentPosition.y + movementVector.y;
  47317. position.z = currentPosition.z + movementVector.z;
  47318. el.setAttribute('position', position);
  47319. },
  47320. remove: function () {
  47321. this.removeKeyEventListeners();
  47322. this.removeVisibilityEventListeners();
  47323. },
  47324. play: function () {
  47325. this.attachKeyEventListeners();
  47326. },
  47327. pause: function () {
  47328. this.keys = {};
  47329. this.removeKeyEventListeners();
  47330. },
  47331. updateVelocity: function (delta) {
  47332. var acceleration;
  47333. var adAxis;
  47334. var adSign;
  47335. var data = this.data;
  47336. var keys = this.keys;
  47337. var velocity = this.velocity;
  47338. var wsAxis;
  47339. var wsSign;
  47340. adAxis = data.adAxis;
  47341. wsAxis = data.wsAxis;
  47342. // If FPS too low, reset velocity.
  47343. if (delta > MAX_DELTA) {
  47344. velocity[adAxis] = 0;
  47345. velocity[wsAxis] = 0;
  47346. return;
  47347. }
  47348. // Decay velocity.
  47349. if (velocity[adAxis] !== 0) {
  47350. velocity[adAxis] -= velocity[adAxis] * data.easing * delta;
  47351. }
  47352. if (velocity[wsAxis] !== 0) {
  47353. velocity[wsAxis] -= velocity[wsAxis] * data.easing * delta;
  47354. }
  47355. // Clamp velocity easing.
  47356. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  47357. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  47358. if (!data.enabled) { return; }
  47359. // Update velocity using keys pressed.
  47360. acceleration = data.acceleration;
  47361. if (data.adEnabled) {
  47362. adSign = data.adInverted ? -1 : 1;
  47363. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  47364. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  47365. }
  47366. if (data.wsEnabled) {
  47367. wsSign = data.wsInverted ? -1 : 1;
  47368. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  47369. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  47370. }
  47371. },
  47372. getMovementVector: (function () {
  47373. var directionVector = new THREE.Vector3(0, 0, 0);
  47374. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  47375. return function (delta) {
  47376. var rotation = this.el.getAttribute('rotation');
  47377. var velocity = this.velocity;
  47378. var xRotation;
  47379. directionVector.copy(velocity);
  47380. directionVector.multiplyScalar(delta);
  47381. // Absolute.
  47382. if (!rotation) { return directionVector; }
  47383. xRotation = this.data.fly ? rotation.x : 0;
  47384. // Transform direction relative to heading.
  47385. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  47386. directionVector.applyEuler(rotationEuler);
  47387. return directionVector;
  47388. };
  47389. })(),
  47390. attachVisibilityEventListeners: function () {
  47391. window.addEventListener('blur', this.onBlur);
  47392. window.addEventListener('focus', this.onFocus);
  47393. document.addEventListener('visibilitychange', this.onVisibilityChange);
  47394. },
  47395. removeVisibilityEventListeners: function () {
  47396. window.removeEventListener('blur', this.onBlur);
  47397. window.removeEventListener('focus', this.onFocus);
  47398. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  47399. },
  47400. attachKeyEventListeners: function () {
  47401. window.addEventListener('keydown', this.onKeyDown);
  47402. window.addEventListener('keyup', this.onKeyUp);
  47403. },
  47404. removeKeyEventListeners: function () {
  47405. window.removeEventListener('keydown', this.onKeyDown);
  47406. window.removeEventListener('keyup', this.onKeyUp);
  47407. },
  47408. onBlur: function () {
  47409. this.pause();
  47410. },
  47411. onFocus: function () {
  47412. this.play();
  47413. },
  47414. onVisibilityChange: function () {
  47415. if (document.hidden) {
  47416. this.onBlur();
  47417. } else {
  47418. this.onFocus();
  47419. }
  47420. },
  47421. onKeyDown: function (event) {
  47422. var code;
  47423. if (!shouldCaptureKeyEvent(event)) { return; }
  47424. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47425. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  47426. },
  47427. onKeyUp: function (event) {
  47428. var code;
  47429. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47430. delete this.keys[code];
  47431. }
  47432. });
  47433. function isEmptyObject (keys) {
  47434. var key;
  47435. for (key in keys) { return false; }
  47436. return true;
  47437. }
  47438. },{"../constants":94,"../core/component":102,"../lib/three":150,"../utils/":172}],93:[function(_dereq_,module,exports){
  47439. /* global THREE */
  47440. var bind = _dereq_('../utils/bind');
  47441. var registerComponent = _dereq_('../core/component').registerComponent;
  47442. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47443. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47444. var utils = _dereq_('../utils/');
  47445. var debug = utils.debug('components:windows-motion-controls:debug');
  47446. var warn = utils.debug('components:windows-motion-controls:warn');
  47447. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  47448. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  47449. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  47450. var GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  47451. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  47452. /**
  47453. * Windows Motion Controller controls.
  47454. * Interface with Windows Motion Controller controllers and map Gamepad events to
  47455. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  47456. * Load a controller model and transform the pressed buttons.
  47457. */
  47458. module.exports.Component = registerComponent('windows-motion-controls', {
  47459. schema: {
  47460. hand: {default: DEFAULT_HANDEDNESS},
  47461. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  47462. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  47463. pair: {default: 0},
  47464. // If true, loads the controller glTF asset.
  47465. model: {default: true},
  47466. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  47467. hideDisconnected: {default: true}
  47468. },
  47469. mapping: {
  47470. // A-Frame specific semantic axis names
  47471. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  47472. // A-Frame specific semantic button names
  47473. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  47474. // A mapping of the semantic name to node name in the glTF model file,
  47475. // that should be transformed by axis value.
  47476. // This array mirrors the browser Gamepad.axes array, such that
  47477. // the mesh corresponding to axis 0 is in this array index 0.
  47478. axisMeshNames: [
  47479. 'THUMBSTICK_X',
  47480. 'THUMBSTICK_Y',
  47481. 'TOUCHPAD_TOUCH_X',
  47482. 'TOUCHPAD_TOUCH_Y'
  47483. ],
  47484. // A mapping of the semantic name to button node name in the glTF model file,
  47485. // that should be transformed by button value.
  47486. buttonMeshNames: {
  47487. 'trigger': 'SELECT',
  47488. 'menu': 'MENU',
  47489. 'grip': 'GRASP',
  47490. 'thumbstick': 'THUMBSTICK_PRESS',
  47491. 'trackpad': 'TOUCHPAD_PRESS'
  47492. },
  47493. pointingPoseMeshName: 'POINTING_POSE'
  47494. },
  47495. bindMethods: function () {
  47496. this.onModelError = bind(this.onModelError, this);
  47497. this.onModelLoaded = bind(this.onModelLoaded, this);
  47498. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47499. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47500. this.onAxisMoved = bind(this.onAxisMoved, this);
  47501. },
  47502. init: function () {
  47503. var self = this;
  47504. var el = this.el;
  47505. this.onButtonChanged = bind(this.onButtonChanged, this);
  47506. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47507. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47508. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47509. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47510. this.onControllerConnected = function () { self.setModelVisibility(true); };
  47511. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  47512. this.controllerPresent = false;
  47513. this.lastControllerCheck = 0;
  47514. this.previousButtonValues = {};
  47515. this.bindMethods();
  47516. // Cache for submeshes that we have looked up by name.
  47517. this.loadedMeshInfo = {
  47518. buttonMeshes: null,
  47519. axisMeshes: null
  47520. };
  47521. // Pointing poses
  47522. this.rayOrigin = {
  47523. origin: new THREE.Vector3(),
  47524. direction: new THREE.Vector3(0, 0, -1),
  47525. createdFromMesh: false
  47526. };
  47527. // Stored on object to allow for mocking in tests
  47528. this.emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47529. this.checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47530. el.addEventListener('controllerconnected', this.onControllerConnected);
  47531. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  47532. },
  47533. addEventListeners: function () {
  47534. var el = this.el;
  47535. el.addEventListener('buttonchanged', this.onButtonChanged);
  47536. el.addEventListener('buttondown', this.onButtonDown);
  47537. el.addEventListener('buttonup', this.onButtonUp);
  47538. el.addEventListener('touchstart', this.onButtonTouchStart);
  47539. el.addEventListener('touchend', this.onButtonTouchEnd);
  47540. el.addEventListener('axismove', this.onAxisMoved);
  47541. el.addEventListener('model-error', this.onModelError);
  47542. el.addEventListener('model-loaded', this.onModelLoaded);
  47543. this.controllerEventsActive = true;
  47544. },
  47545. removeEventListeners: function () {
  47546. var el = this.el;
  47547. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47548. el.removeEventListener('buttondown', this.onButtonDown);
  47549. el.removeEventListener('buttonup', this.onButtonUp);
  47550. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47551. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47552. el.removeEventListener('axismove', this.onAxisMoved);
  47553. el.removeEventListener('model-error', this.onModelError);
  47554. el.removeEventListener('model-loaded', this.onModelLoaded);
  47555. this.controllerEventsActive = false;
  47556. },
  47557. checkIfControllerPresent: function () {
  47558. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  47559. hand: this.data.hand,
  47560. index: this.data.pair
  47561. });
  47562. },
  47563. play: function () {
  47564. this.checkIfControllerPresent();
  47565. this.addControllersUpdateListener();
  47566. },
  47567. pause: function () {
  47568. this.removeEventListeners();
  47569. this.removeControllersUpdateListener();
  47570. },
  47571. updateControllerModel: function () {
  47572. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  47573. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  47574. this.modelReady();
  47575. return;
  47576. }
  47577. var sourceUrl = this.createControllerModelUrl();
  47578. this.loadModel(sourceUrl);
  47579. },
  47580. /**
  47581. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  47582. * art assets.
  47583. */
  47584. createControllerModelUrl: function (forceDefault) {
  47585. // Determine the device specific folder based on the ID suffix
  47586. var trackedControlsComponent = this.el.components['tracked-controls'];
  47587. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  47588. var device = 'default';
  47589. var hand = this.data.hand;
  47590. var filename;
  47591. if (controller) {
  47592. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  47593. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  47594. // In this case, we want to load the universal model, so need to get the '' from the controller.
  47595. hand = controller.hand;
  47596. if (!forceDefault) {
  47597. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  47598. device = ((match && match[0]) || device);
  47599. }
  47600. }
  47601. // Hand
  47602. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  47603. // Final url
  47604. return MODEL_BASE_URL + device + '/' + filename;
  47605. },
  47606. injectTrackedControls: function () {
  47607. var data = this.data;
  47608. this.el.setAttribute('tracked-controls', {
  47609. idPrefix: GAMEPAD_ID_PREFIX,
  47610. controller: data.pair,
  47611. hand: data.hand,
  47612. armModel: false
  47613. });
  47614. this.updateControllerModel();
  47615. },
  47616. addControllersUpdateListener: function () {
  47617. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47618. },
  47619. removeControllersUpdateListener: function () {
  47620. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47621. },
  47622. onControllersUpdate: function () {
  47623. this.checkIfControllerPresent();
  47624. },
  47625. onModelError: function (evt) {
  47626. var defaultUrl = this.createControllerModelUrl(true);
  47627. if (evt.detail.src !== defaultUrl) {
  47628. warn('Failed to load controller model for device, attempting to load default.');
  47629. this.loadModel(defaultUrl);
  47630. } else {
  47631. warn('Failed to load default controller model.');
  47632. }
  47633. },
  47634. loadModel: function (url) {
  47635. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  47636. // removed and re-loaded if the given url changes.
  47637. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  47638. },
  47639. onModelLoaded: function (evt) {
  47640. var rootNode = this.controllerModel = evt.detail.model;
  47641. var loadedMeshInfo = this.loadedMeshInfo;
  47642. var i;
  47643. var meshName;
  47644. var mesh;
  47645. var meshInfo;
  47646. debug('Processing model');
  47647. // Reset the caches
  47648. loadedMeshInfo.buttonMeshes = {};
  47649. loadedMeshInfo.axisMeshes = {};
  47650. // Cache our meshes so we aren't traversing the hierarchy per frame
  47651. if (rootNode) {
  47652. // Button Meshes
  47653. for (i = 0; i < this.mapping.buttons.length; i++) {
  47654. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  47655. if (!meshName) {
  47656. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  47657. continue;
  47658. }
  47659. mesh = rootNode.getObjectByName(meshName);
  47660. if (!mesh) {
  47661. warn('Missing button mesh with name: ' + meshName);
  47662. continue;
  47663. }
  47664. meshInfo = {
  47665. index: i,
  47666. value: getImmediateChildByName(mesh, 'VALUE'),
  47667. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  47668. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  47669. };
  47670. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  47671. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  47672. } else {
  47673. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  47674. warn('Missing button submesh under mesh with name: ' + meshName +
  47675. '(VALUE: ' + !!meshInfo.value +
  47676. ', PRESSED: ' + !!meshInfo.pressed +
  47677. ', UNPRESSED:' + !!meshInfo.unpressed +
  47678. ')');
  47679. }
  47680. }
  47681. // Axis Meshes
  47682. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  47683. meshName = this.mapping.axisMeshNames[i];
  47684. if (!meshName) {
  47685. debug('Skipping unknown axis at index: ' + i);
  47686. continue;
  47687. }
  47688. mesh = rootNode.getObjectByName(meshName);
  47689. if (!mesh) {
  47690. warn('Missing axis mesh with name: ' + meshName);
  47691. continue;
  47692. }
  47693. meshInfo = {
  47694. index: i,
  47695. value: getImmediateChildByName(mesh, 'VALUE'),
  47696. min: getImmediateChildByName(mesh, 'MIN'),
  47697. max: getImmediateChildByName(mesh, 'MAX')
  47698. };
  47699. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  47700. loadedMeshInfo.axisMeshes[i] = meshInfo;
  47701. } else {
  47702. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  47703. warn('Missing axis submesh under mesh with name: ' + meshName +
  47704. '(VALUE: ' + !!meshInfo.value +
  47705. ', MIN: ' + !!meshInfo.min +
  47706. ', MAX:' + !!meshInfo.max +
  47707. ')');
  47708. }
  47709. }
  47710. this.calculateRayOriginFromMesh(rootNode);
  47711. // Determine if the model has to be visible or not.
  47712. this.setModelVisibility();
  47713. }
  47714. debug('Model load complete.');
  47715. // Look through only immediate children. This will return null if no mesh exists with the given name.
  47716. function getImmediateChildByName (object3d, value) {
  47717. for (var i = 0, l = object3d.children.length; i < l; i++) {
  47718. var obj = object3d.children[i];
  47719. if (obj && obj['name'] === value) {
  47720. return obj;
  47721. }
  47722. }
  47723. return undefined;
  47724. }
  47725. },
  47726. calculateRayOriginFromMesh: (function () {
  47727. var quaternion = new THREE.Quaternion();
  47728. return function (rootNode) {
  47729. var mesh;
  47730. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  47731. // in the glTF (assumes that root node is at world origin)
  47732. this.rayOrigin.origin.set(0, 0, 0);
  47733. this.rayOrigin.direction.set(0, 0, -1);
  47734. this.rayOrigin.createdFromMesh = true;
  47735. // Try to read Pointing pose from the source model
  47736. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  47737. if (mesh) {
  47738. var parent = rootNode.parent;
  47739. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  47740. if (parent) {
  47741. rootNode.parent = null;
  47742. rootNode.updateMatrixWorld(true);
  47743. rootNode.parent = parent;
  47744. }
  47745. mesh.getWorldPosition(this.rayOrigin.origin);
  47746. mesh.getWorldQuaternion(quaternion);
  47747. this.rayOrigin.direction.applyQuaternion(quaternion);
  47748. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  47749. if (parent) {
  47750. rootNode.updateMatrixWorld(true);
  47751. }
  47752. } else {
  47753. debug('Mesh does not contain pointing origin data, defaulting to none.');
  47754. }
  47755. // Emit event stating that our pointing ray is now accurate.
  47756. this.modelReady();
  47757. };
  47758. })(),
  47759. lerpAxisTransform: (function () {
  47760. var quaternion = new THREE.Quaternion();
  47761. return function (axis, axisValue) {
  47762. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  47763. if (!axisMeshInfo) return;
  47764. var min = axisMeshInfo.min;
  47765. var max = axisMeshInfo.max;
  47766. var target = axisMeshInfo.value;
  47767. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  47768. var lerpValue = axisValue * 0.5 + 0.5;
  47769. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  47770. target.position.lerpVectors(min.position, max.position, lerpValue);
  47771. };
  47772. })(),
  47773. lerpButtonTransform: (function () {
  47774. var quaternion = new THREE.Quaternion();
  47775. return function (buttonName, buttonValue) {
  47776. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  47777. if (!buttonMeshInfo) return;
  47778. var min = buttonMeshInfo.unpressed;
  47779. var max = buttonMeshInfo.pressed;
  47780. var target = buttonMeshInfo.value;
  47781. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  47782. target.position.lerpVectors(min.position, max.position, buttonValue);
  47783. };
  47784. })(),
  47785. modelReady: function () {
  47786. this.el.emit('controllermodelready', {
  47787. name: 'windows-motion-controls',
  47788. model: this.data.model,
  47789. rayOrigin: this.rayOrigin
  47790. });
  47791. },
  47792. onButtonChanged: function (evt) {
  47793. var buttonName = this.mapping.buttons[evt.detail.id];
  47794. if (buttonName) {
  47795. // Update the button mesh transform
  47796. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  47797. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  47798. }
  47799. // Only emit events for buttons that we know how to map from index to name
  47800. this.el.emit(buttonName + 'changed', evt.detail.state);
  47801. }
  47802. },
  47803. onAxisMoved: function (evt) {
  47804. var numAxes = this.mapping.axisMeshNames.length;
  47805. // Only attempt to update meshes if we have valid data.
  47806. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  47807. for (var axis = 0; axis < numAxes; axis++) {
  47808. // Update the button mesh transform
  47809. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  47810. }
  47811. }
  47812. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  47813. },
  47814. setModelVisibility: function (visible) {
  47815. var model = this.el.getObject3D('mesh');
  47816. visible = visible !== undefined ? visible : this.modelVisible;
  47817. this.modelVisible = visible;
  47818. if (!model) { return; }
  47819. model.visible = visible;
  47820. }
  47821. });
  47822. },{"../constants":94,"../core/component":102,"../utils/":172,"../utils/bind":166,"../utils/tracked-controls":178}],94:[function(_dereq_,module,exports){
  47823. module.exports = {
  47824. AFRAME_INJECTED: 'aframe-injected',
  47825. DEFAULT_CAMERA_HEIGHT: 1.6,
  47826. DEFAULT_HANDEDNESS: 'right',
  47827. keyboardevent: _dereq_('./keyboardevent')
  47828. };
  47829. },{"./keyboardevent":95}],95:[function(_dereq_,module,exports){
  47830. module.exports = {
  47831. // Tiny KeyboardEvent.code polyfill.
  47832. KEYCODE_TO_CODE: {
  47833. '38': 'ArrowUp',
  47834. '37': 'ArrowLeft',
  47835. '40': 'ArrowDown',
  47836. '39': 'ArrowRight',
  47837. '87': 'KeyW',
  47838. '65': 'KeyA',
  47839. '83': 'KeyS',
  47840. '68': 'KeyD'
  47841. }
  47842. };
  47843. },{}],96:[function(_dereq_,module,exports){
  47844. var ANode = _dereq_('./a-node');
  47845. var bind = _dereq_('../utils/bind');
  47846. var debug = _dereq_('../utils/debug');
  47847. var registerElement = _dereq_('./a-register-element').registerElement;
  47848. var THREE = _dereq_('../lib/three');
  47849. var fileLoader = new THREE.FileLoader();
  47850. var warn = debug('core:a-assets:warn');
  47851. /**
  47852. * Asset management system. Handles blocking on asset loading.
  47853. */
  47854. module.exports = registerElement('a-assets', {
  47855. prototype: Object.create(ANode.prototype, {
  47856. createdCallback: {
  47857. value: function () {
  47858. this.isAssets = true;
  47859. this.fileLoader = fileLoader;
  47860. this.timeout = null;
  47861. }
  47862. },
  47863. attachedCallback: {
  47864. value: function () {
  47865. var self = this;
  47866. var i;
  47867. var loaded = [];
  47868. var mediaEl;
  47869. var mediaEls;
  47870. var imgEl;
  47871. var imgEls;
  47872. var timeout;
  47873. if (!this.parentNode.isScene) {
  47874. throw new Error('<a-assets> must be a child of a <a-scene>.');
  47875. }
  47876. // Wait for <img>s.
  47877. imgEls = this.querySelectorAll('img');
  47878. for (i = 0; i < imgEls.length; i++) {
  47879. imgEl = fixUpMediaElement(imgEls[i]);
  47880. loaded.push(new Promise(function (resolve, reject) {
  47881. // Set in cache because we won't be needing to call three.js loader if we have.
  47882. // a loaded media element.
  47883. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  47884. imgEl.onload = resolve;
  47885. imgEl.onerror = reject;
  47886. }));
  47887. }
  47888. // Wait for <audio>s and <video>s.
  47889. mediaEls = this.querySelectorAll('audio, video');
  47890. for (i = 0; i < mediaEls.length; i++) {
  47891. mediaEl = fixUpMediaElement(mediaEls[i]);
  47892. if (!mediaEl.src && !mediaEl.srcObject) {
  47893. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  47894. }
  47895. loaded.push(mediaElementLoaded(mediaEl));
  47896. }
  47897. // Trigger loaded for scene to start rendering.
  47898. Promise.all(loaded).then(bind(this.load, this));
  47899. // Timeout to start loading anyways.
  47900. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  47901. this.timeout = setTimeout(function () {
  47902. if (self.hasLoaded) { return; }
  47903. warn('Asset loading timed out in ', timeout, 'ms');
  47904. self.emit('timeout');
  47905. self.load();
  47906. }, timeout);
  47907. }
  47908. },
  47909. detachedCallback: {
  47910. value: function () {
  47911. if (this.timeout) { clearTimeout(this.timeout); }
  47912. }
  47913. },
  47914. load: {
  47915. value: function () {
  47916. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  47917. return el.isAssetItem && el.hasAttribute('src');
  47918. });
  47919. }
  47920. }
  47921. })
  47922. });
  47923. /**
  47924. * Preload using XHRLoader for any type of asset.
  47925. */
  47926. registerElement('a-asset-item', {
  47927. prototype: Object.create(ANode.prototype, {
  47928. createdCallback: {
  47929. value: function () {
  47930. this.data = null;
  47931. this.isAssetItem = true;
  47932. }
  47933. },
  47934. attachedCallback: {
  47935. value: function () {
  47936. var self = this;
  47937. var src = this.getAttribute('src');
  47938. fileLoader.setResponseType(
  47939. this.getAttribute('response-type') || inferResponseType(src));
  47940. fileLoader.load(src, function handleOnLoad (response) {
  47941. self.data = response;
  47942. /*
  47943. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  47944. previous one closes, the second request never finishes.
  47945. setTimeout finishes the first request and lets the logic triggered by load open
  47946. subsequent requests.
  47947. setTimeout can be removed once the fix for the bug below ships:
  47948. 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
  47949. */
  47950. setTimeout(function load () { ANode.prototype.load.call(self); });
  47951. }, function handleOnProgress (xhr) {
  47952. self.emit('progress', {
  47953. loadedBytes: xhr.loaded,
  47954. totalBytes: xhr.total,
  47955. xhr: xhr
  47956. });
  47957. }, function handleOnError (xhr) {
  47958. self.emit('error', {xhr: xhr});
  47959. });
  47960. }
  47961. }
  47962. })
  47963. });
  47964. /**
  47965. * Create a Promise that resolves once the media element has finished buffering.
  47966. *
  47967. * @param {Element} el - HTMLMediaElement.
  47968. * @returns {Promise}
  47969. */
  47970. function mediaElementLoaded (el) {
  47971. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  47972. return;
  47973. }
  47974. // If media specifies autoplay or preload, wait until media is completely buffered.
  47975. return new Promise(function (resolve, reject) {
  47976. if (el.readyState === 4) { return resolve(); } // Already loaded.
  47977. if (el.error) { return reject(); } // Error.
  47978. el.addEventListener('loadeddata', checkProgress, false);
  47979. el.addEventListener('progress', checkProgress, false);
  47980. el.addEventListener('error', reject, false);
  47981. function checkProgress () {
  47982. // Add up the seconds buffered.
  47983. var secondsBuffered = 0;
  47984. for (var i = 0; i < el.buffered.length; i++) {
  47985. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  47986. }
  47987. // Compare seconds buffered to media duration.
  47988. if (secondsBuffered >= el.duration) {
  47989. // Set in cache because we won't be needing to call three.js loader if we have.
  47990. // a loaded media element.
  47991. // Store video elements only. three.js loader is used for audio elements.
  47992. // See assetParse too.
  47993. if (el.tagName === 'VIDEO') {
  47994. THREE.Cache.files[el.getAttribute('src')] = el;
  47995. }
  47996. resolve();
  47997. }
  47998. }
  47999. });
  48000. }
  48001. /**
  48002. * Automatically add attributes to media elements where convenient.
  48003. * crossorigin, playsinline.
  48004. */
  48005. function fixUpMediaElement (mediaEl) {
  48006. // Cross-origin.
  48007. var newMediaEl = setCrossOrigin(mediaEl);
  48008. // Plays inline for mobile.
  48009. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  48010. newMediaEl.setAttribute('playsinline', '');
  48011. newMediaEl.setAttribute('webkit-playsinline', '');
  48012. }
  48013. if (newMediaEl !== mediaEl) {
  48014. mediaEl.parentNode.appendChild(newMediaEl);
  48015. mediaEl.parentNode.removeChild(mediaEl);
  48016. }
  48017. return newMediaEl;
  48018. }
  48019. /**
  48020. * Automatically set `crossorigin` if not defined on the media element.
  48021. * If it is not defined, we must create and re-append a new media element <img> and
  48022. * have the browser re-request it with `crossorigin` set.
  48023. *
  48024. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  48025. * @returns {Element} Media element to be used to listen to for loaded events.
  48026. */
  48027. function setCrossOrigin (mediaEl) {
  48028. var newMediaEl;
  48029. var src;
  48030. // Already has crossorigin set.
  48031. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  48032. src = mediaEl.getAttribute('src');
  48033. if (src !== null) {
  48034. // Does not have protocol.
  48035. if (src.indexOf('://') === -1) { return mediaEl; }
  48036. // Determine if cross origin is actually needed.
  48037. if (extractDomain(src) === window.location.host) { return mediaEl; }
  48038. }
  48039. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  48040. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  48041. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  48042. mediaEl.crossOrigin = 'anonymous';
  48043. newMediaEl = mediaEl.cloneNode(true);
  48044. return newMediaEl;
  48045. }
  48046. /**
  48047. * Extract domain out of URL.
  48048. *
  48049. * @param {string} url
  48050. * @returns {string}
  48051. */
  48052. function extractDomain (url) {
  48053. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  48054. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  48055. // Find and remove port number.
  48056. return domain.substring(0, domain.indexOf(':'));
  48057. }
  48058. /**
  48059. * Infer response-type attribute from src.
  48060. * Default is text(default XMLHttpRequest.responseType)
  48061. * but we use arraybuffer for .gltf and .glb files
  48062. * because of THREE.GLTFLoader specification.
  48063. *
  48064. * @param {string} src
  48065. * @returns {string}
  48066. */
  48067. function inferResponseType (src) {
  48068. var dotLastIndex = src.lastIndexOf('.');
  48069. if (dotLastIndex >= 0) {
  48070. var extension = src.slice(dotLastIndex, src.length);
  48071. if (extension === '.gltf' || extension === '.glb') {
  48072. return 'arraybuffer';
  48073. }
  48074. }
  48075. return 'text';
  48076. }
  48077. module.exports.inferResponseType = inferResponseType;
  48078. },{"../lib/three":150,"../utils/bind":166,"../utils/debug":168,"./a-node":100,"./a-register-element":101}],97:[function(_dereq_,module,exports){
  48079. var debug = _dereq_('../utils/debug');
  48080. var registerElement = _dereq_('./a-register-element').registerElement;
  48081. var warn = debug('core:cubemap:warn');
  48082. /**
  48083. * Cubemap element that handles validation and exposes list of URLs.
  48084. * Does not listen to updates.
  48085. */
  48086. module.exports = registerElement('a-cubemap', {
  48087. prototype: Object.create(window.HTMLElement.prototype, {
  48088. /**
  48089. * Calculates this.srcs.
  48090. */
  48091. attachedCallback: {
  48092. value: function () {
  48093. this.srcs = this.validate();
  48094. },
  48095. writable: window.debug
  48096. },
  48097. /**
  48098. * Checks for exactly six elements with [src].
  48099. * Does not check explicitly for <img>s in case user does not want
  48100. * prefetching.
  48101. *
  48102. * @returns {Array|null} - six URLs if valid, else null.
  48103. */
  48104. validate: {
  48105. value: function () {
  48106. var elements = this.querySelectorAll('[src]');
  48107. var i;
  48108. var srcs = [];
  48109. if (elements.length === 6) {
  48110. for (i = 0; i < elements.length; i++) {
  48111. srcs.push(elements[i].getAttribute('src'));
  48112. }
  48113. return srcs;
  48114. }
  48115. // Else if there are not six elements, throw a warning.
  48116. warn(
  48117. '<a-cubemap> did not contain exactly six elements each with a ' +
  48118. '`src` attribute.');
  48119. },
  48120. writable: window.debug
  48121. }
  48122. })
  48123. });
  48124. },{"../utils/debug":168,"./a-register-element":101}],98:[function(_dereq_,module,exports){
  48125. var ANode = _dereq_('./a-node');
  48126. var COMPONENTS = _dereq_('./component').components;
  48127. var registerElement = _dereq_('./a-register-element').registerElement;
  48128. var THREE = _dereq_('../lib/three');
  48129. var utils = _dereq_('../utils/');
  48130. var AEntity;
  48131. var debug = utils.debug('core:a-entity:debug');
  48132. var warn = utils.debug('core:a-entity:warn');
  48133. var MULTIPLE_COMPONENT_DELIMITER = '__';
  48134. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  48135. /**
  48136. * Entity is a container object that components are plugged into to comprise everything in
  48137. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  48138. *
  48139. * To be able to take components, the scene element inherits from the entity definition.
  48140. *
  48141. * @member {object} components - entity's currently initialized components.
  48142. * @member {object} object3D - three.js object.
  48143. * @member {array} states
  48144. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  48145. */
  48146. var proto = Object.create(ANode.prototype, {
  48147. createdCallback: {
  48148. value: function () {
  48149. this.components = {};
  48150. // To avoid double initializations and infinite loops.
  48151. this.initializingComponents = {};
  48152. this.componentsToUpdate = {};
  48153. this.isEntity = true;
  48154. this.isPlaying = false;
  48155. this.object3D = new THREE.Group();
  48156. this.object3D.el = this;
  48157. this.object3DMap = {};
  48158. this.parentEl = null;
  48159. this.rotationObj = {};
  48160. this.states = [];
  48161. }
  48162. },
  48163. /**
  48164. * Handle changes coming from the browser DOM inspector.
  48165. */
  48166. attributeChangedCallback: {
  48167. value: function (attr, oldVal, newVal) {
  48168. var component = this.components[attr];
  48169. // If the empty string is passed by the component initialization
  48170. // logic we ignore the component update.
  48171. if (component && component.justInitialized && newVal === '') {
  48172. delete component.justInitialized;
  48173. return;
  48174. }
  48175. // When a component is removed after calling el.removeAttribute('material')
  48176. if (!component && newVal === null) { return; }
  48177. this.setEntityAttribute(attr, oldVal, newVal);
  48178. }
  48179. },
  48180. /**
  48181. * Add to parent, load, play.
  48182. */
  48183. attachedCallback: {
  48184. value: function () {
  48185. var assetsEl; // Asset management system element.
  48186. var sceneEl = this.sceneEl;
  48187. var self = this; // Component.
  48188. this.addToParent();
  48189. // Don't .load() scene on attachedCallback.
  48190. if (this.isScene) { return; }
  48191. // Gracefully not error when outside of <a-scene> (e.g., tests).
  48192. if (!sceneEl) {
  48193. this.load();
  48194. return;
  48195. }
  48196. // Wait for asset management system to finish before loading.
  48197. assetsEl = sceneEl.querySelector('a-assets');
  48198. if (assetsEl && !assetsEl.hasLoaded) {
  48199. assetsEl.addEventListener('loaded', function () { self.load(); });
  48200. return;
  48201. }
  48202. this.load();
  48203. }
  48204. },
  48205. /**
  48206. * Tell parent to remove this element's object3D from its object3D.
  48207. * Do not call on scene element because that will cause a call to document.body.remove().
  48208. */
  48209. detachedCallback: {
  48210. value: function () {
  48211. var componentName;
  48212. if (!this.parentEl) { return; }
  48213. // Remove components.
  48214. for (componentName in this.components) { this.removeComponent(componentName); }
  48215. if (this.isScene) { return; }
  48216. this.removeFromParent();
  48217. ANode.prototype.detachedCallback.call(this);
  48218. // Remove cyclic reference.
  48219. this.object3D.el = null;
  48220. }
  48221. },
  48222. /**
  48223. * Apply mixin to component.
  48224. */
  48225. handleMixinUpdate: {
  48226. value: function (attrName) {
  48227. if (!attrName) {
  48228. this.updateComponents();
  48229. return;
  48230. }
  48231. this.updateComponent(attrName, this.getDOMAttribute(attrName));
  48232. }
  48233. },
  48234. getObject3D: {
  48235. value: function (type) {
  48236. return this.object3DMap[type];
  48237. }
  48238. },
  48239. /**
  48240. * Set a THREE.Object3D into the map.
  48241. *
  48242. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  48243. * @param {object} obj - A THREE.Object3D.
  48244. */
  48245. setObject3D: {
  48246. value: function (type, obj) {
  48247. var oldObj;
  48248. var self = this;
  48249. if (!(obj instanceof THREE.Object3D)) {
  48250. throw new Error(
  48251. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  48252. 'THREE.Object3D.'
  48253. );
  48254. }
  48255. // Remove existing object of the type.
  48256. oldObj = this.getObject3D(type);
  48257. if (oldObj) { this.object3D.remove(oldObj); }
  48258. // Set references to A-Frame entity.
  48259. obj.el = this;
  48260. if (obj.children.length) {
  48261. obj.traverse(function bindEl (child) {
  48262. child.el = self;
  48263. });
  48264. }
  48265. // Add.
  48266. this.object3D.add(obj);
  48267. this.object3DMap[type] = obj;
  48268. this.emit('object3dset', {object: obj, type: type});
  48269. }
  48270. },
  48271. /**
  48272. * Remove object from scene and entity object3D map.
  48273. */
  48274. removeObject3D: {
  48275. value: function (type) {
  48276. var obj = this.getObject3D(type);
  48277. if (!obj) {
  48278. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  48279. return;
  48280. }
  48281. this.object3D.remove(obj);
  48282. delete this.object3DMap[type];
  48283. this.emit('object3dremove', {type: type});
  48284. }
  48285. },
  48286. /**
  48287. * Gets or creates an object3D of a given type.
  48288. *
  48289. * @param {string} type - Type of the object3D.
  48290. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  48291. * @returns {object}
  48292. */
  48293. getOrCreateObject3D: {
  48294. value: function (type, Constructor) {
  48295. var object3D = this.getObject3D(type);
  48296. if (!object3D && Constructor) {
  48297. object3D = new Constructor();
  48298. this.setObject3D(type, object3D);
  48299. }
  48300. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  48301. 'and `object3dset` event instead.');
  48302. return object3D;
  48303. }
  48304. },
  48305. /**
  48306. * Add child entity.
  48307. *
  48308. * @param {Element} el - Child entity.
  48309. */
  48310. add: {
  48311. value: function (el) {
  48312. if (!el.object3D) {
  48313. throw new Error("Trying to add an element that doesn't have an `object3D`");
  48314. }
  48315. this.object3D.add(el.object3D);
  48316. this.emit('child-attached', {el: el});
  48317. }
  48318. },
  48319. /**
  48320. * Tell parentNode to add this entity to itself.
  48321. */
  48322. addToParent: {
  48323. value: function () {
  48324. var parentNode = this.parentEl = this.parentNode;
  48325. // `!parentNode` check primarily for unit tests.
  48326. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  48327. parentNode.add(this);
  48328. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  48329. }
  48330. },
  48331. /**
  48332. * Tell parentNode to remove this entity from itself.
  48333. */
  48334. removeFromParent: {
  48335. value: function () {
  48336. var parentEl = this.parentEl;
  48337. this.parentEl.remove(this);
  48338. this.attachedToParent = false;
  48339. this.parentEl = null;
  48340. parentEl.emit('child-detached', {el: this});
  48341. }
  48342. },
  48343. load: {
  48344. value: function () {
  48345. var self = this;
  48346. if (this.hasLoaded || !this.parentEl) { return; }
  48347. ANode.prototype.load.call(this, function entityLoadCallback () {
  48348. // Check if entity was detached while it was waiting to load.
  48349. if (!self.parentEl) { return; }
  48350. self.updateComponents();
  48351. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  48352. });
  48353. },
  48354. writable: window.debug
  48355. },
  48356. /**
  48357. * Remove child entity.
  48358. *
  48359. * @param {Element} el - Child entity.
  48360. */
  48361. remove: {
  48362. value: function (el) {
  48363. this.object3D.remove(el.object3D);
  48364. }
  48365. },
  48366. /**
  48367. * @returns {array} Direct children that are entities.
  48368. */
  48369. getChildEntities: {
  48370. value: function () {
  48371. var children = this.children;
  48372. var childEntities = [];
  48373. for (var i = 0; i < children.length; i++) {
  48374. var child = children[i];
  48375. if (child instanceof AEntity) {
  48376. childEntities.push(child);
  48377. }
  48378. }
  48379. return childEntities;
  48380. }
  48381. },
  48382. /**
  48383. * Initialize component.
  48384. *
  48385. * @param {string} attrName - Attribute name asociated to the component.
  48386. * @param {object} data - Component data
  48387. * @param {boolean} isDependency - True if the component is a dependency.
  48388. */
  48389. initComponent: {
  48390. value: function (attrName, data, isDependency) {
  48391. var component;
  48392. var componentId;
  48393. var componentInfo;
  48394. var componentName;
  48395. var isComponentDefined;
  48396. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  48397. componentName = componentInfo[0];
  48398. componentId = componentInfo.length > 2
  48399. ? componentInfo.slice(1).join('__')
  48400. : componentInfo[1];
  48401. // Not a registered component.
  48402. if (!COMPONENTS[componentName]) { return; }
  48403. // Component is not a dependency and is undefined.
  48404. // If a component is a dependency, then it is okay to have no data.
  48405. isComponentDefined = checkComponentDefined(this, attrName) ||
  48406. data !== undefined;
  48407. if (!isComponentDefined && !isDependency) { return; }
  48408. // Component already initialized.
  48409. if (attrName in this.components) { return; }
  48410. // Initialize dependencies first
  48411. this.initComponentDependencies(componentName);
  48412. // If component name has an id we check component type multiplic
  48413. if (componentId && !COMPONENTS[componentName].multiple) {
  48414. throw new Error('Trying to initialize multiple ' +
  48415. 'components of type `' + componentName +
  48416. '`. There can only be one component of this type per entity.');
  48417. }
  48418. component = new COMPONENTS[componentName].Component(this, data, componentId);
  48419. if (this.isPlaying) { component.play(); }
  48420. // Components are reflected in the DOM as attributes but the state is not shown
  48421. // hence we set the attribute to empty string.
  48422. // The flag justInitialized is for attributeChangedCallback to not overwrite
  48423. // the component with the empty string.
  48424. if (!this.hasAttribute(attrName)) {
  48425. component.justInitialized = true;
  48426. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  48427. }
  48428. debug('Component initialized: %s', attrName);
  48429. },
  48430. writable: window.debug
  48431. },
  48432. /**
  48433. * Initialize dependencies of a component.
  48434. *
  48435. * @param {string} name - Root component name.
  48436. */
  48437. initComponentDependencies: {
  48438. value: function (name) {
  48439. var self = this;
  48440. var component = COMPONENTS[name];
  48441. var dependencies;
  48442. var i;
  48443. // Not a component.
  48444. if (!component) { return; }
  48445. // No dependencies.
  48446. dependencies = COMPONENTS[name].dependencies;
  48447. if (!dependencies) { return; }
  48448. // Initialize dependencies.
  48449. for (i = 0; i < dependencies.length; i++) {
  48450. // Call getAttribute to initialize the data from the DOM.
  48451. self.initComponent(
  48452. dependencies[i],
  48453. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  48454. true
  48455. );
  48456. }
  48457. }
  48458. },
  48459. removeComponent: {
  48460. value: function (name) {
  48461. var component;
  48462. component = this.components[name];
  48463. if (!component) { return; }
  48464. // Wait for component to initialize.
  48465. if (!component.initialized) {
  48466. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  48467. if (evt.detail.name !== name) { return; }
  48468. this.removeComponent(name);
  48469. this.removeEventListener('componentinitialized', tryRemoveLater);
  48470. });
  48471. return;
  48472. }
  48473. component.pause();
  48474. component.remove();
  48475. delete this.components[name];
  48476. this.emit('componentremoved', component.evtDetail);
  48477. },
  48478. writable: window.debug
  48479. },
  48480. /**
  48481. * Initialize or update all components.
  48482. * Build data using initial components, defined attributes, mixins, and defaults.
  48483. * Update default components before the rest.
  48484. *
  48485. * @member {function} getExtraComponents - Can be implemented to include component data
  48486. * from other sources (e.g., implemented by primitives).
  48487. */
  48488. updateComponents: {
  48489. value: function () {
  48490. var data;
  48491. var extraComponents;
  48492. var i;
  48493. var name;
  48494. var componentsToUpdate = this.componentsToUpdate;
  48495. if (!this.hasLoaded) { return; }
  48496. // Gather mixin-defined components.
  48497. for (i = 0; i < this.mixinEls.length; i++) {
  48498. for (name in this.mixinEls[i].componentCache) {
  48499. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48500. }
  48501. }
  48502. // Gather from extra initial component data if defined (e.g., primitives).
  48503. if (this.getExtraComponents) {
  48504. extraComponents = this.getExtraComponents();
  48505. for (name in extraComponents) {
  48506. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48507. }
  48508. }
  48509. // Gather entity-defined components.
  48510. for (i = 0; i < this.attributes.length; ++i) {
  48511. name = this.attributes[i].name;
  48512. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  48513. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48514. }
  48515. // object3D components first (position, rotation, scale, visible).
  48516. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  48517. name = OBJECT3D_COMPONENTS[i];
  48518. if (!this.hasAttribute(name)) { continue; }
  48519. this.updateComponent(name, this.getDOMAttribute(name));
  48520. }
  48521. // Initialize or update rest of components.
  48522. for (name in componentsToUpdate) {
  48523. data = mergeComponentData(this.getDOMAttribute(name),
  48524. extraComponents && extraComponents[name]);
  48525. this.updateComponent(name, data);
  48526. delete componentsToUpdate[name];
  48527. }
  48528. },
  48529. writable: window.debug
  48530. },
  48531. /**
  48532. * Initialize, update, or remove a single component.
  48533. *
  48534. * When initializing, we set the component on `this.components`.
  48535. *
  48536. * @param {string} attr - Component name.
  48537. * @param {object} attrValue - Value of the DOM attribute.
  48538. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  48539. */
  48540. updateComponent: {
  48541. value: function (attr, attrValue, clobber) {
  48542. var component = this.components[attr];
  48543. if (component) {
  48544. // Remove component.
  48545. if (attrValue === null && !checkComponentDefined(this, attr)) {
  48546. this.removeComponent(attr);
  48547. return;
  48548. }
  48549. // Component already initialized. Update component.
  48550. component.updateProperties(attrValue, clobber);
  48551. return;
  48552. }
  48553. // Component not yet initialized. Initialize component.
  48554. this.initComponent(attr, attrValue, false);
  48555. }
  48556. },
  48557. /**
  48558. * If `attr` is a component name, detach the component from the entity.
  48559. *
  48560. * If `propertyName` is given, reset the component property value to its default.
  48561. *
  48562. * @param {string} attr - Attribute name, which could also be a component name.
  48563. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  48564. */
  48565. removeAttribute: {
  48566. value: function (attr, propertyName) {
  48567. var component = this.components[attr];
  48568. // Remove component.
  48569. if (component && propertyName === undefined) {
  48570. this.removeComponent(attr);
  48571. }
  48572. // Reset component property value.
  48573. if (component && propertyName !== undefined) {
  48574. component.resetProperty(propertyName);
  48575. return;
  48576. }
  48577. // Remove mixins.
  48578. if (attr === 'mixin') {
  48579. this.mixinUpdate('');
  48580. }
  48581. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  48582. }
  48583. },
  48584. /**
  48585. * Start dynamic behavior associated with entity such as dynamic components and animations.
  48586. * Tell all children entities to also play.
  48587. */
  48588. play: {
  48589. value: function () {
  48590. var entities;
  48591. var i;
  48592. var key;
  48593. // Already playing.
  48594. if (this.isPlaying || !this.hasLoaded) { return; }
  48595. this.isPlaying = true;
  48596. // Wake up all components.
  48597. for (key in this.components) { this.components[key].play(); }
  48598. // Tell all child entities to play.
  48599. entities = this.getChildEntities();
  48600. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  48601. this.emit('play');
  48602. },
  48603. writable: true
  48604. },
  48605. /**
  48606. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  48607. * Tell all children entities to also pause.
  48608. */
  48609. pause: {
  48610. value: function () {
  48611. var entities;
  48612. var i;
  48613. var key;
  48614. if (!this.isPlaying) { return; }
  48615. this.isPlaying = false;
  48616. // Sleep all components.
  48617. for (key in this.components) { this.components[key].pause(); }
  48618. // Tell all child entities to pause.
  48619. entities = this.getChildEntities();
  48620. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  48621. this.emit('pause');
  48622. },
  48623. writable: true
  48624. },
  48625. /**
  48626. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  48627. *
  48628. * @param {string} attr
  48629. * @param {string} oldVal
  48630. * @param {string|object} newVal
  48631. */
  48632. setEntityAttribute: {
  48633. value: function (attr, oldVal, newVal) {
  48634. if (COMPONENTS[attr] || this.components[attr]) {
  48635. this.updateComponent(attr, newVal);
  48636. return;
  48637. }
  48638. if (attr === 'mixin') {
  48639. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  48640. if (newVal === this.computedMixinStr) { return; }
  48641. this.mixinUpdate(newVal, oldVal);
  48642. }
  48643. }
  48644. },
  48645. mixinUpdate: {
  48646. value: function (newMixins, oldMixins) {
  48647. oldMixins = oldMixins || this.getAttribute('mixin');
  48648. this.updateMixins(newMixins, oldMixins);
  48649. this.updateComponents();
  48650. }
  48651. },
  48652. /**
  48653. * setAttribute can:
  48654. *
  48655. * 1. Set a single property of a multi-property component.
  48656. * 2. Set multiple properties of a multi-property component.
  48657. * 3. Replace properties of a multi-property component.
  48658. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  48659. *
  48660. * @param {string} attrName - Component or attribute name.
  48661. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  48662. * object of properties.
  48663. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  48664. * it is a boolean indicating whether to clobber previous values (defaults to false).
  48665. */
  48666. setAttribute: {
  48667. value: function (attrName, arg1, arg2) {
  48668. var newAttrValue;
  48669. var clobber;
  48670. var componentName;
  48671. var delimiterIndex;
  48672. var isDebugMode;
  48673. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  48674. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  48675. // Not a component. Normal set attribute.
  48676. if (!COMPONENTS[componentName]) {
  48677. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  48678. ANode.prototype.setAttribute.call(this, attrName, arg1);
  48679. return;
  48680. }
  48681. // Initialize component first if not yet initialized.
  48682. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  48683. this.updateComponent(attrName,
  48684. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  48685. }
  48686. // Determine new attributes from the arguments
  48687. if (typeof arg2 !== 'undefined' &&
  48688. typeof arg1 === 'string' &&
  48689. arg1.length > 0 &&
  48690. typeof utils.styleParser.parse(arg1) === 'string') {
  48691. // Update a single property of a multi-property component
  48692. newAttrValue = {};
  48693. newAttrValue[arg1] = arg2;
  48694. clobber = false;
  48695. } else {
  48696. // Update with a value, object, or CSS-style property string, with the possiblity
  48697. // of clobbering previous values.
  48698. newAttrValue = arg1;
  48699. clobber = (arg2 === true);
  48700. }
  48701. // Update component
  48702. this.updateComponent(attrName, newAttrValue, clobber);
  48703. // In debug mode, write component data up to the DOM.
  48704. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  48705. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  48706. },
  48707. writable: window.debug
  48708. },
  48709. /**
  48710. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  48711. *
  48712. * @param {bool} recursive - Also flushToDOM on the children.
  48713. **/
  48714. flushToDOM: {
  48715. value: function (recursive) {
  48716. var components = this.components;
  48717. var child;
  48718. var children = this.children;
  48719. var i;
  48720. var key;
  48721. // Flush entity's components to DOM.
  48722. for (key in components) {
  48723. components[key].flushToDOM();
  48724. }
  48725. // Recurse.
  48726. if (!recursive) { return; }
  48727. for (i = 0; i < children.length; ++i) {
  48728. child = children[i];
  48729. if (!child.flushToDOM) { continue; }
  48730. child.flushToDOM(recursive);
  48731. }
  48732. }
  48733. },
  48734. /**
  48735. * If `attr` is a component, returns ALL component data including applied mixins and
  48736. * defaults.
  48737. *
  48738. * If `attr` is not a component, fall back to HTML getAttribute.
  48739. *
  48740. * @param {string} attr
  48741. * @returns {object|string} Object if component, else string.
  48742. */
  48743. getAttribute: {
  48744. value: function (attr) {
  48745. // If component, return component data.
  48746. var component;
  48747. if (attr === 'position') { return this.object3D.position; }
  48748. if (attr === 'rotation') { return getRotation(this); }
  48749. if (attr === 'scale') { return this.object3D.scale; }
  48750. if (attr === 'visible') { return this.object3D.visible; }
  48751. component = this.components[attr];
  48752. if (component) { return component.data; }
  48753. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  48754. },
  48755. writable: window.debug
  48756. },
  48757. /**
  48758. * If `attr` is a component, returns JUST the component data defined on the entity.
  48759. * Like a partial version of `getComputedAttribute` as returned component data
  48760. * does not include applied mixins or defaults.
  48761. *
  48762. * If `attr` is not a component, fall back to HTML getAttribute.
  48763. *
  48764. * @param {string} attr
  48765. * @returns {object|string} Object if component, else string.
  48766. */
  48767. getDOMAttribute: {
  48768. value: function (attr) {
  48769. // If cached value exists, return partial component data.
  48770. var component = this.components[attr];
  48771. if (component) { return component.attrValue; }
  48772. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  48773. },
  48774. writable: window.debug
  48775. },
  48776. addState: {
  48777. value: function (state) {
  48778. if (this.is(state)) { return; }
  48779. this.states.push(state);
  48780. this.emit('stateadded', state);
  48781. }
  48782. },
  48783. removeState: {
  48784. value: function (state) {
  48785. var stateIndex = this.states.indexOf(state);
  48786. if (stateIndex === -1) { return; }
  48787. this.states.splice(stateIndex, 1);
  48788. this.emit('stateremoved', state);
  48789. }
  48790. },
  48791. /**
  48792. * Checks if the element is in a given state. e.g. el.is('alive');
  48793. * @type {string} state - Name of the state we want to check
  48794. */
  48795. is: {
  48796. value: function (state) {
  48797. return this.states.indexOf(state) !== -1;
  48798. }
  48799. }
  48800. });
  48801. /**
  48802. * Check if a component is *defined* for an entity, including defaults and mixins.
  48803. * Does not check whether the component has been *initialized* for an entity.
  48804. *
  48805. * @param {string} el - Entity.
  48806. * @param {string} name - Component name.
  48807. * @returns {boolean}
  48808. */
  48809. function checkComponentDefined (el, name) {
  48810. // Check if element contains the component.
  48811. if (el.components[name] && el.components[name].attrValue) { return true; }
  48812. return isComponentMixedIn(name, el.mixinEls);
  48813. }
  48814. /**
  48815. * Check if any mixins contains a component.
  48816. *
  48817. * @param {string} name - Component name.
  48818. * @param {array} mixinEls - Array of <a-mixin>s.
  48819. */
  48820. function isComponentMixedIn (name, mixinEls) {
  48821. var i;
  48822. var inMixin = false;
  48823. for (i = 0; i < mixinEls.length; ++i) {
  48824. inMixin = mixinEls[i].hasAttribute(name);
  48825. if (inMixin) { break; }
  48826. }
  48827. return inMixin;
  48828. }
  48829. /**
  48830. * Given entity defined value, merge in extra data if necessary.
  48831. * Handle both single and multi-property components.
  48832. *
  48833. * @param {string} attrValue - Entity data.
  48834. * @param extraData - Entity data from another source to merge in.
  48835. */
  48836. function mergeComponentData (attrValue, extraData) {
  48837. // Extra data not defined, just return attrValue.
  48838. if (!extraData) { return attrValue; }
  48839. // Merge multi-property data.
  48840. if (extraData.constructor === Object) {
  48841. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  48842. }
  48843. // Return data, precendence to the defined value.
  48844. return attrValue || extraData;
  48845. }
  48846. function isComponent (componentName) {
  48847. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  48848. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  48849. }
  48850. if (!COMPONENTS[componentName]) { return false; }
  48851. return true;
  48852. }
  48853. function getRotation (entityEl) {
  48854. var radToDeg = THREE.Math.radToDeg;
  48855. var rotation = entityEl.object3D.rotation;
  48856. var rotationObj = entityEl.rotationObj;
  48857. rotationObj.x = radToDeg(rotation.x);
  48858. rotationObj.y = radToDeg(rotation.y);
  48859. rotationObj.z = radToDeg(rotation.z);
  48860. return rotationObj;
  48861. }
  48862. AEntity = registerElement('a-entity', {prototype: proto});
  48863. module.exports = AEntity;
  48864. },{"../lib/three":150,"../utils/":172,"./a-node":100,"./a-register-element":101,"./component":102}],99:[function(_dereq_,module,exports){
  48865. var ANode = _dereq_('./a-node');
  48866. var registerElement = _dereq_('./a-register-element').registerElement;
  48867. var components = _dereq_('./component').components;
  48868. var utils = _dereq_('../utils');
  48869. var MULTIPLE_COMPONENT_DELIMITER = '__';
  48870. /**
  48871. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  48872. * are component names and the values are already parsed by the component.
  48873. */
  48874. module.exports = registerElement('a-mixin', {
  48875. prototype: Object.create(ANode.prototype, {
  48876. createdCallback: {
  48877. value: function () {
  48878. this.componentCache = {};
  48879. this.id = this.getAttribute('id');
  48880. this.isMixin = true;
  48881. }
  48882. },
  48883. attributeChangedCallback: {
  48884. value: function (attr, oldVal, newVal) {
  48885. this.cacheAttribute(attr, newVal);
  48886. }
  48887. },
  48888. attachedCallback: {
  48889. value: function () {
  48890. this.sceneEl = this.closestScene();
  48891. this.cacheAttributes();
  48892. this.updateEntities();
  48893. this.load();
  48894. }
  48895. },
  48896. /**
  48897. * setAttribute that parses and caches component values.
  48898. */
  48899. setAttribute: {
  48900. value: function (attr, value) {
  48901. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  48902. this.cacheAttribute(attr, value);
  48903. }
  48904. },
  48905. /**
  48906. * If `attr` is a component, then parse the value using the schema and store it.
  48907. */
  48908. cacheAttribute: {
  48909. value: function (attr, value) {
  48910. var component;
  48911. var componentName;
  48912. // Get component data.
  48913. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  48914. component = components[componentName];
  48915. if (!component) { return; }
  48916. if (value === undefined) {
  48917. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  48918. }
  48919. this.componentCache[attr] = component.parseAttrValueForCache(value);
  48920. }
  48921. },
  48922. /**
  48923. * If `attr` is a component, then grab pre-parsed value from the cache.
  48924. * Else do a normal getAttribute.
  48925. */
  48926. getAttribute: {
  48927. value: function (attr) {
  48928. return this.componentCache[attr] ||
  48929. window.HTMLElement.prototype.getAttribute.call(this, attr);
  48930. }
  48931. },
  48932. /**
  48933. * Parse and cache every component defined on the mixin.
  48934. */
  48935. cacheAttributes: {
  48936. value: function () {
  48937. var attributes = this.attributes;
  48938. var attrName;
  48939. var i;
  48940. for (i = 0; i < attributes.length; i++) {
  48941. attrName = attributes[i].name;
  48942. this.cacheAttribute(attrName);
  48943. }
  48944. }
  48945. },
  48946. /**
  48947. * For entities that already have been loaded by the time the mixin was attached, tell
  48948. * those entities to register the mixin and refresh their component data.
  48949. */
  48950. updateEntities: {
  48951. value: function () {
  48952. var entity;
  48953. var entities;
  48954. var i;
  48955. if (!this.sceneEl) { return; }
  48956. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  48957. for (i = 0; i < entities.length; i++) {
  48958. entity = entities[i];
  48959. if (!entity.hasLoaded || entity.isMixin) { continue; }
  48960. entity.mixinUpdate(this.id);
  48961. }
  48962. }
  48963. }
  48964. })
  48965. });
  48966. },{"../utils":172,"./a-node":100,"./a-register-element":101,"./component":102}],100:[function(_dereq_,module,exports){
  48967. /* global CustomEvent, MutationObserver */
  48968. var registerElement = _dereq_('./a-register-element').registerElement;
  48969. var isNode = _dereq_('./a-register-element').isNode;
  48970. var utils = _dereq_('../utils/');
  48971. var warn = utils.debug('core:a-node:warn');
  48972. var error = utils.debug('core:a-node:error');
  48973. var MIXIN_OBSERVER_CONFIG = {attributes: true};
  48974. /**
  48975. * Base class for A-Frame that manages loading of objects.
  48976. *
  48977. * Nodes can be modified using mixins.
  48978. * Nodes emit a `loaded` event when they and their children have initialized.
  48979. */
  48980. module.exports = registerElement('a-node', {
  48981. prototype: Object.create(window.HTMLElement.prototype, {
  48982. createdCallback: {
  48983. value: function () {
  48984. this.computedMixinStr = '';
  48985. this.hasLoaded = false;
  48986. this.isNode = true;
  48987. this.mixinEls = [];
  48988. this.mixinObservers = {};
  48989. },
  48990. writable: window.debug
  48991. },
  48992. attachedCallback: {
  48993. value: function () {
  48994. var mixins;
  48995. this.sceneEl = this.closestScene();
  48996. if (!this.sceneEl) {
  48997. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  48998. 'scene. Append this element to `<a-scene>` instead.');
  48999. }
  49000. this.hasLoaded = false;
  49001. this.emit('nodeready', undefined, false);
  49002. if (!this.isMixin) {
  49003. mixins = this.getAttribute('mixin');
  49004. if (mixins) { this.updateMixins(mixins); }
  49005. }
  49006. },
  49007. writable: window.debug
  49008. },
  49009. /**
  49010. * Handle mixin.
  49011. */
  49012. attributeChangedCallback: {
  49013. value: function (attr, oldVal, newVal) {
  49014. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  49015. if (newVal === this.computedMixinStr) { return; }
  49016. if (attr === 'mixin' && !this.isMixin) {
  49017. this.updateMixins(newVal, oldVal);
  49018. }
  49019. }
  49020. },
  49021. /**
  49022. * Returns the first scene by traversing up the tree starting from and
  49023. * including receiver element.
  49024. */
  49025. closestScene: {
  49026. value: function closest () {
  49027. var element = this;
  49028. while (element) {
  49029. if (element.isScene) { break; }
  49030. element = element.parentElement;
  49031. }
  49032. return element;
  49033. }
  49034. },
  49035. /**
  49036. * Returns first element matching a selector by traversing up the tree starting
  49037. * from and including receiver element.
  49038. *
  49039. * @param {string} selector - Selector of element to find.
  49040. */
  49041. closest: {
  49042. value: function closest (selector) {
  49043. var matches = this.matches || this.mozMatchesSelector ||
  49044. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  49045. var element = this;
  49046. while (element) {
  49047. if (matches.call(element, selector)) { break; }
  49048. element = element.parentElement;
  49049. }
  49050. return element;
  49051. }
  49052. },
  49053. detachedCallback: {
  49054. value: function () {
  49055. this.hasLoaded = false;
  49056. }
  49057. },
  49058. /**
  49059. * Wait for children to load, if any.
  49060. * Then emit `loaded` event and set `hasLoaded`.
  49061. */
  49062. load: {
  49063. value: function (cb, childFilter) {
  49064. var children;
  49065. var childrenLoaded;
  49066. var self = this;
  49067. if (this.hasLoaded) { return; }
  49068. // Default to waiting for all nodes.
  49069. childFilter = childFilter || isNode;
  49070. // Wait for children to load (if any), then load.
  49071. children = this.getChildren();
  49072. childrenLoaded = children.filter(childFilter).map(function (child) {
  49073. return new Promise(function waitForLoaded (resolve) {
  49074. if (child.hasLoaded) { return resolve(); }
  49075. child.addEventListener('loaded', resolve);
  49076. });
  49077. });
  49078. Promise.all(childrenLoaded).then(function emitLoaded () {
  49079. self.hasLoaded = true;
  49080. if (cb) { cb(); }
  49081. self.emit('loaded', undefined, false);
  49082. }).catch(function (err) {
  49083. error('Failure loading node: ', err);
  49084. });
  49085. },
  49086. writable: true
  49087. },
  49088. getChildren: {
  49089. value: function () {
  49090. return Array.prototype.slice.call(this.children, 0);
  49091. }
  49092. },
  49093. /**
  49094. * Unregister old mixins and listeners.
  49095. * Register new mixins and listeners.
  49096. * Registering means to update `this.mixinEls` with listeners.
  49097. */
  49098. updateMixins: {
  49099. value: (function () {
  49100. var newMixinIdArray = [];
  49101. var oldMixinIdArray = [];
  49102. return function (newMixins, oldMixins) {
  49103. var i;
  49104. var newMixinIds;
  49105. var oldMixinIds;
  49106. newMixinIdArray.length = 0;
  49107. oldMixinIdArray.length = 0;
  49108. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  49109. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  49110. // Unregister old mixins.
  49111. for (i = 0; i < oldMixinIds.length; i++) {
  49112. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  49113. this.unregisterMixin(oldMixinIds[i]);
  49114. }
  49115. }
  49116. // Register new mixins.
  49117. this.computedMixinStr = '';
  49118. this.mixinEls.length = 0;
  49119. for (i = 0; i < newMixinIds.length; i++) {
  49120. this.registerMixin(document.getElementById(newMixinIds[i]));
  49121. }
  49122. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  49123. // update.
  49124. if (this.computedMixinStr) {
  49125. this.computedMixinStr = this.computedMixinStr.trim();
  49126. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  49127. this.computedMixinStr);
  49128. }
  49129. };
  49130. })()
  49131. },
  49132. /**
  49133. * From mixin ID, add mixin element to `mixinEls`.
  49134. *
  49135. * @param {Element} mixinEl
  49136. */
  49137. registerMixin: {
  49138. value: function (mixinEl) {
  49139. var compositedMixinIds;
  49140. var i;
  49141. var mixin;
  49142. if (!mixinEl) { return; }
  49143. // Register composited mixins (if mixin has mixins).
  49144. mixin = mixinEl.getAttribute('mixin');
  49145. if (mixin) {
  49146. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  49147. for (i = 0; i < compositedMixinIds.length; i++) {
  49148. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  49149. }
  49150. }
  49151. // Register mixin.
  49152. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  49153. this.mixinEls.push(mixinEl);
  49154. this.attachMixinListener(mixinEl);
  49155. }
  49156. },
  49157. setAttribute: {
  49158. value: function (attr, newValue) {
  49159. if (attr === 'mixin') { this.updateMixins(newValue); }
  49160. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  49161. }
  49162. },
  49163. unregisterMixin: {
  49164. value: function (mixinId) {
  49165. var i;
  49166. var mixinEls = this.mixinEls;
  49167. var mixinEl;
  49168. for (i = 0; i < mixinEls.length; ++i) {
  49169. mixinEl = mixinEls[i];
  49170. if (mixinId === mixinEl.id) {
  49171. mixinEls.splice(i, 1);
  49172. break;
  49173. }
  49174. }
  49175. this.removeMixinListener(mixinId);
  49176. }
  49177. },
  49178. removeMixinListener: {
  49179. value: function (mixinId) {
  49180. var observer = this.mixinObservers[mixinId];
  49181. if (!observer) { return; }
  49182. observer.disconnect();
  49183. this.mixinObservers[mixinId] = null;
  49184. }
  49185. },
  49186. /**
  49187. * Add mutation observer from entity to mixin.
  49188. */
  49189. attachMixinListener: {
  49190. value: function (mixinEl) {
  49191. var currentObserver;
  49192. var mixinId;
  49193. var observer;
  49194. var self = this;
  49195. if (!mixinEl) { return; }
  49196. mixinId = mixinEl.id;
  49197. currentObserver = this.mixinObservers[mixinId];
  49198. if (currentObserver) { return; }
  49199. // Add observer.
  49200. observer = new MutationObserver(function (mutations) {
  49201. self.handleMixinUpdate(mutations[0].attributeName);
  49202. });
  49203. observer.observe(mixinEl, MIXIN_OBSERVER_CONFIG);
  49204. this.mixinObservers[mixinId] = observer;
  49205. }
  49206. },
  49207. handleMixinUpdate: {
  49208. value: function () { /* no-op */ }
  49209. },
  49210. /**
  49211. * Emit a DOM event.
  49212. *
  49213. * @param {string} name - Name of event.
  49214. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  49215. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  49216. * @param {object} [extraData] - Extra data to pass to the event, if any.
  49217. */
  49218. emit: {
  49219. value: (function () {
  49220. var data = {};
  49221. return function (name, detail, bubbles, extraData) {
  49222. if (bubbles === undefined) { bubbles = true; }
  49223. data.bubbles = !!bubbles;
  49224. data.detail = detail;
  49225. // If extra data is present, we need to create a new object.
  49226. if (extraData) { data = utils.extend({}, extraData, data); }
  49227. this.dispatchEvent(new CustomEvent(name, data));
  49228. };
  49229. })(),
  49230. writable: window.debug
  49231. }
  49232. })
  49233. });
  49234. },{"../utils/":172,"./a-register-element":101}],101:[function(_dereq_,module,exports){
  49235. /*
  49236. ------------------------------------------------------------
  49237. ------------- WARNING WARNING WARNING WARNING --------------
  49238. ------------------------------------------------------------
  49239. This module wraps registerElement to deal with components that inherit from
  49240. `ANode` and `AEntity`. It's a pass through in any other case.
  49241. It wraps some of the prototype methods of the created element to make sure
  49242. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  49243. are also invoked. The method in the base prototype is always called before the one
  49244. in the derived prototype.
  49245. */
  49246. // Polyfill `document.registerElement`.
  49247. _dereq_('document-register-element');
  49248. var ANode; // Must declare before AEntity. Initialized at the bottom.
  49249. var AEntity;
  49250. var knownTags = module.exports.knownTags = {};
  49251. function addTagName (tagName) {
  49252. knownTags[tagName.toLowerCase()] = true;
  49253. }
  49254. /**
  49255. * Return whether the element type is one of our known registered ones.
  49256. *
  49257. * @param {string} node - The name of the tag to register.
  49258. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  49259. */
  49260. module.exports.isNode = function (node) {
  49261. return node.tagName.toLowerCase() in knownTags || node.isNode;
  49262. };
  49263. /**
  49264. * @param {string} tagName - The name of the tag to register.
  49265. * @param {object} obj - The prototype of the new element.
  49266. * @returns {object} The prototype of the new element.
  49267. */
  49268. module.exports.registerElement = function (tagName, obj) {
  49269. var proto = Object.getPrototypeOf(obj.prototype);
  49270. var newObj = obj;
  49271. var isANode = ANode && proto === ANode.prototype;
  49272. var isAEntity = AEntity && proto === AEntity.prototype;
  49273. if (isANode || isAEntity) { addTagName(tagName); }
  49274. // Wrap if element inherits from `ANode`.
  49275. if (isANode) {
  49276. newObj = wrapANodeMethods(obj.prototype);
  49277. newObj = {prototype: Object.create(proto, newObj)};
  49278. }
  49279. // Wrap if element inherits from `AEntity`.
  49280. if (isAEntity) {
  49281. newObj = wrapAEntityMethods(obj.prototype);
  49282. newObj = {prototype: Object.create(proto, newObj)};
  49283. }
  49284. // Give all functions their proper name.
  49285. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  49286. var propVal = newObj.prototype[propName];
  49287. if (typeof propVal === 'function') {
  49288. propVal.displayName = propName;
  49289. }
  49290. });
  49291. return document.registerElement(tagName, newObj);
  49292. };
  49293. /**
  49294. * Wrap some obj methods to call those on `ANode` base prototype.
  49295. *
  49296. * @param {object} obj - Object that contains the methods that will be wrapped.
  49297. * @return {object} An object with the same properties as the input parameter but
  49298. * with some of methods wrapped.
  49299. */
  49300. function wrapANodeMethods (obj) {
  49301. var newObj = {};
  49302. var ANodeMethods = [
  49303. 'attachedCallback',
  49304. 'attributeChangedCallback',
  49305. 'createdCallback',
  49306. 'detachedCallback'
  49307. ];
  49308. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49309. copyProperties(obj, newObj);
  49310. return newObj;
  49311. }
  49312. /**
  49313. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  49314. *
  49315. * @param {object} obj - The objects that contains the methods that will be wrapped.
  49316. * @return {object} - An object with the same properties as the input parameter but
  49317. * with some of methods wrapped.
  49318. */
  49319. function wrapAEntityMethods (obj) {
  49320. var newObj = {};
  49321. var ANodeMethods = [
  49322. 'attachedCallback',
  49323. 'attributeChangedCallback',
  49324. 'createdCallback',
  49325. 'detachedCallback'
  49326. ];
  49327. var AEntityMethods = [
  49328. 'attachedCallback',
  49329. 'attributeChangedCallback',
  49330. 'createdCallback',
  49331. 'detachedCallback'
  49332. ];
  49333. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49334. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  49335. // Copies the remaining properties into the new object.
  49336. copyProperties(obj, newObj);
  49337. return newObj;
  49338. }
  49339. /**
  49340. * Wrap a list a methods to ensure that those in the base prototype are called
  49341. * before the derived one.
  49342. *
  49343. * @param {object} targetObj - Object that will contain the wrapped methods.
  49344. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  49345. * @param {object} derivedObject - Object that inherits from the baseObj.
  49346. * @param {object} baseObj - Object that derivedObj inherits from.
  49347. */
  49348. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  49349. methodList.forEach(function (methodName) {
  49350. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  49351. });
  49352. }
  49353. module.exports.wrapMethods = wrapMethods;
  49354. /**
  49355. * Wrap one method to ensure that the one in the base prototype is called before
  49356. * the one in the derived one.
  49357. *
  49358. * @param {object} obj - Object that will contain the wrapped method.
  49359. * @param {string} methodName - The name of the method that will be wrapped.
  49360. * @param {object} derivedObject - Object that inherits from the baseObj.
  49361. * @param {object} baseObj - Object that derivedObj inherits from.
  49362. */
  49363. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  49364. var derivedMethod = derivedObj[methodName];
  49365. var baseMethod = baseObj[methodName];
  49366. // Derived prototype does not define method, no need to wrap.
  49367. if (!derivedMethod || !baseMethod) { return; }
  49368. // Derived prototype doesn't override the one in the base one, no need to wrap.
  49369. if (derivedMethod === baseMethod) { return; }
  49370. // Wrap to ensure the base method is called before the one in the derived prototype.
  49371. obj[methodName] = {
  49372. value: function wrappedMethod () {
  49373. baseMethod.apply(this, arguments);
  49374. return derivedMethod.apply(this, arguments);
  49375. },
  49376. writable: window.debug
  49377. };
  49378. }
  49379. /**
  49380. * It copies the properties from source to destination object if they don't
  49381. * exist already.
  49382. *
  49383. * @param {object} source - The object where properties are copied from.
  49384. * @param {type} destination - The object where properties are copied to.
  49385. */
  49386. function copyProperties (source, destination) {
  49387. var props = Object.getOwnPropertyNames(source);
  49388. props.forEach(function (prop) {
  49389. var desc;
  49390. if (!destination[prop]) {
  49391. desc = Object.getOwnPropertyDescriptor(source, prop);
  49392. destination[prop] = {value: source[prop], writable: desc.writable};
  49393. }
  49394. });
  49395. }
  49396. ANode = _dereq_('./a-node');
  49397. AEntity = _dereq_('./a-entity');
  49398. },{"./a-entity":98,"./a-node":100,"document-register-element":11}],102:[function(_dereq_,module,exports){
  49399. /* global Node */
  49400. var schema = _dereq_('./schema');
  49401. var scenes = _dereq_('./scene/scenes');
  49402. var systems = _dereq_('./system');
  49403. var utils = _dereq_('../utils/');
  49404. var components = module.exports.components = {}; // Keep track of registered components.
  49405. var parseProperties = schema.parseProperties;
  49406. var parseProperty = schema.parseProperty;
  49407. var processSchema = schema.process;
  49408. var isSingleProp = schema.isSingleProperty;
  49409. var stringifyProperties = schema.stringifyProperties;
  49410. var stringifyProperty = schema.stringifyProperty;
  49411. var styleParser = utils.styleParser;
  49412. var warn = utils.debug('core:component:warn');
  49413. var aframeScript = document.currentScript;
  49414. var upperCaseRegExp = new RegExp('[A-Z]+');
  49415. /**
  49416. * Component class definition.
  49417. *
  49418. * Components configure appearance, modify behavior, or add functionality to
  49419. * entities. The behavior and appearance of an entity can be changed at runtime
  49420. * by adding, removing, or updating components. Entities do not share instances
  49421. * of components.
  49422. *
  49423. * @member {object} el - Reference to the entity element.
  49424. * @member {string} attrValue - Value of the corresponding HTML attribute.
  49425. * @member {object} data - Component data populated by parsing the
  49426. * mapped attribute of the component plus applying defaults and mixins.
  49427. */
  49428. var Component = module.exports.Component = function (el, attrValue, id) {
  49429. var self = this;
  49430. this.el = el;
  49431. this.id = id;
  49432. this.attrName = this.name + (id ? '__' + id : '');
  49433. this.evtDetail = {id: this.id, name: this.name};
  49434. this.initialized = false;
  49435. this.el.components[this.attrName] = this;
  49436. // Store component data from previous update call.
  49437. this.oldData = undefined;
  49438. // Last value passed to updateProperties.
  49439. this.previousAttrValue = undefined;
  49440. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  49441. el.emit('componentchanged', self.evtDetail, false);
  49442. }, 200);
  49443. this.updateProperties(attrValue);
  49444. };
  49445. Component.prototype = {
  49446. /**
  49447. * Contains the type schema and defaults for the data values.
  49448. * Data is coerced into the types of the values of the defaults.
  49449. */
  49450. schema: {},
  49451. /**
  49452. * Init handler. Similar to attachedCallback.
  49453. * Called during component initialization and is only run once.
  49454. * Components can use this to set initial state.
  49455. */
  49456. init: function () { /* no-op */ },
  49457. /**
  49458. * Update handler. Similar to attributeChangedCallback.
  49459. * Called whenever component's data changes.
  49460. * Also called on component initialization when the component receives initial data.
  49461. *
  49462. * @param {object} prevData - Previous attributes of the component.
  49463. */
  49464. update: function (prevData) { /* no-op */ },
  49465. updateSchema: undefined,
  49466. /**
  49467. * Tick handler.
  49468. * Called on each tick of the scene render loop.
  49469. * Affected by play and pause.
  49470. *
  49471. * @param {number} time - Scene tick time.
  49472. * @param {number} timeDelta - Difference in current render time and previous render time.
  49473. */
  49474. tick: undefined,
  49475. /**
  49476. * Tock handler.
  49477. * Called on each tock of the scene render loop.
  49478. * Affected by play and pause.
  49479. *
  49480. * @param {number} time - Scene tick time.
  49481. * @param {number} timeDelta - Difference in current render time and previous render time.
  49482. * @param {object} camera - Camera used to render the last frame.
  49483. */
  49484. tock: undefined,
  49485. /**
  49486. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  49487. */
  49488. play: function () { /* no-op */ },
  49489. /**
  49490. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  49491. */
  49492. pause: function () { /* no-op */ },
  49493. /**
  49494. * Remove handler. Similar to detachedCallback.
  49495. * Called whenever component is removed from the entity (i.e., removeAttribute).
  49496. * Components can use this to reset behavior on the entity.
  49497. */
  49498. remove: function () { /* no-op */ },
  49499. /**
  49500. * Parses each property based on property type.
  49501. * If component is single-property, then parses the single property value.
  49502. *
  49503. * @param {string} value - HTML attribute value.
  49504. * @param {boolean} silent - Suppress warning messages.
  49505. * @returns {object} Component data.
  49506. */
  49507. parse: function (value, silent) {
  49508. var schema = this.schema;
  49509. if (isSingleProp(schema)) { return parseProperty(value, schema); }
  49510. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  49511. },
  49512. /**
  49513. * Stringify properties if necessary.
  49514. *
  49515. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  49516. * value (e.g., selector, vec3 property types).
  49517. *
  49518. * @param {object} data - Complete component data.
  49519. * @returns {string}
  49520. */
  49521. stringify: function (data) {
  49522. var schema = this.schema;
  49523. if (typeof data === 'string') { return data; }
  49524. if (isSingleProp(schema)) { return stringifyProperty(data, schema); }
  49525. data = stringifyProperties(data, schema);
  49526. return styleParser.stringify(data);
  49527. },
  49528. /**
  49529. * Update the cache of the pre-parsed attribute value.
  49530. *
  49531. * @param {string} value - New data.
  49532. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  49533. */
  49534. updateCachedAttrValue: function (value, clobber) {
  49535. var attrValue = this.parseAttrValueForCache(value);
  49536. var isSinglePropSchema = isSingleProp(this.schema);
  49537. var property;
  49538. if (value === undefined) { return; }
  49539. // Merge new data with previous `attrValue` if updating and not clobbering.
  49540. if (!isSinglePropSchema && !clobber) {
  49541. this.attrValue = this.attrValue ? cloneData(this.attrValue) : {};
  49542. for (property in attrValue) {
  49543. this.attrValue[property] = attrValue[property];
  49544. }
  49545. return;
  49546. }
  49547. // If single-prop schema or clobber.
  49548. this.attrValue = attrValue;
  49549. },
  49550. /**
  49551. * Given an HTML attribute value parses the string
  49552. * based on the component schema. To avoid double parsings of
  49553. * strings into strings we store the original instead
  49554. * of the parsed one
  49555. *
  49556. * @param {string} value - HTML attribute value
  49557. */
  49558. parseAttrValueForCache: function (value) {
  49559. var parsedValue;
  49560. if (typeof value !== 'string') { return value; }
  49561. if (isSingleProp(this.schema)) {
  49562. parsedValue = this.schema.parse(value);
  49563. /**
  49564. * To avoid bogus double parsings. Cached values will be parsed when building
  49565. * component data. For instance when parsing a src id to its url, we want to cache
  49566. * original string and not the parsed one (#monster -> models/monster.dae)
  49567. * so when building data we parse the expected value.
  49568. */
  49569. if (typeof parsedValue === 'string') { parsedValue = value; }
  49570. } else {
  49571. // Parse using the style parser to avoid double parsing of individual properties.
  49572. parsedValue = styleParser.parse(value);
  49573. }
  49574. return parsedValue;
  49575. },
  49576. /**
  49577. * Write cached attribute data to the entity DOM element.
  49578. *
  49579. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  49580. * default components.
  49581. */
  49582. flushToDOM: function (isDefault) {
  49583. var attrValue = isDefault ? this.data : this.attrValue;
  49584. if (!attrValue) { return; }
  49585. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  49586. this.stringify(attrValue));
  49587. },
  49588. /**
  49589. * Apply new component data if data has changed.
  49590. *
  49591. * @param {string} attrValue - HTML attribute value.
  49592. * If undefined, use the cached attribute value and continue updating properties.
  49593. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  49594. */
  49595. updateProperties: function (attrValue, clobber) {
  49596. var el = this.el;
  49597. var isSinglePropSchema;
  49598. var key;
  49599. var skipTypeChecking;
  49600. var oldData = this.oldData;
  49601. var hasComponentChanged;
  49602. // Just cache the attribute if the entity has not loaded
  49603. // Components are not initialized until the entity has loaded
  49604. if (!el.hasLoaded) {
  49605. this.updateCachedAttrValue(attrValue);
  49606. return;
  49607. }
  49608. isSinglePropSchema = isSingleProp(this.schema);
  49609. // Disable type checking if the passed attribute is an object and has not changed.
  49610. skipTypeChecking = attrValue !== null && typeof this.previousAttrValue === 'object' &&
  49611. attrValue === this.previousAttrValue;
  49612. if (skipTypeChecking) {
  49613. for (key in this.attrValue) {
  49614. if (!(key in attrValue)) {
  49615. skipTypeChecking = false;
  49616. break;
  49617. }
  49618. }
  49619. for (key in attrValue) {
  49620. if (!(key in this.attrValue)) {
  49621. skipTypeChecking = false;
  49622. break;
  49623. }
  49624. }
  49625. }
  49626. // Cache previously passed attribute to decide if we skip type checking.
  49627. this.previousAttrValue = attrValue;
  49628. // Cache current attrValue for future updates. Updates `this.attrValue`.
  49629. attrValue = this.parseAttrValueForCache(attrValue);
  49630. this.updateCachedAttrValue(attrValue, clobber);
  49631. if (this.updateSchema) {
  49632. this.updateSchema(this.buildData(this.attrValue, false, true));
  49633. }
  49634. this.data = this.buildData(this.attrValue, clobber, false, skipTypeChecking);
  49635. if (!this.initialized) {
  49636. // Component is being already initialized.
  49637. if (el.initializingComponents[this.name]) { return; }
  49638. // Prevent infinite loop in case of init method setting same component on the entity.
  49639. el.initializingComponents[this.name] = true;
  49640. // Initialize component.
  49641. this.init();
  49642. this.initialized = true;
  49643. delete el.initializingComponents[this.name];
  49644. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  49645. // Pass undefined to rest of types.
  49646. oldData = (!isSinglePropSchema ||
  49647. typeof parseProperty(undefined, this.schema) === 'object') ? {} : undefined;
  49648. // Store current data as previous data for future updates.
  49649. this.oldData = extendProperties({}, this.data, isSinglePropSchema);
  49650. this.update(oldData);
  49651. // Play the component if the entity is playing.
  49652. if (el.isPlaying) { this.play(); }
  49653. el.emit('componentinitialized', this.evtDetail, false);
  49654. } else {
  49655. hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
  49656. // Don't update if properties haven't changed.
  49657. // Always update rotation, position, scale.
  49658. if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
  49659. // Store current data as previous data for future updates.
  49660. this.oldData = extendProperties({}, this.data, isSinglePropSchema);
  49661. // Update component.
  49662. this.update(oldData);
  49663. // In the case of position, rotation, scale always update the component
  49664. // but don't emit componentchanged event if component has not changed.
  49665. if (!hasComponentChanged) { return; }
  49666. this.throttledEmitComponentChanged();
  49667. }
  49668. },
  49669. /**
  49670. * Reset value of a property to the property's default value.
  49671. * If single-prop component, reset value to component's default value.
  49672. *
  49673. * @param {string} propertyName - Name of property to reset.
  49674. */
  49675. resetProperty: function (propertyName) {
  49676. if (isSingleProp(this.schema)) {
  49677. this.attrValue = undefined;
  49678. } else {
  49679. if (!(propertyName in this.attrValue)) { return; }
  49680. delete this.attrValue[propertyName];
  49681. }
  49682. this.updateProperties(this.attrValue);
  49683. },
  49684. /**
  49685. * Extend schema of component given a partial schema.
  49686. *
  49687. * Some components might want to mutate their schema based on certain properties.
  49688. * e.g., Material component changes its schema based on `shader` to account for different
  49689. * uniforms
  49690. *
  49691. * @param {object} schemaAddon - Schema chunk that extend base schema.
  49692. */
  49693. extendSchema: function (schemaAddon) {
  49694. // Clone base schema.
  49695. var extendedSchema = utils.extend({}, components[this.name].schema);
  49696. // Extend base schema with new schema chunk.
  49697. utils.extend(extendedSchema, schemaAddon);
  49698. this.schema = processSchema(extendedSchema);
  49699. this.el.emit('schemachanged', {component: this.name});
  49700. },
  49701. /**
  49702. * Builds component data from the current state of the entity, ultimately
  49703. * updating this.data.
  49704. *
  49705. * If the component was detached completely, set data to null.
  49706. *
  49707. * Precedence:
  49708. * 1. Defaults data
  49709. * 2. Mixin data.
  49710. * 3. Attribute data.
  49711. *
  49712. * Finally coerce the data to the types of the defaults.
  49713. *
  49714. * @param {object} newData - Element new data.
  49715. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  49716. * @param {boolean} silent - Suppress warning messages.
  49717. * @param {boolean} skipTypeChecking - Skip type checking and cohercion.
  49718. * @return {object} The component data
  49719. */
  49720. buildData: function (newData, clobber, silent, skipTypeChecking) {
  49721. var componentDefined;
  49722. var data;
  49723. var defaultValue;
  49724. var keys;
  49725. var keysLength;
  49726. var mixinData;
  49727. var schema = this.schema;
  49728. var i;
  49729. var isSinglePropSchema = isSingleProp(schema);
  49730. var mixinEls = this.el.mixinEls;
  49731. var previousData;
  49732. // Whether component has a defined value. For arrays, treat empty as not defined.
  49733. componentDefined = newData && newData.constructor === Array
  49734. ? newData.length
  49735. : newData !== undefined && newData !== null;
  49736. // 1. Default values (lowest precendence).
  49737. if (isSinglePropSchema) {
  49738. // Clone default value if plain object so components don't share the same object
  49739. // that might be modified by the user.
  49740. data = isObjectOrArray(schema.default) ? utils.clone(schema.default) : schema.default;
  49741. } else {
  49742. // Preserve previously set properties if clobber not enabled.
  49743. previousData = !clobber && this.attrValue;
  49744. // Clone previous data to prevent sharing references with attrValue that might be
  49745. // modified by the user.
  49746. data = typeof previousData === 'object' ? cloneData(previousData) : {};
  49747. // Apply defaults.
  49748. for (i = 0, keys = Object.keys(schema), keysLength = keys.length; i < keysLength; i++) {
  49749. defaultValue = schema[keys[i]].default;
  49750. if (data[keys[i]] !== undefined) { continue; }
  49751. // Clone default value if object so components don't share object
  49752. data[keys[i]] = isObjectOrArray(defaultValue) ? utils.clone(defaultValue) : defaultValue;
  49753. }
  49754. }
  49755. // 2. Mixin values.
  49756. for (i = 0; i < mixinEls.length; i++) {
  49757. mixinData = mixinEls[i].getAttribute(this.attrName);
  49758. if (mixinData) {
  49759. data = extendProperties(data, mixinData, isSinglePropSchema);
  49760. }
  49761. }
  49762. // 3. Attribute values (highest precendence).
  49763. if (componentDefined) {
  49764. if (isSinglePropSchema) {
  49765. if (skipTypeChecking === true) { return newData; }
  49766. return parseProperty(newData, schema);
  49767. }
  49768. data = extendProperties(data, newData, isSinglePropSchema);
  49769. } else {
  49770. if (skipTypeChecking === true) { return data; }
  49771. // Parse and coerce using the schema.
  49772. if (isSinglePropSchema) { return parseProperty(data, schema); }
  49773. }
  49774. if (skipTypeChecking === true) { return data; }
  49775. return parseProperties(data, schema, undefined, this.name, silent);
  49776. }
  49777. };
  49778. // For testing.
  49779. if (window.debug) {
  49780. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  49781. }
  49782. /**
  49783. * Registers a component to A-Frame.
  49784. *
  49785. * @param {string} name - Component name.
  49786. * @param {object} definition - Component schema and lifecycle method handlers.
  49787. * @returns {object} Component.
  49788. */
  49789. module.exports.registerComponent = function (name, definition) {
  49790. var NewComponent;
  49791. var proto = {};
  49792. // Warning if component is statically registered after the scene.
  49793. if (document.currentScript && document.currentScript !== aframeScript) {
  49794. scenes.forEach(function checkPosition (sceneEl) {
  49795. // Okay to register component after the scene at runtime.
  49796. if (sceneEl.hasLoaded) { return; }
  49797. // Check that component is declared before the scene.
  49798. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  49799. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  49800. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  49801. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  49802. 'such that the component is available to entities during scene initialization.');
  49803. // For testing.
  49804. if (window.debug) { registrationOrderWarnings[name] = true; }
  49805. });
  49806. }
  49807. if (upperCaseRegExp.test(name) === true) {
  49808. warn('The component name `' + name + '` contains uppercase characters, but ' +
  49809. 'HTML will ignore the capitalization of attribute names. ' +
  49810. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  49811. }
  49812. if (name.indexOf('__') !== -1) {
  49813. throw new Error('The component name `' + name + '` is not allowed. ' +
  49814. 'The sequence __ (double underscore) is reserved to specify an id' +
  49815. ' for multiple components of the same type');
  49816. }
  49817. // Format definition object to prototype object.
  49818. Object.keys(definition).forEach(function (key) {
  49819. proto[key] = {
  49820. value: definition[key],
  49821. writable: true
  49822. };
  49823. });
  49824. if (components[name]) {
  49825. throw new Error('The component `' + name + '` has been already registered. ' +
  49826. 'Check that you are not loading two versions of the same component ' +
  49827. 'or two different components of the same name.');
  49828. }
  49829. NewComponent = function (el, attr, id) {
  49830. Component.call(this, el, attr, id);
  49831. };
  49832. NewComponent.prototype = Object.create(Component.prototype, proto);
  49833. NewComponent.prototype.name = name;
  49834. NewComponent.prototype.isPositionRotationScale = name === 'position' || name === 'rotation' || name === 'scale';
  49835. NewComponent.prototype.constructor = NewComponent;
  49836. NewComponent.prototype.system = systems && systems.systems[name];
  49837. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  49838. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  49839. components[name] = {
  49840. Component: NewComponent,
  49841. dependencies: NewComponent.prototype.dependencies,
  49842. isSingleProp: isSingleProp(NewComponent.prototype.schema),
  49843. multiple: NewComponent.prototype.multiple,
  49844. parse: NewComponent.prototype.parse,
  49845. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  49846. schema: utils.extend(processSchema(NewComponent.prototype.schema, NewComponent.prototype.name)),
  49847. stringify: NewComponent.prototype.stringify,
  49848. type: NewComponent.prototype.type
  49849. };
  49850. return NewComponent;
  49851. };
  49852. /**
  49853. * Clone component data.
  49854. * Clone only the properties that are plain objects while keeping a reference for the rest.
  49855. *
  49856. * @param data - Component data to clone.
  49857. * @returns Cloned data.
  49858. */
  49859. function cloneData (data) {
  49860. var clone = {};
  49861. var parsedProperty;
  49862. var key;
  49863. for (key in data) {
  49864. parsedProperty = data[key];
  49865. clone[key] = isObjectOrArray(parsedProperty) ? utils.clone(parsedProperty) : parsedProperty;
  49866. }
  49867. return clone;
  49868. }
  49869. /**
  49870. * Object extending with checking for single-property schema.
  49871. *
  49872. * @param dest - Destination object or value.
  49873. * @param source - Source object or value
  49874. * @param {boolean} isSinglePropSchema - Whether or not schema is only a single property.
  49875. * @returns Overridden object or value.
  49876. */
  49877. function extendProperties (dest, source, isSinglePropSchema) {
  49878. if (isSinglePropSchema && (source === null || typeof source !== 'object')) { return source; }
  49879. var copy = utils.extend(dest, source);
  49880. var key;
  49881. for (key in copy) {
  49882. if (!copy[key] || copy[key].constructor !== Object) { continue; }
  49883. copy[key] = utils.clone(copy[key]);
  49884. }
  49885. return copy;
  49886. }
  49887. /**
  49888. * Checks if a component has defined a method that needs to run every frame.
  49889. */
  49890. function hasBehavior (component) {
  49891. return component.tick || component.tock;
  49892. }
  49893. /**
  49894. * Wrapper for user defined pause method
  49895. * Pause component by removing tick behavior and calling user's pause method.
  49896. *
  49897. * @param pauseMethod {function} - user defined pause method
  49898. */
  49899. function wrapPause (pauseMethod) {
  49900. return function pause () {
  49901. var sceneEl = this.el.sceneEl;
  49902. if (!this.isPlaying) { return; }
  49903. pauseMethod.call(this);
  49904. this.isPlaying = false;
  49905. // Remove tick behavior.
  49906. if (!hasBehavior(this)) { return; }
  49907. sceneEl.removeBehavior(this);
  49908. };
  49909. }
  49910. /**
  49911. * Wrapper for user defined play method
  49912. * Play component by adding tick behavior and calling user's play method.
  49913. *
  49914. * @param playMethod {function} - user defined play method
  49915. *
  49916. */
  49917. function wrapPlay (playMethod) {
  49918. return function play () {
  49919. var sceneEl = this.el.sceneEl;
  49920. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  49921. if (!this.initialized || !shouldPlay) { return; }
  49922. playMethod.call(this);
  49923. this.isPlaying = true;
  49924. // Add tick behavior.
  49925. if (!hasBehavior(this)) { return; }
  49926. sceneEl.addBehavior(this);
  49927. };
  49928. }
  49929. function isObjectOrArray (value) {
  49930. return value && (value.constructor === Object || value.constructor === Array);
  49931. }
  49932. },{"../utils/":172,"./scene/scenes":108,"./schema":110,"./system":112}],103:[function(_dereq_,module,exports){
  49933. var schema = _dereq_('./schema');
  49934. var processSchema = schema.process;
  49935. var geometries = module.exports.geometries = {}; // Registered geometries.
  49936. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  49937. var THREE = _dereq_('../lib/three');
  49938. /**
  49939. * Geometry class definition.
  49940. *
  49941. * Geometries extend the geometry component API to create and register geometry types.
  49942. */
  49943. var Geometry = module.exports.Geometry = function () {};
  49944. Geometry.prototype = {
  49945. /**
  49946. * Contains the type schema and defaults for the data values.
  49947. * Data is coerced into the types of the values of the defaults.
  49948. */
  49949. schema: {},
  49950. /**
  49951. * Init handler. Similar to attachedCallback.
  49952. * Called during shader initialization and is only run once.
  49953. */
  49954. init: function (data) {
  49955. this.geometry = new THREE.Geometry();
  49956. return this.geometry;
  49957. },
  49958. /**
  49959. * Update handler. Similar to attributeChangedCallback.
  49960. * Called whenever the associated geometry data changes.
  49961. *
  49962. * @param {object} data - New geometry data.
  49963. */
  49964. update: function (data) { /* no-op */ }
  49965. };
  49966. /**
  49967. * Registers a geometry to A-Frame.
  49968. *
  49969. * @param {string} name - Geometry name.
  49970. * @param {object} definition - Geometry property and methods.
  49971. * @returns {object} Geometry.
  49972. */
  49973. module.exports.registerGeometry = function (name, definition) {
  49974. var NewGeometry;
  49975. var proto = {};
  49976. // Format definition object to prototype object.
  49977. Object.keys(definition).forEach(function expandDefinition (key) {
  49978. proto[key] = {
  49979. value: definition[key],
  49980. writable: true
  49981. };
  49982. });
  49983. if (geometries[name]) {
  49984. throw new Error('The geometry `' + name + '` has been already registered');
  49985. }
  49986. NewGeometry = function () { Geometry.call(this); };
  49987. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  49988. NewGeometry.prototype.name = name;
  49989. NewGeometry.prototype.constructor = NewGeometry;
  49990. geometries[name] = {
  49991. Geometry: NewGeometry,
  49992. schema: processSchema(NewGeometry.prototype.schema)
  49993. };
  49994. geometryNames.push(name);
  49995. return NewGeometry;
  49996. };
  49997. },{"../lib/three":150,"./schema":110}],104:[function(_dereq_,module,exports){
  49998. var coordinates = _dereq_('../utils/coordinates');
  49999. var debug = _dereq_('debug');
  50000. var error = debug('core:propertyTypes:warn');
  50001. var warn = debug('core:propertyTypes:warn');
  50002. var propertyTypes = module.exports.propertyTypes = {};
  50003. var nonCharRegex = /[,> .[\]:]/;
  50004. // Built-in property types.
  50005. registerPropertyType('audio', '', assetParse);
  50006. registerPropertyType('array', [], arrayParse, arrayStringify);
  50007. registerPropertyType('asset', '', assetParse);
  50008. registerPropertyType('boolean', false, boolParse);
  50009. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  50010. registerPropertyType('int', 0, intParse);
  50011. registerPropertyType('number', 0, numberParse);
  50012. registerPropertyType('map', '', assetParse);
  50013. registerPropertyType('model', '', assetParse);
  50014. registerPropertyType('selector', null, selectorParse, selectorStringify);
  50015. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  50016. registerPropertyType('src', '', srcParse);
  50017. registerPropertyType('string', '', defaultParse, defaultStringify);
  50018. registerPropertyType('time', 0, intParse);
  50019. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  50020. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  50021. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  50022. /**
  50023. * Register a parser for re-use such that when someone uses `type` in the schema,
  50024. * `schema.process` will set the property `parse` and `stringify`.
  50025. *
  50026. * @param {string} type - Type name.
  50027. * @param [defaultValue=null] -
  50028. * Default value to use if component does not define default value.
  50029. * @param {function} [parse=defaultParse] - Parse string function.
  50030. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  50031. */
  50032. function registerPropertyType (type, defaultValue, parse, stringify) {
  50033. if ('type' in propertyTypes) {
  50034. error('Property type ' + type + ' is already registered.');
  50035. return;
  50036. }
  50037. propertyTypes[type] = {
  50038. default: defaultValue,
  50039. parse: parse || defaultParse,
  50040. stringify: stringify || defaultStringify
  50041. };
  50042. }
  50043. module.exports.registerPropertyType = registerPropertyType;
  50044. function arrayParse (value) {
  50045. if (Array.isArray(value)) { return value; }
  50046. if (!value || typeof value !== 'string') { return []; }
  50047. return value.split(',').map(trim);
  50048. function trim (str) { return str.trim(); }
  50049. }
  50050. function arrayStringify (value) {
  50051. return value.join(', ');
  50052. }
  50053. /**
  50054. * For general assets.
  50055. *
  50056. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  50057. * just string.
  50058. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  50059. * just string.
  50060. */
  50061. function assetParse (value) {
  50062. var el;
  50063. var parsedUrl;
  50064. // If an element was provided (e.g. canvas or video), just return it.
  50065. if (typeof value !== 'string') { return value; }
  50066. // Wrapped `url()` in case of data URI.
  50067. parsedUrl = value.match(/\url\((.+)\)/);
  50068. if (parsedUrl) { return parsedUrl[1]; }
  50069. // ID.
  50070. if (value.charAt(0) === '#') {
  50071. el = document.getElementById(value.substring(1));
  50072. if (el) {
  50073. // Pass through media elements. If we have the elements, we don't have to call
  50074. // three.js loaders which would re-request the assets.
  50075. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  50076. return el;
  50077. }
  50078. return el.getAttribute('src');
  50079. }
  50080. warn('"' + value + '" asset not found.');
  50081. return;
  50082. }
  50083. // Non-wrapped url().
  50084. return value;
  50085. }
  50086. function defaultParse (value) {
  50087. return value;
  50088. }
  50089. function defaultStringify (value) {
  50090. if (value === null) { return 'null'; }
  50091. return value.toString();
  50092. }
  50093. function boolParse (value) {
  50094. return value !== 'false' && value !== false;
  50095. }
  50096. function intParse (value) {
  50097. return parseInt(value, 10);
  50098. }
  50099. function numberParse (value) {
  50100. return parseFloat(value, 10);
  50101. }
  50102. function selectorParse (value) {
  50103. if (!value) { return null; }
  50104. if (typeof value !== 'string') { return value; }
  50105. if (value[0] === '#' && !nonCharRegex.test(value)) {
  50106. // When selecting element by ID only, use getElementById for better performance.
  50107. // Don't match like #myId .child.
  50108. return document.getElementById(value.substring(1));
  50109. }
  50110. return document.querySelector(value);
  50111. }
  50112. function selectorAllParse (value) {
  50113. if (!value) { return null; }
  50114. if (typeof value !== 'string') { return value; }
  50115. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  50116. }
  50117. function selectorStringify (value) {
  50118. if (value.getAttribute) {
  50119. return '#' + value.getAttribute('id');
  50120. }
  50121. return defaultStringify(value);
  50122. }
  50123. function selectorAllStringify (value) {
  50124. if (value instanceof Array) {
  50125. return value.map(function (element) {
  50126. return '#' + element.getAttribute('id');
  50127. }).join(', ');
  50128. }
  50129. return defaultStringify(value);
  50130. }
  50131. function srcParse (value) {
  50132. warn('`src` property type is deprecated. Use `asset` instead.');
  50133. return assetParse(value);
  50134. }
  50135. function vecParse (value) {
  50136. return coordinates.parse(value, this.default);
  50137. }
  50138. /**
  50139. * Validate the default values in a schema to match their type.
  50140. *
  50141. * @param {string} type - Property type name.
  50142. * @param defaultVal - Property type default value.
  50143. * @returns {boolean} Whether default value is accurate given the type.
  50144. */
  50145. function isValidDefaultValue (type, defaultVal) {
  50146. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  50147. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  50148. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  50149. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  50150. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  50151. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  50152. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  50153. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  50154. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  50155. if (type === 'selector' && typeof defaultVal !== 'string' &&
  50156. defaultVal !== null) { return false; }
  50157. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  50158. defaultVal !== null) { return false; }
  50159. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  50160. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  50161. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  50162. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  50163. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  50164. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  50165. return true;
  50166. }
  50167. module.exports.isValidDefaultValue = isValidDefaultValue;
  50168. /**
  50169. * Checks if default coordinates are valid.
  50170. *
  50171. * @param possibleCoordinates
  50172. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  50173. * @returns {boolean} Whether coordinates are parsed correctly.
  50174. */
  50175. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  50176. if (possibleCoordinates === null) { return true; }
  50177. if (typeof possibleCoordinates !== 'object') { return false; }
  50178. if (Object.keys(possibleCoordinates).length !== dimensions) {
  50179. return false;
  50180. } else {
  50181. var x = possibleCoordinates.x;
  50182. var y = possibleCoordinates.y;
  50183. var z = possibleCoordinates.z;
  50184. var w = possibleCoordinates.w;
  50185. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  50186. if (dimensions > 2 && typeof z !== 'number') { return false; }
  50187. if (dimensions > 3 && typeof w !== 'number') { return false; }
  50188. }
  50189. return true;
  50190. }
  50191. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  50192. },{"../utils/coordinates":167,"debug":8}],105:[function(_dereq_,module,exports){
  50193. /* global Promise, screen */
  50194. var initMetaTags = _dereq_('./metaTags').inject;
  50195. var initWakelock = _dereq_('./wakelock');
  50196. var re = _dereq_('../a-register-element');
  50197. var scenes = _dereq_('./scenes');
  50198. var systems = _dereq_('../system').systems;
  50199. var THREE = _dereq_('../../lib/three');
  50200. var utils = _dereq_('../../utils/');
  50201. // Require after.
  50202. var AEntity = _dereq_('../a-entity');
  50203. var ANode = _dereq_('../a-node');
  50204. var initPostMessageAPI = _dereq_('./postMessage');
  50205. var bind = utils.bind;
  50206. var isIOS = utils.device.isIOS();
  50207. var isMobile = utils.device.isMobile();
  50208. var registerElement = re.registerElement;
  50209. var warn = utils.debug('core:a-scene:warn');
  50210. /**
  50211. * Scene element, holds all entities.
  50212. *
  50213. * @member {array} behaviors - Component instances that have registered themselves to be
  50214. updated on every tick.
  50215. * @member {object} camera - three.js Camera object.
  50216. * @member {object} canvas
  50217. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  50218. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  50219. * @member {object} object3D - Root three.js Scene object.
  50220. * @member {object} renderer
  50221. * @member {bool} renderStarted
  50222. * @member {object} systems - Registered instantiated systems.
  50223. * @member {number} time
  50224. */
  50225. module.exports.AScene = registerElement('a-scene', {
  50226. prototype: Object.create(AEntity.prototype, {
  50227. createdCallback: {
  50228. value: function () {
  50229. this.isIOS = isIOS;
  50230. this.isMobile = isMobile;
  50231. this.isScene = true;
  50232. this.object3D = new THREE.Scene();
  50233. var self = this;
  50234. this.object3D.onAfterRender = function (renderer, scene, camera) {
  50235. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  50236. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  50237. };
  50238. this.render = bind(this.render, this);
  50239. this.systems = {};
  50240. this.systemNames = [];
  50241. this.time = this.delta = 0;
  50242. this.behaviors = {tick: [], tock: []};
  50243. this.hasLoaded = false;
  50244. this.isPlaying = false;
  50245. this.originalHTML = this.innerHTML;
  50246. this.renderTarget = null;
  50247. // Default components.
  50248. this.setAttribute('inspector', '');
  50249. this.setAttribute('keyboard-shortcuts', '');
  50250. this.setAttribute('screenshot', '');
  50251. this.setAttribute('vr-mode-ui', '');
  50252. }
  50253. },
  50254. addFullScreenStyles: {
  50255. value: function () {
  50256. var htmlEl = document.documentElement;
  50257. htmlEl.classList.add('a-html');
  50258. document.body.classList.add('a-body');
  50259. this.classList.add('fullscreen');
  50260. }
  50261. },
  50262. removeFullScreenStyles: {
  50263. value: function () {
  50264. var htmlEl = document.documentElement;
  50265. htmlEl.classList.remove('a-html');
  50266. document.body.classList.remove('a-body');
  50267. this.classList.remove('fullscreen');
  50268. }
  50269. },
  50270. attachedCallback: {
  50271. value: function () {
  50272. var self = this;
  50273. // Renderer initialization
  50274. setupCanvas(this);
  50275. this.setupRenderer();
  50276. this.resize();
  50277. this.addFullScreenStyles();
  50278. initPostMessageAPI(this);
  50279. initMetaTags(this);
  50280. initWakelock(this);
  50281. // Camera set up by camera system.
  50282. this.addEventListener('cameraready', function () {
  50283. self.attachedCallbackPostCamera();
  50284. });
  50285. this.initSystems();
  50286. }
  50287. },
  50288. attachedCallbackPostCamera: {
  50289. value: function () {
  50290. var resize;
  50291. var self = this;
  50292. resize = bind(this.resize, this);
  50293. window.addEventListener('load', resize);
  50294. window.addEventListener('resize', function () {
  50295. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  50296. // where the window does not contain the correct viewport size
  50297. // after an orientation change. The window size is correct if the operation
  50298. // is postponed a few milliseconds.
  50299. // self.resize can be called directly once the bug above is fixed.
  50300. if (self.isIOS) {
  50301. setTimeout(resize, 100);
  50302. } else {
  50303. resize();
  50304. }
  50305. });
  50306. this.play();
  50307. // Add to scene index.
  50308. scenes.push(this);
  50309. // Handler to exit VR (e.g., Oculus Browser back button).
  50310. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  50311. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  50312. // bind functions
  50313. this.enterVRBound = function () { self.enterVR(); };
  50314. this.exitVRBound = function () { self.exitVR(); };
  50315. this.exitVRTrueBound = function () { self.exitVR(true); };
  50316. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  50317. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  50318. // Enter VR on `vrdisplayactivate` (e.g. putting on Rift headset).
  50319. window.addEventListener('vrdisplayactivate', this.enterVRBound);
  50320. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  50321. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  50322. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  50323. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  50324. // Register for mouse restricted events while in VR
  50325. // (e.g. mouse no longer available on desktop 2D view)
  50326. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  50327. // Register for mouse unrestricted events while in VR
  50328. // (e.g. mouse once again available on desktop 2D view)
  50329. window.addEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  50330. },
  50331. writable: window.debug
  50332. },
  50333. /**
  50334. * Initialize all systems.
  50335. */
  50336. initSystems: {
  50337. value: function () {
  50338. var name;
  50339. // Initialize camera system first.
  50340. this.initSystem('camera');
  50341. for (name in systems) {
  50342. if (name === 'camera') { continue; }
  50343. this.initSystem(name);
  50344. }
  50345. }
  50346. },
  50347. /**
  50348. * Initialize a system.
  50349. */
  50350. initSystem: {
  50351. value: function (name) {
  50352. if (this.systems[name]) { return; }
  50353. this.systems[name] = new systems[name](this);
  50354. this.systemNames.push(name);
  50355. }
  50356. },
  50357. /**
  50358. * Shut down scene on detach.
  50359. */
  50360. detachedCallback: {
  50361. value: function () {
  50362. // Remove from scene index.
  50363. var sceneIndex = scenes.indexOf(this);
  50364. scenes.splice(sceneIndex, 1);
  50365. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  50366. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  50367. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  50368. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  50369. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  50370. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  50371. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  50372. }
  50373. },
  50374. /**
  50375. * Add ticks and tocks.
  50376. *
  50377. * @param {object} behavior - A component.
  50378. */
  50379. addBehavior: {
  50380. value: function (behavior) {
  50381. var behaviorArr;
  50382. var behaviors = this.behaviors;
  50383. var behaviorType;
  50384. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  50385. for (behaviorType in behaviors) {
  50386. if (!behavior[behaviorType]) { continue; }
  50387. behaviorArr = this.behaviors[behaviorType];
  50388. if (behaviorArr.indexOf(behavior) === -1) {
  50389. behaviorArr.push(behavior);
  50390. }
  50391. }
  50392. }
  50393. },
  50394. /**
  50395. * For tests.
  50396. */
  50397. getPointerLockElement: {
  50398. value: function () {
  50399. return document.pointerLockElement;
  50400. },
  50401. writable: window.debug
  50402. },
  50403. /**
  50404. * For tests.
  50405. */
  50406. checkHeadsetConnected: {
  50407. value: utils.device.checkHeadsetConnected,
  50408. writable: window.debug
  50409. },
  50410. /**
  50411. * Call `requestPresent` if WebVR or WebVR polyfill.
  50412. * Call `requestFullscreen` on desktop.
  50413. * Handle events, states, fullscreen styles.
  50414. *
  50415. * @returns {Promise}
  50416. */
  50417. enterVR: {
  50418. value: function () {
  50419. var self = this;
  50420. var vrDisplay;
  50421. var vrManager = self.renderer.vr;
  50422. // Don't enter VR if already in VR.
  50423. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  50424. // Enter VR via WebVR API.
  50425. if (this.checkHeadsetConnected() || this.isMobile) {
  50426. vrDisplay = utils.device.getVRDisplay();
  50427. vrManager.setDevice(vrDisplay);
  50428. vrManager.enabled = true;
  50429. if (!vrDisplay.isPresenting) {
  50430. return vrDisplay.requestPresent([{source: this.canvas}])
  50431. .then(enterVRSuccess, enterVRFailure);
  50432. }
  50433. }
  50434. enterVRSuccess();
  50435. return Promise.resolve();
  50436. function enterVRSuccess () {
  50437. self.addState('vr-mode');
  50438. self.emit('enter-vr', {target: self});
  50439. // Lock to landscape orientation on mobile.
  50440. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  50441. screen.orientation.lock('landscape');
  50442. }
  50443. self.addFullScreenStyles();
  50444. // On mobile, the polyfill handles fullscreen.
  50445. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  50446. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  50447. // connected.
  50448. if (!self.isMobile && !self.checkHeadsetConnected()) {
  50449. requestFullscreen(self.canvas);
  50450. }
  50451. self.resize();
  50452. }
  50453. function enterVRFailure (err) {
  50454. if (err && err.message) {
  50455. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  50456. } else {
  50457. throw new Error('Failed to enter VR mode (`requestPresent`).');
  50458. }
  50459. }
  50460. },
  50461. writable: true
  50462. },
  50463. /**
  50464. * Call `exitPresent` if WebVR or WebVR polyfill.
  50465. * Handle events, states, fullscreen styles.
  50466. *
  50467. * @returns {Promise}
  50468. */
  50469. exitVR: {
  50470. value: function () {
  50471. var self = this;
  50472. var vrDisplay;
  50473. // Don't exit VR if not in VR.
  50474. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  50475. exitFullscreen();
  50476. // Handle exiting VR if not yet already and in a headset or polyfill.
  50477. if (this.checkHeadsetConnected() || this.isMobile) {
  50478. this.renderer.vr.enabled = false;
  50479. vrDisplay = utils.device.getVRDisplay();
  50480. if (vrDisplay.isPresenting) {
  50481. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  50482. }
  50483. }
  50484. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  50485. exitVRSuccess();
  50486. return Promise.resolve();
  50487. function exitVRSuccess () {
  50488. self.removeState('vr-mode');
  50489. // Lock to landscape orientation on mobile.
  50490. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  50491. screen.orientation.unlock();
  50492. }
  50493. // Exiting VR in embedded mode, no longer need fullscreen styles.
  50494. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  50495. self.resize();
  50496. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  50497. self.emit('exit-vr', {target: self});
  50498. }
  50499. function exitVRFailure (err) {
  50500. if (err && err.message) {
  50501. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  50502. } else {
  50503. throw new Error('Failed to exit VR mode (`exitPresent`).');
  50504. }
  50505. }
  50506. },
  50507. writable: true
  50508. },
  50509. pointerRestricted: {
  50510. value: function () {
  50511. if (this.canvas) {
  50512. var pointerLockElement = this.getPointerLockElement();
  50513. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  50514. // Recreate pointer lock on the canvas, if taken on another element.
  50515. document.exitPointerLock();
  50516. }
  50517. if (this.canvas.requestPointerLock) {
  50518. this.canvas.requestPointerLock();
  50519. }
  50520. }
  50521. }
  50522. },
  50523. pointerUnrestricted: {
  50524. value: function () {
  50525. var pointerLockElement = this.getPointerLockElement();
  50526. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  50527. document.exitPointerLock();
  50528. }
  50529. }
  50530. },
  50531. /**
  50532. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  50533. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  50534. */
  50535. onVRPresentChange: {
  50536. value: function (evt) {
  50537. // Polyfill places display inside the detail property
  50538. var display = evt.display || evt.detail.display;
  50539. // Entering VR.
  50540. if (display.isPresenting) {
  50541. this.enterVR();
  50542. return;
  50543. }
  50544. // Exiting VR.
  50545. this.exitVR();
  50546. }
  50547. },
  50548. /**
  50549. * Wraps Entity.getAttribute to take into account for systems.
  50550. * If system exists, then return system data rather than possible component data.
  50551. */
  50552. getAttribute: {
  50553. value: function (attr) {
  50554. var system = this.systems[attr];
  50555. if (system) { return system.data; }
  50556. return AEntity.prototype.getAttribute.call(this, attr);
  50557. }
  50558. },
  50559. /**
  50560. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  50561. * what `getAttribute` is now. Now legacy code.
  50562. */
  50563. getComputedAttribute: {
  50564. value: function (attr) {
  50565. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  50566. this.getAttribute(attr);
  50567. }
  50568. },
  50569. /**
  50570. * Wraps Entity.getDOMAttribute to take into account for systems.
  50571. * If system exists, then return system data rather than possible component data.
  50572. */
  50573. getDOMAttribute: {
  50574. value: function (attr) {
  50575. var system = this.systems[attr];
  50576. if (system) { return system.data; }
  50577. return AEntity.prototype.getDOMAttribute.call(this, attr);
  50578. }
  50579. },
  50580. /**
  50581. * Wrap Entity.setAttribute to take into account for systems.
  50582. * If system exists, then skip component initialization checks and do a normal
  50583. * setAttribute.
  50584. */
  50585. setAttribute: {
  50586. value: function (attr, value, componentPropValue) {
  50587. var system = this.systems[attr];
  50588. if (system) {
  50589. ANode.prototype.setAttribute.call(this, attr, value);
  50590. system.updateProperties(value);
  50591. return;
  50592. }
  50593. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  50594. }
  50595. },
  50596. /**
  50597. * @param {object} behavior - A component.
  50598. */
  50599. removeBehavior: {
  50600. value: function (behavior) {
  50601. var behaviorArr;
  50602. var behaviorType;
  50603. var behaviors = this.behaviors;
  50604. var index;
  50605. // Check if behavior has tick and/or tock and remove the behavior from the appropriate
  50606. // array.
  50607. for (behaviorType in behaviors) {
  50608. if (!behavior[behaviorType]) { continue; }
  50609. behaviorArr = this.behaviors[behaviorType];
  50610. index = behaviorArr.indexOf(behavior);
  50611. if (index !== -1) { behaviorArr.splice(index, 1); }
  50612. }
  50613. }
  50614. },
  50615. resize: {
  50616. value: function () {
  50617. var camera = this.camera;
  50618. var canvas = this.canvas;
  50619. var embedded;
  50620. var isVRPresenting;
  50621. var size;
  50622. var vrDevice;
  50623. vrDevice = this.renderer.vr.getDevice();
  50624. isVRPresenting = this.renderer.vr.enabled && vrDevice && vrDevice.isPresenting;
  50625. // Do not update renderer, if a camera or a canvas have not been injected.
  50626. // In VR mode, three handles canvas resize based on the dimensions returned by
  50627. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  50628. // the window size, therefore should not be overwritten with the window's width and
  50629. // height, // except when in fullscreen mode.
  50630. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) {
  50631. return;
  50632. }
  50633. // Update camera.
  50634. embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  50635. size = getCanvasSize(canvas, embedded, this.maxCanvasSize, this.is('vr-mode'));
  50636. camera.aspect = size.width / size.height;
  50637. camera.updateProjectionMatrix();
  50638. // Notify renderer of size change.
  50639. this.renderer.setSize(size.width, size.height, false);
  50640. this.emit('rendererresize', null, false);
  50641. },
  50642. writable: true
  50643. },
  50644. setupRenderer: {
  50645. value: function () {
  50646. var self = this;
  50647. var renderer;
  50648. var rendererAttr;
  50649. var rendererAttrString;
  50650. var rendererConfig;
  50651. rendererConfig = {alpha: true, antialias: !isMobile, canvas: this.canvas, logarithmicDepthBuffer: false};
  50652. if (this.hasAttribute('antialias')) {
  50653. rendererConfig.antialias = this.getAttribute('antialias') === 'true';
  50654. }
  50655. if (this.hasAttribute('logarithmicDepthBuffer')) {
  50656. rendererConfig.logarithmicDepthBuffer = this.getAttribute('logarithmicDepthBuffer') === 'true';
  50657. }
  50658. this.maxCanvasSize = {height: 1920, width: 1920};
  50659. if (this.hasAttribute('renderer')) {
  50660. rendererAttrString = this.getAttribute('renderer');
  50661. rendererAttr = utils.styleParser.parse(rendererAttrString);
  50662. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  50663. rendererConfig.antialias = rendererAttr.antialias === 'true';
  50664. }
  50665. this.maxCanvasSize = {
  50666. width: rendererAttr.maxCanvasWidth
  50667. ? parseInt(rendererAttr.maxCanvasWidth)
  50668. : this.maxCanvasSize.width,
  50669. height: rendererAttr.maxCanvasHeight
  50670. ? parseInt(rendererAttr.maxCanvasHeight)
  50671. : this.maxCanvasSize.height
  50672. };
  50673. }
  50674. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  50675. renderer.setPixelRatio(window.devicePixelRatio);
  50676. renderer.sortObjects = false;
  50677. renderer.vr.setPoseTarget(this.camera);
  50678. this.addEventListener('camera-set-active', function () {
  50679. renderer.vr.setPoseTarget(self.camera);
  50680. });
  50681. },
  50682. writable: window.debug
  50683. },
  50684. /**
  50685. * Handler attached to elements to help scene know when to kick off.
  50686. * Scene waits for all entities to load.
  50687. */
  50688. play: {
  50689. value: function () {
  50690. var self = this;
  50691. var sceneEl = this;
  50692. if (this.renderStarted) {
  50693. AEntity.prototype.play.call(this);
  50694. return;
  50695. }
  50696. this.addEventListener('loaded', function () {
  50697. AEntity.prototype.play.call(this); // .play() *before* render.
  50698. if (sceneEl.renderStarted) { return; }
  50699. sceneEl.resize();
  50700. // Kick off render loop.
  50701. if (sceneEl.renderer) {
  50702. if (window.performance) { window.performance.mark('render-started'); }
  50703. sceneEl.clock = new THREE.Clock();
  50704. sceneEl.render();
  50705. sceneEl.renderStarted = true;
  50706. sceneEl.emit('renderstart');
  50707. }
  50708. });
  50709. // setTimeout to wait for all nodes to attach and run their callbacks.
  50710. setTimeout(function () {
  50711. AEntity.prototype.load.call(self);
  50712. });
  50713. }
  50714. },
  50715. /**
  50716. * Wrap `updateComponent` to not initialize the component if the component has a system
  50717. * (aframevr/aframe#2365).
  50718. */
  50719. updateComponent: {
  50720. value: function (componentName) {
  50721. if (componentName in systems) { return; }
  50722. AEntity.prototype.updateComponent.apply(this, arguments);
  50723. }
  50724. },
  50725. /**
  50726. * Behavior-updater meant to be called from scene render.
  50727. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  50728. * needing to render.
  50729. */
  50730. tick: {
  50731. value: function (time, timeDelta) {
  50732. var i;
  50733. var systems = this.systems;
  50734. // Components.
  50735. for (i = 0; i < this.behaviors.tick.length; i++) {
  50736. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  50737. this.behaviors.tick[i].tick(time, timeDelta);
  50738. }
  50739. // Systems.
  50740. for (i = 0; i < this.systemNames.length; i++) {
  50741. if (!systems[this.systemNames[i]].tick) { continue; }
  50742. systems[this.systemNames[i]].tick(time, timeDelta);
  50743. }
  50744. }
  50745. },
  50746. /**
  50747. * Behavior-updater meant to be called after scene render for post processing purposes.
  50748. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  50749. * needing to render.
  50750. */
  50751. tock: {
  50752. value: function (time, timeDelta, camera) {
  50753. var i;
  50754. var systems = this.systems;
  50755. // Components.
  50756. for (i = 0; i < this.behaviors.tock.length; i++) {
  50757. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  50758. this.behaviors.tock[i].tock(time, timeDelta, camera);
  50759. }
  50760. // Systems.
  50761. for (i = 0; i < this.systemNames.length; i++) {
  50762. if (!systems[this.systemNames[i]].tock) { continue; }
  50763. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  50764. }
  50765. }
  50766. },
  50767. /**
  50768. * The render loop.
  50769. *
  50770. * Updates animations.
  50771. * Updates behaviors.
  50772. * Renders with request animation frame.
  50773. */
  50774. render: {
  50775. value: function () {
  50776. var renderer = this.renderer;
  50777. this.delta = this.clock.getDelta() * 1000;
  50778. this.time = this.clock.elapsedTime * 1000;
  50779. if (this.isPlaying) { this.tick(this.time, this.delta); }
  50780. renderer.setAnimationLoop(this.render);
  50781. renderer.render(this.object3D, this.camera, this.renderTarget);
  50782. },
  50783. writable: true
  50784. }
  50785. })
  50786. });
  50787. /**
  50788. * Return the canvas size where the scene will be rendered.
  50789. * Will be always the window size except when the scene is embedded.
  50790. * The parent size (less than max size) will be returned in that case.
  50791. *
  50792. * @param {object} canvasEl - the canvas element
  50793. * @param {boolean} embedded - Is the scene embedded?
  50794. * @param {object} max - Max size parameters
  50795. * @param {boolean} isVR - If in VR
  50796. */
  50797. function getCanvasSize (canvasEl, embedded, maxSize, isVR) {
  50798. if (embedded) {
  50799. return {
  50800. height: canvasEl.parentElement.offsetHeight,
  50801. width: canvasEl.parentElement.offsetWidth
  50802. };
  50803. }
  50804. return getMaxSize(maxSize, isVR);
  50805. }
  50806. /**
  50807. * Return the canvas size. Will be the window size unless that size is greater than the
  50808. * maximum size (1920x1920 by default). The constrained size will be returned in that case,
  50809. * maintaining aspect ratio
  50810. *
  50811. * @param {object} maxSize - Max size parameters (width and height).
  50812. * @param {boolean} isVR - If in VR.
  50813. * @returns {object} Width and height.
  50814. */
  50815. function getMaxSize (maxSize, isVR) {
  50816. var aspectRatio;
  50817. var size;
  50818. var pixelRatio = window.devicePixelRatio;
  50819. size = {height: document.body.offsetHeight, width: document.body.offsetWidth};
  50820. if (!maxSize || isVR || (maxSize.width === -1 && maxSize.height === -1)) {
  50821. return size;
  50822. }
  50823. if (size.width * pixelRatio < maxSize.width &&
  50824. size.height * pixelRatio < maxSize.height) {
  50825. return size;
  50826. }
  50827. aspectRatio = size.width / size.height;
  50828. if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
  50829. size.width = Math.round(maxSize.width / pixelRatio);
  50830. size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
  50831. }
  50832. if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
  50833. size.height = Math.round(maxSize.height / pixelRatio);
  50834. size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
  50835. }
  50836. return size;
  50837. }
  50838. function requestFullscreen (canvas) {
  50839. var requestFullscreen =
  50840. canvas.requestFullscreen ||
  50841. canvas.webkitRequestFullscreen ||
  50842. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  50843. canvas.msRequestFullscreen;
  50844. requestFullscreen.apply(canvas);
  50845. }
  50846. function exitFullscreen () {
  50847. if (document.exitFullscreen) {
  50848. document.exitFullscreen();
  50849. } else if (document.mozCancelFullScreen) {
  50850. document.mozCancelFullScreen();
  50851. } else if (document.webkitExitFullscreen) {
  50852. document.webkitExitFullscreen();
  50853. }
  50854. }
  50855. function setupCanvas (sceneEl) {
  50856. var canvasEl;
  50857. canvasEl = document.createElement('canvas');
  50858. canvasEl.classList.add('a-canvas');
  50859. // Mark canvas as provided/injected by A-Frame.
  50860. canvasEl.dataset.aframeCanvas = true;
  50861. sceneEl.appendChild(canvasEl);
  50862. document.addEventListener('fullscreenchange', onFullScreenChange);
  50863. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  50864. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  50865. // Prevent overscroll on mobile.
  50866. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  50867. // Set canvas on scene.
  50868. sceneEl.canvas = canvasEl;
  50869. sceneEl.emit('render-target-loaded', {target: canvasEl});
  50870. // For unknown reasons a synchronous resize does not work on desktop when
  50871. // entering/exiting fullscreen.
  50872. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  50873. function onFullScreenChange () {
  50874. var fullscreenEl =
  50875. document.fullscreenElement ||
  50876. document.mozFullScreenElement ||
  50877. document.webkitFullscreenElement;
  50878. // No fullscren element === exit fullscreen
  50879. if (!fullscreenEl) { sceneEl.exitVR(); }
  50880. document.activeElement.blur();
  50881. document.body.focus();
  50882. }
  50883. }
  50884. module.exports.setupCanvas = setupCanvas; // For testing.
  50885. },{"../../lib/three":150,"../../utils/":172,"../a-entity":98,"../a-node":100,"../a-register-element":101,"../system":112,"./metaTags":106,"./postMessage":107,"./scenes":108,"./wakelock":109}],106:[function(_dereq_,module,exports){
  50886. var constants = _dereq_('../../constants/');
  50887. var extend = _dereq_('../../utils').extend;
  50888. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  50889. Meta({name: 'viewport', content: 'width=device-width,initial-scale=1,maximum-scale=1,shrink-to-fit=no,user-scalable=no,minimal-ui'}),
  50890. // W3C-standardised meta tags.
  50891. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  50892. Meta({name: 'theme-color', content: 'black'})
  50893. ];
  50894. var MOBILE_IOS_HEAD_TAGS = [
  50895. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  50896. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  50897. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  50898. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  50899. ];
  50900. function Meta (attrs) {
  50901. return {
  50902. tagName: 'meta',
  50903. attributes: attrs,
  50904. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  50905. };
  50906. }
  50907. function Link (attrs) {
  50908. return {
  50909. tagName: 'link',
  50910. attributes: attrs,
  50911. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  50912. };
  50913. }
  50914. /**
  50915. * Injects the necessary metatags in the document for mobile support:
  50916. * 1. Prevent the user to zoom in the document.
  50917. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  50918. * values and the canvas is properly scaled.
  50919. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  50920. * iOS.
  50921. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  50922. *
  50923. * @param {object} scene - Scene element
  50924. * @returns {Array}
  50925. */
  50926. module.exports.inject = function injectHeadTags (scene) {
  50927. var headEl = document.head;
  50928. var headScriptEl = headEl.querySelector('script');
  50929. var tag;
  50930. var headTags = [];
  50931. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  50932. if (scene.isIOS) {
  50933. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  50934. }
  50935. return headTags;
  50936. function createAndInjectTag (tagObj) {
  50937. if (!tagObj || tagObj.exists()) { return; }
  50938. tag = createTag(tagObj);
  50939. if (!tag) { return; }
  50940. if (headScriptEl) {
  50941. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  50942. } else {
  50943. headEl.appendChild(tag);
  50944. }
  50945. headTags.push(tag);
  50946. }
  50947. };
  50948. function createTag (tagObj) {
  50949. if (!tagObj || !tagObj.tagName) { return; }
  50950. var meta = document.createElement(tagObj.tagName);
  50951. meta.setAttribute(constants.AFRAME_INJECTED, '');
  50952. return extend(meta, tagObj.attributes);
  50953. }
  50954. },{"../../constants/":94,"../../utils":172}],107:[function(_dereq_,module,exports){
  50955. var bind = _dereq_('../../utils/bind');
  50956. var isIframed = _dereq_('../../utils/').isIframed;
  50957. /**
  50958. * Provides a post message API for scenes contained
  50959. * in an iframe.
  50960. */
  50961. module.exports = function initPostMessageAPI (scene) {
  50962. // Handles fullscreen behavior when inside an iframe.
  50963. if (!isIframed()) { return; }
  50964. // postMessage API handler
  50965. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  50966. };
  50967. function postMessageAPIHandler (event) {
  50968. var scene = this;
  50969. if (!event.data) { return; }
  50970. switch (event.data.type) {
  50971. case 'vr': {
  50972. switch (event.data.data) {
  50973. case 'enter':
  50974. scene.enterVR();
  50975. break;
  50976. case 'exit':
  50977. scene.exitVR();
  50978. break;
  50979. }
  50980. }
  50981. }
  50982. }
  50983. },{"../../utils/":172,"../../utils/bind":166}],108:[function(_dereq_,module,exports){
  50984. /*
  50985. Scene index for keeping track of created scenes.
  50986. */
  50987. module.exports = [];
  50988. },{}],109:[function(_dereq_,module,exports){
  50989. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  50990. module.exports = function initWakelock (scene) {
  50991. if (!scene.isMobile) { return; }
  50992. var wakelock = scene.wakelock = new Wakelock();
  50993. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  50994. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  50995. };
  50996. },{"../../../vendor/wakelock/wakelock":182}],110:[function(_dereq_,module,exports){
  50997. var utils = _dereq_('../utils/');
  50998. var PropertyTypes = _dereq_('./propertyTypes');
  50999. var debug = utils.debug;
  51000. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  51001. var propertyTypes = PropertyTypes.propertyTypes;
  51002. var warn = debug('core:schema:warn');
  51003. /**
  51004. * A schema is classified as a schema for a single property if:
  51005. * - `type` is defined on the schema as a string.
  51006. * - OR `default` is defined on the schema, as a reserved keyword.
  51007. * - OR schema is empty.
  51008. */
  51009. function isSingleProperty (schema) {
  51010. if ('type' in schema) {
  51011. return typeof schema.type === 'string';
  51012. }
  51013. return 'default' in schema;
  51014. }
  51015. module.exports.isSingleProperty = isSingleProperty;
  51016. /**
  51017. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  51018. *
  51019. * @param {object} schema
  51020. * @param {string} componentName
  51021. * @returns {object} Schema.
  51022. */
  51023. module.exports.process = function (schema, componentName) {
  51024. var propName;
  51025. // For single property schema, run processPropDefinition over the whole schema.
  51026. if (isSingleProperty(schema)) {
  51027. return processPropertyDefinition(schema, componentName);
  51028. }
  51029. // For multi-property schema, run processPropDefinition over each property definition.
  51030. for (propName in schema) {
  51031. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  51032. }
  51033. return schema;
  51034. };
  51035. /**
  51036. * Inject default value, parser, stringifier for single property.
  51037. *
  51038. * @param {object} propDefinition
  51039. * @param {string} componentName
  51040. */
  51041. function processPropertyDefinition (propDefinition, componentName) {
  51042. var defaultVal = propDefinition.default;
  51043. var isCustomType;
  51044. var propType;
  51045. var typeName = propDefinition.type;
  51046. // Type inference.
  51047. if (!propDefinition.type) {
  51048. if (defaultVal !== undefined &&
  51049. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  51050. // Type inference.
  51051. typeName = typeof defaultVal;
  51052. } else if (Array.isArray(defaultVal)) {
  51053. typeName = 'array';
  51054. } else {
  51055. // Fall back to string.
  51056. typeName = 'string';
  51057. }
  51058. } else if (propDefinition.type === 'bool') {
  51059. typeName = 'boolean';
  51060. } else if (propDefinition.type === 'float') {
  51061. typeName = 'number';
  51062. }
  51063. propType = propertyTypes[typeName];
  51064. if (!propType) {
  51065. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  51066. }
  51067. // Fill in parse and stringify using property types.
  51068. isCustomType = !!propDefinition.parse;
  51069. propDefinition.parse = propDefinition.parse || propType.parse;
  51070. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  51071. // Fill in type name.
  51072. propDefinition.type = typeName;
  51073. // Check that default value exists.
  51074. if ('default' in propDefinition) {
  51075. // Check that default values are valid.
  51076. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  51077. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  51078. '` in component `' + componentName + '`');
  51079. }
  51080. } else {
  51081. // Fill in default value.
  51082. propDefinition.default = propType.default;
  51083. }
  51084. return propDefinition;
  51085. }
  51086. module.exports.processPropertyDefinition = processPropertyDefinition;
  51087. /**
  51088. * Parse propData using schema. Use default values if not existing in propData.
  51089. *
  51090. * @param {object} propData - Unparsed properties.
  51091. * @param {object} schema - Property types definition.
  51092. * @param {boolean} getPartialData - Whether to return full component data or just the data
  51093. * with keys in `propData`.
  51094. * @param {string } componentName - Name of the component, used for the property warning.
  51095. * @param {boolean} silent - Suppress warning messages.
  51096. */
  51097. module.exports.parseProperties = (function () {
  51098. var propNames = [];
  51099. return function (propData, schema, getPartialData, componentName, silent) {
  51100. var i;
  51101. var propName;
  51102. var propDefinition;
  51103. var propValue;
  51104. propNames.length = 0;
  51105. for (propName in (getPartialData ? propData : schema)) { propNames.push(propName); }
  51106. if (propData === null || typeof propData !== 'object') { return propData; }
  51107. // Validation errors.
  51108. for (propName in propData) {
  51109. if (!schema[propName] && !silent) {
  51110. warn('Unknown property `' + propName +
  51111. '` for component/system `' + componentName + '`.');
  51112. }
  51113. }
  51114. for (i = 0; i < propNames.length; i++) {
  51115. propName = propNames[i];
  51116. propDefinition = schema[propName];
  51117. propValue = propData[propName];
  51118. if (!(schema[propName])) { return; }
  51119. propData[propName] = parseProperty(propValue, propDefinition);
  51120. }
  51121. return propData;
  51122. };
  51123. })();
  51124. /**
  51125. * Deserialize a single property.
  51126. */
  51127. function parseProperty (value, propDefinition) {
  51128. // Use default value if value is falsy.
  51129. if (value === undefined || value === null || value === '') {
  51130. value = propDefinition.default;
  51131. if (Array.isArray(value)) { value = value.slice(); }
  51132. }
  51133. // Invoke property type parser.
  51134. return propDefinition.parse(value, propDefinition.default);
  51135. }
  51136. module.exports.parseProperty = parseProperty;
  51137. /**
  51138. * Serialize a group of properties.
  51139. */
  51140. module.exports.stringifyProperties = function (propData, schema) {
  51141. var propName;
  51142. var propDefinition;
  51143. var propValue;
  51144. var stringifiedData = {};
  51145. var value;
  51146. for (propName in propData) {
  51147. propDefinition = schema[propName];
  51148. propValue = propData[propName];
  51149. value = propValue;
  51150. if (typeof value === 'object') {
  51151. value = stringifyProperty(propValue, propDefinition);
  51152. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  51153. }
  51154. stringifiedData[propName] = value;
  51155. }
  51156. return stringifiedData;
  51157. };
  51158. /**
  51159. * Serialize a single property.
  51160. */
  51161. function stringifyProperty (value, propDefinition) {
  51162. // This function stringifies but it's used in a context where
  51163. // there's always second stringification pass. By returning the original
  51164. // value when it's not an object we save one unnecessary call
  51165. // to JSON.stringify.
  51166. if (typeof value !== 'object') { return value; }
  51167. // if there's no schema for the property we use standar JSON stringify
  51168. if (!propDefinition || value === null) { return JSON.stringify(value); }
  51169. return propDefinition.stringify(value);
  51170. }
  51171. module.exports.stringifyProperty = stringifyProperty;
  51172. },{"../utils/":172,"./propertyTypes":104}],111:[function(_dereq_,module,exports){
  51173. var schema = _dereq_('./schema');
  51174. var processSchema = schema.process;
  51175. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  51176. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  51177. var THREE = _dereq_('../lib/three');
  51178. var utils = _dereq_('../utils');
  51179. // A-Frame properties to three.js uniform types.
  51180. var propertyToThreeMapping = {
  51181. array: 'v3',
  51182. color: 'v3',
  51183. int: 'i',
  51184. number: 'f',
  51185. map: 't',
  51186. time: 'f',
  51187. vec2: 'v2',
  51188. vec3: 'v3',
  51189. vec4: 'v4'
  51190. };
  51191. /**
  51192. * Shader class definition.
  51193. *
  51194. * Shaders extend the material component API so you can create your own library
  51195. * of customized materials
  51196. *
  51197. */
  51198. var Shader = module.exports.Shader = function () {};
  51199. Shader.prototype = {
  51200. /**
  51201. * Contains the type schema and defaults for the data values.
  51202. * Data is coerced into the types of the values of the defaults.
  51203. */
  51204. schema: {},
  51205. vertexShader:
  51206. 'void main() {' +
  51207. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  51208. '}',
  51209. fragmentShader:
  51210. 'void main() {' +
  51211. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  51212. '}',
  51213. /**
  51214. * Init handler. Similar to attachedCallback.
  51215. * Called during shader initialization and is only run once.
  51216. */
  51217. init: function (data) {
  51218. this.attributes = this.initVariables(data, 'attribute');
  51219. this.uniforms = this.initVariables(data, 'uniform');
  51220. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  51221. // attributes: this.attributes,
  51222. uniforms: this.uniforms,
  51223. vertexShader: this.vertexShader,
  51224. fragmentShader: this.fragmentShader
  51225. });
  51226. return this.material;
  51227. },
  51228. initVariables: function (data, type) {
  51229. var key;
  51230. var schema = this.schema;
  51231. var variables = {};
  51232. var varType;
  51233. for (key in schema) {
  51234. if (schema[key].is !== type) { continue; }
  51235. varType = propertyToThreeMapping[schema[key].type];
  51236. variables[key] = {
  51237. type: varType,
  51238. value: undefined // Let updateVariables handle setting these.
  51239. };
  51240. }
  51241. return variables;
  51242. },
  51243. /**
  51244. * Update handler. Similar to attributeChangedCallback.
  51245. * Called whenever the associated material data changes.
  51246. *
  51247. * @param {object} data - New material data.
  51248. */
  51249. update: function (data) {
  51250. this.updateVariables(data, 'attribute');
  51251. this.updateVariables(data, 'uniform');
  51252. },
  51253. updateVariables: function (data, type) {
  51254. var key;
  51255. var materialKey;
  51256. var schema = this.schema;
  51257. var variables;
  51258. variables = type === 'uniform' ? this.uniforms : this.attributes;
  51259. for (key in data) {
  51260. if (!schema[key] || schema[key].is !== type) { continue; }
  51261. if (schema[key].type === 'map') {
  51262. // If data unchanged, get out early.
  51263. if (!variables[key] || variables[key].value === data[key]) { continue; }
  51264. // Special handling is needed for textures.
  51265. materialKey = '_texture_' + key;
  51266. // We can't actually set the variable correctly until we've loaded the texture.
  51267. this.setMapOnTextureLoad(variables, key, materialKey);
  51268. // Kick off the texture update now that handler is added.
  51269. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  51270. continue;
  51271. }
  51272. variables[key].value = this.parseValue(schema[key].type, data[key]);
  51273. variables[key].needsUpdate = true;
  51274. }
  51275. },
  51276. parseValue: function (type, value) {
  51277. var color;
  51278. switch (type) {
  51279. case 'vec2': {
  51280. return new THREE.Vector2(value.x, value.y);
  51281. }
  51282. case 'vec3': {
  51283. return new THREE.Vector3(value.x, value.y, value.z);
  51284. }
  51285. case 'vec4': {
  51286. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  51287. }
  51288. case 'color': {
  51289. color = new THREE.Color(value);
  51290. return new THREE.Vector3(color.r, color.g, color.b);
  51291. }
  51292. case 'map': {
  51293. return THREE.ImageUtils.loadTexture(value);
  51294. }
  51295. default: {
  51296. return value;
  51297. }
  51298. }
  51299. },
  51300. setMapOnTextureLoad: function (variables, key, materialKey) {
  51301. var self = this;
  51302. this.el.addEventListener('materialtextureloaded', function () {
  51303. variables[key].value = self.material[materialKey];
  51304. variables[key].needsUpdate = true;
  51305. });
  51306. }
  51307. };
  51308. /**
  51309. * Registers a shader to A-Frame.
  51310. *
  51311. * @param {string} name - shader name.
  51312. * @param {object} definition - shader property and methods.
  51313. * @returns {object} Shader.
  51314. */
  51315. module.exports.registerShader = function (name, definition) {
  51316. var NewShader;
  51317. var proto = {};
  51318. // Format definition object to prototype object.
  51319. Object.keys(definition).forEach(function (key) {
  51320. proto[key] = {
  51321. value: definition[key],
  51322. writable: true
  51323. };
  51324. });
  51325. if (shaders[name]) {
  51326. throw new Error('The shader ' + name + ' has been already registered');
  51327. }
  51328. NewShader = function () { Shader.call(this); };
  51329. NewShader.prototype = Object.create(Shader.prototype, proto);
  51330. NewShader.prototype.name = name;
  51331. NewShader.prototype.constructor = NewShader;
  51332. shaders[name] = {
  51333. Shader: NewShader,
  51334. schema: processSchema(NewShader.prototype.schema)
  51335. };
  51336. shaderNames.push(name);
  51337. return NewShader;
  51338. };
  51339. },{"../lib/three":150,"../utils":172,"./schema":110}],112:[function(_dereq_,module,exports){
  51340. var components = _dereq_('./component');
  51341. var schema = _dereq_('./schema');
  51342. var utils = _dereq_('../utils/');
  51343. var parseProperties = schema.parseProperties;
  51344. var parseProperty = schema.parseProperty;
  51345. var processSchema = schema.process;
  51346. var isSingleProp = schema.isSingleProperty;
  51347. var styleParser = utils.styleParser;
  51348. var systems = module.exports.systems = {}; // Keep track of registered systems.
  51349. /**
  51350. * System class definition.
  51351. *
  51352. * Systems provide global scope and services to a group of instantiated components of the
  51353. * same class. They can also help abstract logic away from components such that components
  51354. * only have to worry about data.
  51355. *
  51356. * For example, a physics component that creates a physics world that oversees
  51357. * all entities with a physics or rigid body component.
  51358. *
  51359. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  51360. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  51361. * setAttribute behavior).
  51362. *
  51363. * @member {string} name - Name that system is registered under.
  51364. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  51365. */
  51366. var System = module.exports.System = function (sceneEl) {
  51367. var component = components && components.components[this.name];
  51368. // Set reference to scene.
  51369. this.el = sceneEl;
  51370. this.sceneEl = sceneEl;
  51371. // Set reference to matching component (if exists).
  51372. if (component) { component.Component.prototype.system = this; }
  51373. // Process system configuration.
  51374. this.buildData();
  51375. this.init();
  51376. this.update({});
  51377. };
  51378. System.prototype = {
  51379. /**
  51380. * Schema to configure system.
  51381. */
  51382. schema: {},
  51383. /**
  51384. * Init handler. Called during scene initialization and is only run once.
  51385. * Systems can use this to set initial state.
  51386. */
  51387. init: function () { /* no-op */ },
  51388. /**
  51389. * Update handler. Called during scene attribute updates.
  51390. * Systems can use this to dynamically update their state.
  51391. */
  51392. update: function (oldData) { /* no-op */ },
  51393. /**
  51394. * Build data and call update handler.
  51395. *
  51396. * @private
  51397. */
  51398. updateProperties: function (rawData) {
  51399. var oldData = this.data;
  51400. if (!Object.keys(schema).length) { return; }
  51401. this.buildData(rawData);
  51402. this.update(oldData);
  51403. },
  51404. /**
  51405. * Parse data.
  51406. */
  51407. buildData: function (rawData) {
  51408. var schema = this.schema;
  51409. if (!Object.keys(schema).length) { return; }
  51410. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  51411. if (isSingleProp(schema)) {
  51412. this.data = parseProperty(rawData, schema);
  51413. } else {
  51414. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  51415. }
  51416. },
  51417. /**
  51418. * Tick handler.
  51419. * Called on each tick of the scene render loop.
  51420. * Affected by play and pause.
  51421. *
  51422. * @param {number} time - Scene tick time.
  51423. * @param {number} timeDelta - Difference in current render time and previous render time.
  51424. */
  51425. tick: undefined,
  51426. /**
  51427. * Tock handler.
  51428. * Called on each tock of the scene render loop.
  51429. * Affected by play and pause.
  51430. *
  51431. * @param {number} time - Scene tick time.
  51432. * @param {number} timeDelta - Difference in current render time and previous render time.
  51433. */
  51434. tock: undefined,
  51435. /**
  51436. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  51437. */
  51438. play: function () { /* no-op */ },
  51439. /**
  51440. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  51441. */
  51442. pause: function () { /* no-op */ }
  51443. };
  51444. /**
  51445. * Registers a system to A-Frame.
  51446. *
  51447. * @param {string} name - Component name.
  51448. * @param {object} definition - Component property and methods.
  51449. * @returns {object} Component.
  51450. */
  51451. module.exports.registerSystem = function (name, definition) {
  51452. var i;
  51453. var NewSystem;
  51454. var proto = {};
  51455. var scenes = utils.findAllScenes(document);
  51456. // Format definition object to prototype object.
  51457. Object.keys(definition).forEach(function (key) {
  51458. proto[key] = {
  51459. value: definition[key],
  51460. writable: true
  51461. };
  51462. });
  51463. if (systems[name]) {
  51464. throw new Error('The system `' + name + '` has been already registered. ' +
  51465. 'Check that you are not loading two versions of the same system ' +
  51466. 'or two different systems of the same name.');
  51467. }
  51468. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  51469. NewSystem.prototype = Object.create(System.prototype, proto);
  51470. NewSystem.prototype.name = name;
  51471. NewSystem.prototype.constructor = NewSystem;
  51472. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  51473. systems[name] = NewSystem;
  51474. // Initialize systems for existing scenes
  51475. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  51476. };
  51477. },{"../utils/":172,"./component":102,"./schema":110}],113:[function(_dereq_,module,exports){
  51478. _dereq_('./pivot');
  51479. },{"./pivot":114}],114:[function(_dereq_,module,exports){
  51480. var registerComponent = _dereq_('../../core/component').registerComponent;
  51481. var THREE = _dereq_('../../lib/three');
  51482. var originalPosition = new THREE.Vector3();
  51483. var originalRotation = new THREE.Vector3();
  51484. /**
  51485. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  51486. */
  51487. registerComponent('pivot', {
  51488. dependencies: ['position'],
  51489. schema: {type: 'vec3'},
  51490. init: function () {
  51491. var data = this.data;
  51492. var el = this.el;
  51493. var originalParent = el.object3D.parent;
  51494. var originalGroup = el.object3D;
  51495. var outerGroup = new THREE.Group();
  51496. originalPosition.copy(originalGroup.position);
  51497. originalRotation.copy(originalGroup.rotation);
  51498. // Detach current group from parent.
  51499. originalParent.remove(originalGroup);
  51500. outerGroup.add(originalGroup);
  51501. // Set new group as the outer group.
  51502. originalParent.add(outerGroup);
  51503. // Set outer group as new object3D.
  51504. el.object3D = outerGroup;
  51505. // Apply pivot to original group.
  51506. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  51507. // Offset the pivot so that world position not affected.
  51508. // And restore position onto outer group.
  51509. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  51510. data.z + originalPosition.z);
  51511. // Transfer rotation to outer group.
  51512. outerGroup.rotation.copy(originalGroup.rotation);
  51513. originalGroup.rotation.set(0, 0, 0);
  51514. }
  51515. });
  51516. },{"../../core/component":102,"../../lib/three":150}],115:[function(_dereq_,module,exports){
  51517. /**
  51518. * Common mesh defaults, mappings, and transforms.
  51519. */
  51520. var components = _dereq_('../../core/component').components;
  51521. var shaders = _dereq_('../../core/shader').shaders;
  51522. var utils = _dereq_('../../utils/');
  51523. var materialMappings = {};
  51524. Object.keys(components.material.schema).forEach(addMapping);
  51525. Object.keys(shaders.standard.schema).forEach(addMapping);
  51526. function addMapping (prop) {
  51527. // To hyphenated.
  51528. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  51529. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  51530. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  51531. materialMappings[htmlAttrName] = 'material.' + prop;
  51532. }
  51533. module.exports = function getMeshMixin () {
  51534. return {
  51535. defaultComponents: {material: {}},
  51536. mappings: utils.extend({}, materialMappings)
  51537. };
  51538. };
  51539. },{"../../core/component":102,"../../core/shader":111,"../../utils/":172}],116:[function(_dereq_,module,exports){
  51540. _dereq_('./primitives/a-camera');
  51541. _dereq_('./primitives/a-collada-model');
  51542. _dereq_('./primitives/a-cursor');
  51543. _dereq_('./primitives/a-curvedimage');
  51544. _dereq_('./primitives/a-gltf-model');
  51545. _dereq_('./primitives/a-image');
  51546. _dereq_('./primitives/a-light');
  51547. _dereq_('./primitives/a-link');
  51548. _dereq_('./primitives/a-obj-model');
  51549. _dereq_('./primitives/a-sky');
  51550. _dereq_('./primitives/a-sound');
  51551. _dereq_('./primitives/a-text');
  51552. _dereq_('./primitives/a-video');
  51553. _dereq_('./primitives/a-videosphere');
  51554. _dereq_('./primitives/meshPrimitives');
  51555. },{"./primitives/a-camera":118,"./primitives/a-collada-model":119,"./primitives/a-cursor":120,"./primitives/a-curvedimage":121,"./primitives/a-gltf-model":122,"./primitives/a-image":123,"./primitives/a-light":124,"./primitives/a-link":125,"./primitives/a-obj-model":126,"./primitives/a-sky":127,"./primitives/a-sound":128,"./primitives/a-text":129,"./primitives/a-video":130,"./primitives/a-videosphere":131,"./primitives/meshPrimitives":132}],117:[function(_dereq_,module,exports){
  51556. var AEntity = _dereq_('../../core/a-entity');
  51557. var components = _dereq_('../../core/component').components;
  51558. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  51559. var utils = _dereq_('../../utils/');
  51560. var debug = utils.debug;
  51561. var setComponentProperty = utils.entity.setComponentProperty;
  51562. var log = debug('extras:primitives:debug');
  51563. var warn = debug('extras:primitives:warn');
  51564. var primitives = module.exports.primitives = {};
  51565. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  51566. name = name.toLowerCase();
  51567. log('Registering <%s>', name);
  51568. // Deprecation warning for defaultAttributes usage.
  51569. if (definition.defaultAttributes) {
  51570. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  51571. }
  51572. var primitive = registerElement(name, {
  51573. prototype: Object.create(AEntity.prototype, {
  51574. defaultComponentsFromPrimitive: {
  51575. value: definition.defaultComponents || definition.defaultAttributes || {}
  51576. },
  51577. deprecated: {value: definition.deprecated || null},
  51578. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  51579. mappings: {value: definition.mappings || {}},
  51580. createdCallback: {
  51581. value: function () {
  51582. if (definition.deprecated) { console.warn(definition.deprecated); }
  51583. this.resolveMappingCollisions();
  51584. }
  51585. },
  51586. /**
  51587. * If a mapping collides with a registered component name
  51588. * it renames the mapping to componentname-property
  51589. */
  51590. resolveMappingCollisions: {
  51591. value: function () {
  51592. var mappings = this.mappings;
  51593. var self = this;
  51594. Object.keys(mappings).forEach(function resolveCollision (key) {
  51595. var newAttribute;
  51596. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  51597. if (components[key]) {
  51598. newAttribute = mappings[key].replace('.', '-');
  51599. mappings[newAttribute] = mappings[key];
  51600. delete mappings[key];
  51601. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  51602. 'The attribute ' + key + ' has the same name as a registered component and' +
  51603. ' has been renamed to ' + newAttribute);
  51604. }
  51605. });
  51606. }
  51607. },
  51608. getExtraComponents: {
  51609. value: function () {
  51610. var attr;
  51611. var data;
  51612. var i;
  51613. var mapping;
  51614. var mixins;
  51615. var path;
  51616. var self = this;
  51617. // Gather component data from default components.
  51618. data = utils.clone(this.defaultComponentsFromPrimitive);
  51619. // Factor in mixins to overwrite default components.
  51620. mixins = this.getAttribute('mixin');
  51621. if (mixins) {
  51622. mixins = mixins.trim().split(' ');
  51623. mixins.forEach(function applyMixin (mixinId) {
  51624. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  51625. Object.keys(mixinComponents).forEach(function setComponent (name) {
  51626. data[name] = extend(data[name], mixinComponents[name]);
  51627. });
  51628. });
  51629. }
  51630. // Gather component data from mappings.
  51631. for (i = 0; i < this.attributes.length; i++) {
  51632. attr = this.attributes[i];
  51633. mapping = this.mappings[attr.name];
  51634. if (mapping) {
  51635. path = utils.entity.getComponentPropertyPath(mapping);
  51636. if (path.constructor === Array) {
  51637. data[path[0]] = data[path[0]] || {};
  51638. data[path[0]][path[1]] = attr.value.trim();
  51639. } else {
  51640. data[path] = attr.value.trim();
  51641. }
  51642. continue;
  51643. }
  51644. }
  51645. return data;
  51646. /**
  51647. * For the base to be extensible, both objects must be pure JavaScript objects.
  51648. * The function assumes that base is undefined, or null or a pure object.
  51649. */
  51650. function extend (base, extension) {
  51651. if (isUndefined(base)) {
  51652. return copy(extension);
  51653. }
  51654. if (isUndefined(extension)) {
  51655. return copy(base);
  51656. }
  51657. if (isPureObject(base) && isPureObject(extension)) {
  51658. return utils.extendDeep(base, extension);
  51659. }
  51660. return copy(extension);
  51661. }
  51662. function isUndefined (value) {
  51663. return typeof value === 'undefined';
  51664. }
  51665. function copy (value) {
  51666. if (isPureObject(value)) {
  51667. return utils.extendDeep({}, value);
  51668. }
  51669. return value;
  51670. }
  51671. function isPureObject (value) {
  51672. return value !== null && value.constructor === Object;
  51673. }
  51674. }
  51675. },
  51676. /**
  51677. * Sync to attribute to component property whenever mapped attribute changes.
  51678. * If attribute is mapped to a component property, set the component property using
  51679. * the attribute value.
  51680. */
  51681. attributeChangedCallback: {
  51682. value: function (attr, oldVal, value) {
  51683. var componentName = this.mappings[attr];
  51684. if (attr in this.deprecatedMappings) {
  51685. console.warn(this.deprecatedMappings[attr]);
  51686. }
  51687. if (!attr || !componentName) { return; }
  51688. // Set value.
  51689. setComponentProperty(this, componentName, value);
  51690. }
  51691. }
  51692. })
  51693. });
  51694. // Store.
  51695. primitives[name] = primitive;
  51696. return primitive;
  51697. };
  51698. /**
  51699. * Add component mappings using schema.
  51700. */
  51701. function addComponentMapping (componentName, mappings) {
  51702. var schema = components[componentName].schema;
  51703. Object.keys(schema).map(function (prop) {
  51704. // Hyphenate where there is camelCase.
  51705. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  51706. // If there is a mapping collision, prefix with component name and hyphen.
  51707. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  51708. mappings[attrName] = componentName + '.' + prop;
  51709. });
  51710. }
  51711. /**
  51712. * Helper to define a primitive, building mappings using a component schema.
  51713. */
  51714. function definePrimitive (tagName, defaultComponents, mappings) {
  51715. // If no initial mappings provided, start from empty map.
  51716. mappings = mappings || {};
  51717. // From the default components, add mapping automagically.
  51718. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  51719. addComponentMapping(componentName, mappings);
  51720. });
  51721. // Register the primitive.
  51722. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  51723. defaultComponents: defaultComponents,
  51724. mappings: mappings
  51725. }));
  51726. }
  51727. module.exports.definePrimitive = definePrimitive;
  51728. },{"../../core/a-entity":98,"../../core/a-register-element":101,"../../core/component":102,"../../utils/":172}],118:[function(_dereq_,module,exports){
  51729. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51730. registerPrimitive('a-camera', {
  51731. defaultComponents: {
  51732. 'camera': {},
  51733. 'look-controls': {},
  51734. 'wasd-controls': {},
  51735. 'position': {y: 1.6}
  51736. },
  51737. mappings: {
  51738. active: 'camera.active',
  51739. far: 'camera.far',
  51740. fov: 'camera.fov',
  51741. 'look-controls-enabled': 'look-controls.enabled',
  51742. near: 'camera.near',
  51743. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  51744. 'wasd-controls-enabled': 'wasd-controls.enabled',
  51745. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  51746. zoom: 'camera.zoom'
  51747. }
  51748. });
  51749. },{"../primitives":117}],119:[function(_dereq_,module,exports){
  51750. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51751. registerPrimitive('a-collada-model', {
  51752. mappings: {
  51753. src: 'collada-model'
  51754. }
  51755. });
  51756. },{"../primitives":117}],120:[function(_dereq_,module,exports){
  51757. var getMeshMixin = _dereq_('../getMeshMixin');
  51758. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51759. var utils = _dereq_('../../../utils/');
  51760. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  51761. defaultComponents: {
  51762. cursor: {},
  51763. geometry: {
  51764. primitive: 'ring',
  51765. radiusOuter: 0.016,
  51766. radiusInner: 0.01,
  51767. segmentsTheta: 32
  51768. },
  51769. material: {
  51770. color: '#000',
  51771. shader: 'flat',
  51772. opacity: 0.8
  51773. },
  51774. position: {
  51775. x: 0,
  51776. y: 0,
  51777. z: -1
  51778. }
  51779. },
  51780. mappings: {
  51781. far: 'raycaster.far',
  51782. fuse: 'cursor.fuse',
  51783. 'fuse-timeout': 'cursor.fuseTimeout',
  51784. interval: 'raycaster.interval',
  51785. objects: 'raycaster.objects'
  51786. }
  51787. }));
  51788. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],121:[function(_dereq_,module,exports){
  51789. var getMeshMixin = _dereq_('../getMeshMixin');
  51790. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51791. var utils = _dereq_('../../../utils/');
  51792. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  51793. defaultComponents: {
  51794. geometry: {
  51795. height: 1,
  51796. primitive: 'cylinder',
  51797. radius: 2,
  51798. segmentsRadial: 48,
  51799. thetaLength: 270,
  51800. openEnded: true,
  51801. thetaStart: 0
  51802. },
  51803. material: {
  51804. color: '#FFF',
  51805. shader: 'flat',
  51806. side: 'double',
  51807. transparent: true,
  51808. repeat: '-1 1'
  51809. }
  51810. },
  51811. mappings: {
  51812. height: 'geometry.height',
  51813. 'open-ended': 'geometry.openEnded',
  51814. radius: 'geometry.radius',
  51815. segments: 'geometry.segmentsRadial',
  51816. start: 'geometry.thetaStart',
  51817. 'theta-length': 'geometry.thetaLength',
  51818. 'theta-start': 'geometry.thetaStart',
  51819. 'width': 'geometry.thetaLength'
  51820. }
  51821. }));
  51822. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],122:[function(_dereq_,module,exports){
  51823. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51824. registerPrimitive('a-gltf-model', {
  51825. mappings: {
  51826. src: 'gltf-model'
  51827. }
  51828. });
  51829. },{"../primitives":117}],123:[function(_dereq_,module,exports){
  51830. var getMeshMixin = _dereq_('../getMeshMixin');
  51831. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51832. var utils = _dereq_('../../../utils/');
  51833. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  51834. defaultComponents: {
  51835. geometry: {
  51836. primitive: 'plane'
  51837. },
  51838. material: {
  51839. color: '#FFF',
  51840. shader: 'flat',
  51841. side: 'double',
  51842. transparent: true
  51843. }
  51844. },
  51845. mappings: {
  51846. height: 'geometry.height',
  51847. width: 'geometry.width'
  51848. }
  51849. }));
  51850. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],124:[function(_dereq_,module,exports){
  51851. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51852. registerPrimitive('a-light', {
  51853. defaultComponents: {
  51854. light: {}
  51855. },
  51856. mappings: {
  51857. angle: 'light.angle',
  51858. color: 'light.color',
  51859. 'ground-color': 'light.groundColor',
  51860. decay: 'light.decay',
  51861. distance: 'light.distance',
  51862. intensity: 'light.intensity',
  51863. penumbra: 'light.penumbra',
  51864. type: 'light.type',
  51865. target: 'light.target'
  51866. }
  51867. });
  51868. },{"../primitives":117}],125:[function(_dereq_,module,exports){
  51869. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51870. registerPrimitive('a-link', {
  51871. defaultComponents: {},
  51872. mappings: {
  51873. href: 'link.href',
  51874. image: 'link.image',
  51875. title: 'link.title'
  51876. }
  51877. });
  51878. },{"../primitives":117}],126:[function(_dereq_,module,exports){
  51879. var meshMixin = _dereq_('../getMeshMixin')();
  51880. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51881. var utils = _dereq_('../../../utils/');
  51882. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  51883. defaultComponents: {
  51884. 'obj-model': {}
  51885. },
  51886. mappings: {
  51887. src: 'obj-model.obj',
  51888. mtl: 'obj-model.mtl'
  51889. }
  51890. }));
  51891. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],127:[function(_dereq_,module,exports){
  51892. var getMeshMixin = _dereq_('../getMeshMixin');
  51893. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51894. var utils = _dereq_('../../../utils/');
  51895. var meshPrimitives = _dereq_('./meshPrimitives');
  51896. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  51897. defaultComponents: {
  51898. geometry: {
  51899. primitive: 'sphere',
  51900. radius: 5000,
  51901. segmentsWidth: 64,
  51902. segmentsHeight: 32
  51903. },
  51904. material: {
  51905. color: '#FFF',
  51906. side: 'back',
  51907. shader: 'flat',
  51908. npot: true
  51909. },
  51910. scale: '-1 1 1'
  51911. },
  51912. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  51913. }));
  51914. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117,"./meshPrimitives":132}],128:[function(_dereq_,module,exports){
  51915. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51916. registerPrimitive('a-sound', {
  51917. defaultComponents: {
  51918. sound: {}
  51919. },
  51920. mappings: {
  51921. src: 'sound.src',
  51922. on: 'sound.on',
  51923. autoplay: 'sound.autoplay',
  51924. loop: 'sound.loop',
  51925. volume: 'sound.volume'
  51926. }
  51927. });
  51928. },{"../primitives":117}],129:[function(_dereq_,module,exports){
  51929. // <a-text> using `definePrimitive` helper.
  51930. var definePrimitive = _dereq_('../primitives').definePrimitive;
  51931. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  51932. },{"../primitives":117}],130:[function(_dereq_,module,exports){
  51933. var getMeshMixin = _dereq_('../getMeshMixin');
  51934. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51935. var utils = _dereq_('../../../utils/');
  51936. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  51937. defaultComponents: {
  51938. geometry: {
  51939. primitive: 'plane'
  51940. },
  51941. material: {
  51942. color: '#FFF',
  51943. shader: 'flat',
  51944. side: 'double',
  51945. transparent: true
  51946. }
  51947. },
  51948. mappings: {
  51949. height: 'geometry.height',
  51950. width: 'geometry.width'
  51951. }
  51952. }));
  51953. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],131:[function(_dereq_,module,exports){
  51954. var getMeshMixin = _dereq_('../getMeshMixin');
  51955. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51956. var utils = _dereq_('../../../utils/');
  51957. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  51958. defaultComponents: {
  51959. geometry: {
  51960. primitive: 'sphere',
  51961. radius: 5000,
  51962. segmentsWidth: 64,
  51963. segmentsHeight: 32
  51964. },
  51965. material: {
  51966. color: '#FFF',
  51967. shader: 'flat',
  51968. side: 'back',
  51969. npot: true
  51970. },
  51971. scale: '-1 1 1'
  51972. },
  51973. mappings: {
  51974. radius: 'geometry.radius',
  51975. 'segments-height': 'geometry.segmentsHeight',
  51976. 'segments-width': 'geometry.segmentsWidth'
  51977. }
  51978. }));
  51979. },{"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],132:[function(_dereq_,module,exports){
  51980. /**
  51981. * Automated mesh primitive registration.
  51982. */
  51983. var getMeshMixin = _dereq_('../getMeshMixin');
  51984. var geometries = _dereq_('../../../core/geometry').geometries;
  51985. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  51986. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51987. var utils = _dereq_('../../../utils/');
  51988. // For testing.
  51989. var meshPrimitives = module.exports = {};
  51990. // Generate primitive for each geometry type.
  51991. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  51992. var geometry = geometries[geometryName];
  51993. var geometryHyphened = unCamelCase(geometryName);
  51994. // Generate mappings.
  51995. var mappings = {};
  51996. Object.keys(geometry.schema).forEach(function createMapping (property) {
  51997. mappings[unCamelCase(property)] = 'geometry.' + property;
  51998. });
  51999. // Register.
  52000. var tagName = 'a-' + geometryHyphened;
  52001. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  52002. defaultComponents: {geometry: {primitive: geometryName}},
  52003. mappings: mappings
  52004. }));
  52005. meshPrimitives[tagName] = primitive;
  52006. });
  52007. /**
  52008. * camelCase to hyphened-string.
  52009. */
  52010. function unCamelCase (str) {
  52011. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52012. }
  52013. },{"../../../core/geometry":103,"../../../utils/":172,"../getMeshMixin":115,"../primitives":117}],133:[function(_dereq_,module,exports){
  52014. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52015. var THREE = _dereq_('../lib/three');
  52016. registerGeometry('box', {
  52017. schema: {
  52018. depth: {default: 1, min: 0},
  52019. height: {default: 1, min: 0},
  52020. width: {default: 1, min: 0},
  52021. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  52022. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  52023. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  52024. },
  52025. init: function (data) {
  52026. this.geometry = new THREE.BoxGeometry(
  52027. data.width, data.height, data.depth,
  52028. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  52029. }
  52030. });
  52031. },{"../core/geometry":103,"../lib/three":150}],134:[function(_dereq_,module,exports){
  52032. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52033. var THREE = _dereq_('../lib/three');
  52034. var degToRad = THREE.Math.degToRad;
  52035. registerGeometry('circle', {
  52036. schema: {
  52037. radius: {default: 1, min: 0},
  52038. segments: {default: 32, min: 3, type: 'int'},
  52039. thetaLength: {default: 360, min: 0},
  52040. thetaStart: {default: 0}
  52041. },
  52042. init: function (data) {
  52043. this.geometry = new THREE.CircleGeometry(
  52044. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  52045. }
  52046. });
  52047. },{"../core/geometry":103,"../lib/three":150}],135:[function(_dereq_,module,exports){
  52048. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52049. var THREE = _dereq_('../lib/three');
  52050. var degToRad = THREE.Math.degToRad;
  52051. registerGeometry('cone', {
  52052. schema: {
  52053. height: {default: 1, min: 0},
  52054. openEnded: {default: false},
  52055. radiusBottom: {default: 1, min: 0},
  52056. radiusTop: {default: 0.01, min: 0},
  52057. segmentsHeight: {default: 18, min: 1, type: 'int'},
  52058. segmentsRadial: {default: 36, min: 3, type: 'int'},
  52059. thetaLength: {default: 360, min: 0},
  52060. thetaStart: {default: 0}
  52061. },
  52062. init: function (data) {
  52063. this.geometry = new THREE.CylinderGeometry(
  52064. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  52065. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  52066. degToRad(data.thetaLength));
  52067. }
  52068. });
  52069. },{"../core/geometry":103,"../lib/three":150}],136:[function(_dereq_,module,exports){
  52070. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52071. var THREE = _dereq_('../lib/three');
  52072. var degToRad = THREE.Math.degToRad;
  52073. registerGeometry('cylinder', {
  52074. schema: {
  52075. height: {default: 1, min: 0},
  52076. openEnded: {default: false},
  52077. radius: {default: 1, min: 0},
  52078. segmentsHeight: {default: 18, min: 1, type: 'int'},
  52079. segmentsRadial: {default: 36, min: 3, type: 'int'},
  52080. thetaLength: {default: 360, min: 0},
  52081. thetaStart: {default: 0}
  52082. },
  52083. init: function (data) {
  52084. this.geometry = new THREE.CylinderGeometry(
  52085. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  52086. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  52087. }
  52088. });
  52089. },{"../core/geometry":103,"../lib/three":150}],137:[function(_dereq_,module,exports){
  52090. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52091. var THREE = _dereq_('../lib/three');
  52092. registerGeometry('dodecahedron', {
  52093. schema: {
  52094. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52095. radius: {default: 1, min: 0}
  52096. },
  52097. init: function (data) {
  52098. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  52099. }
  52100. });
  52101. },{"../core/geometry":103,"../lib/three":150}],138:[function(_dereq_,module,exports){
  52102. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52103. var THREE = _dereq_('../lib/three');
  52104. registerGeometry('icosahedron', {
  52105. schema: {
  52106. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52107. radius: {default: 1, min: 0}
  52108. },
  52109. init: function (data) {
  52110. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  52111. }
  52112. });
  52113. },{"../core/geometry":103,"../lib/three":150}],139:[function(_dereq_,module,exports){
  52114. _dereq_('./box.js');
  52115. _dereq_('./circle.js');
  52116. _dereq_('./cone.js');
  52117. _dereq_('./cylinder.js');
  52118. _dereq_('./dodecahedron.js');
  52119. _dereq_('./icosahedron.js');
  52120. _dereq_('./octahedron.js');
  52121. _dereq_('./plane.js');
  52122. _dereq_('./ring.js');
  52123. _dereq_('./sphere.js');
  52124. _dereq_('./tetrahedron.js');
  52125. _dereq_('./torus.js');
  52126. _dereq_('./torusKnot.js');
  52127. _dereq_('./triangle.js');
  52128. },{"./box.js":133,"./circle.js":134,"./cone.js":135,"./cylinder.js":136,"./dodecahedron.js":137,"./icosahedron.js":138,"./octahedron.js":140,"./plane.js":141,"./ring.js":142,"./sphere.js":143,"./tetrahedron.js":144,"./torus.js":145,"./torusKnot.js":146,"./triangle.js":147}],140:[function(_dereq_,module,exports){
  52129. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52130. var THREE = _dereq_('../lib/three');
  52131. registerGeometry('octahedron', {
  52132. schema: {
  52133. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52134. radius: {default: 1, min: 0}
  52135. },
  52136. init: function (data) {
  52137. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  52138. }
  52139. });
  52140. },{"../core/geometry":103,"../lib/three":150}],141:[function(_dereq_,module,exports){
  52141. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52142. var THREE = _dereq_('../lib/three');
  52143. registerGeometry('plane', {
  52144. schema: {
  52145. height: {default: 1, min: 0},
  52146. width: {default: 1, min: 0},
  52147. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  52148. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  52149. },
  52150. init: function (data) {
  52151. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  52152. }
  52153. });
  52154. },{"../core/geometry":103,"../lib/three":150}],142:[function(_dereq_,module,exports){
  52155. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52156. var THREE = _dereq_('../lib/three');
  52157. var degToRad = THREE.Math.degToRad;
  52158. registerGeometry('ring', {
  52159. schema: {
  52160. radiusInner: {default: 0.8, min: 0},
  52161. radiusOuter: {default: 1.2, min: 0},
  52162. segmentsPhi: {default: 10, min: 1, type: 'int'},
  52163. segmentsTheta: {default: 32, min: 3, type: 'int'},
  52164. thetaLength: {default: 360, min: 0},
  52165. thetaStart: {default: 0}
  52166. },
  52167. init: function (data) {
  52168. this.geometry = new THREE.RingGeometry(
  52169. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  52170. degToRad(data.thetaStart), degToRad(data.thetaLength));
  52171. }
  52172. });
  52173. },{"../core/geometry":103,"../lib/three":150}],143:[function(_dereq_,module,exports){
  52174. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52175. var THREE = _dereq_('../lib/three');
  52176. var degToRad = THREE.Math.degToRad;
  52177. registerGeometry('sphere', {
  52178. schema: {
  52179. radius: {default: 1, min: 0},
  52180. phiLength: {default: 360},
  52181. phiStart: {default: 0, min: 0},
  52182. thetaLength: {default: 180, min: 0},
  52183. thetaStart: {default: 0},
  52184. segmentsHeight: {default: 18, min: 2, type: 'int'},
  52185. segmentsWidth: {default: 36, min: 3, type: 'int'}
  52186. },
  52187. init: function (data) {
  52188. this.geometry = new THREE.SphereGeometry(
  52189. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  52190. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  52191. }
  52192. });
  52193. },{"../core/geometry":103,"../lib/three":150}],144:[function(_dereq_,module,exports){
  52194. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52195. var THREE = _dereq_('../lib/three');
  52196. registerGeometry('tetrahedron', {
  52197. schema: {
  52198. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52199. radius: {default: 1, min: 0}
  52200. },
  52201. init: function (data) {
  52202. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  52203. }
  52204. });
  52205. },{"../core/geometry":103,"../lib/three":150}],145:[function(_dereq_,module,exports){
  52206. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52207. var THREE = _dereq_('../lib/three');
  52208. var degToRad = THREE.Math.degToRad;
  52209. registerGeometry('torus', {
  52210. schema: {
  52211. arc: {default: 360},
  52212. radius: {default: 1, min: 0},
  52213. radiusTubular: {default: 0.2, min: 0},
  52214. segmentsRadial: {default: 36, min: 2, type: 'int'},
  52215. segmentsTubular: {default: 32, min: 3, type: 'int'}
  52216. },
  52217. init: function (data) {
  52218. this.geometry = new THREE.TorusGeometry(
  52219. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  52220. degToRad(data.arc));
  52221. }
  52222. });
  52223. },{"../core/geometry":103,"../lib/three":150}],146:[function(_dereq_,module,exports){
  52224. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52225. var THREE = _dereq_('../lib/three');
  52226. registerGeometry('torusKnot', {
  52227. schema: {
  52228. p: {default: 2, min: 1},
  52229. q: {default: 3, min: 1},
  52230. radius: {default: 1, min: 0},
  52231. radiusTubular: {default: 0.2, min: 0},
  52232. segmentsRadial: {default: 8, min: 3, type: 'int'},
  52233. segmentsTubular: {default: 100, min: 3, type: 'int'}
  52234. },
  52235. init: function (data) {
  52236. this.geometry = new THREE.TorusKnotGeometry(
  52237. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  52238. data.p, data.q);
  52239. }
  52240. });
  52241. },{"../core/geometry":103,"../lib/three":150}],147:[function(_dereq_,module,exports){
  52242. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52243. var THREE = _dereq_('../lib/three');
  52244. var quaternion = new THREE.Quaternion();
  52245. var rotateVector = new THREE.Vector3(0, 0, 1);
  52246. var uvMinVector = new THREE.Vector2();
  52247. var uvMaxVector = new THREE.Vector2();
  52248. var uvScaleVector = new THREE.Vector2();
  52249. registerGeometry('triangle', {
  52250. schema: {
  52251. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  52252. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  52253. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  52254. },
  52255. init: function (data) {
  52256. var geometry;
  52257. var normal;
  52258. var triangle;
  52259. var uvA;
  52260. var uvB;
  52261. var uvC;
  52262. triangle = new THREE.Triangle();
  52263. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  52264. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  52265. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  52266. normal = triangle.getNormal(new THREE.Vector3());
  52267. // Rotate the 3D triangle to be parallel to XY plane.
  52268. quaternion.setFromUnitVectors(normal, rotateVector);
  52269. uvA = triangle.a.clone().applyQuaternion(quaternion);
  52270. uvB = triangle.b.clone().applyQuaternion(quaternion);
  52271. uvC = triangle.c.clone().applyQuaternion(quaternion);
  52272. // Compute UVs.
  52273. // Normalize x/y values of UV so they are within 0 to 1.
  52274. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  52275. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  52276. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  52277. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  52278. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  52279. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  52280. geometry = this.geometry = new THREE.Geometry();
  52281. geometry.vertices.push(triangle.a);
  52282. geometry.vertices.push(triangle.b);
  52283. geometry.vertices.push(triangle.c);
  52284. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  52285. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  52286. }
  52287. });
  52288. },{"../core/geometry":103,"../lib/three":150}],148:[function(_dereq_,module,exports){
  52289. // Check before the polyfill runs.
  52290. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays || !!window.navigator.getVRDevices;
  52291. // WebVR polyfill
  52292. var WebVRPolyfill = _dereq_('webvr-polyfill');
  52293. window.webvrpolyfill = new WebVRPolyfill({
  52294. BUFFER_SCALE: 1,
  52295. CARDBOARD_UI_DISABLED: true,
  52296. ROTATE_INSTRUCTIONS_DISABLED: true
  52297. });
  52298. var utils = _dereq_('./utils/');
  52299. var debug = utils.debug;
  52300. var error = debug('A-Frame:error');
  52301. var warn = debug('A-Frame:warn');
  52302. if (window.document.currentScript && window.document.currentScript.parentNode !==
  52303. window.document.head && !window.debug) {
  52304. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  52305. 'ensure everything for A-Frame is properly registered before they are used from ' +
  52306. 'HTML.');
  52307. }
  52308. // Error if not using a server.
  52309. if (window.location.protocol === 'file:') {
  52310. error(
  52311. 'This HTML file is currently being served via the file:// protocol. ' +
  52312. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  52313. 'Please use a local or hosted server: ' +
  52314. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  52315. }
  52316. // Polyfill `Promise`.
  52317. window.Promise = window.Promise || _dereq_('promise-polyfill');
  52318. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  52319. // Only for iOS on versions older than 10.
  52320. if (utils.device.isIOSOlderThan10(window.navigator.userAgent)) {
  52321. window.WebVRConfig.BUFFER_SCALE = 1 / window.devicePixelRatio;
  52322. }
  52323. _dereq_('present'); // Polyfill `performance.now()`.
  52324. // CSS.
  52325. if (utils.device.isBrowserEnvironment) {
  52326. _dereq_('./style/aframe.css');
  52327. _dereq_('./style/rStats.css');
  52328. }
  52329. // Required before `AEntity` so that all components are registered.
  52330. var AScene = _dereq_('./core/scene/a-scene').AScene;
  52331. var components = _dereq_('./core/component').components;
  52332. var registerComponent = _dereq_('./core/component').registerComponent;
  52333. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  52334. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  52335. var registerShader = _dereq_('./core/shader').registerShader;
  52336. var registerSystem = _dereq_('./core/system').registerSystem;
  52337. var shaders = _dereq_('./core/shader').shaders;
  52338. var systems = _dereq_('./core/system').systems;
  52339. // Exports THREE to window so three.js can be used without alteration.
  52340. var THREE = window.THREE = _dereq_('./lib/three');
  52341. var pkg = _dereq_('../package');
  52342. _dereq_('./components/index'); // Register standard components.
  52343. _dereq_('./geometries/index'); // Register standard geometries.
  52344. _dereq_('./shaders/index'); // Register standard shaders.
  52345. _dereq_('./systems/index'); // Register standard systems.
  52346. var ANode = _dereq_('./core/a-node');
  52347. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  52348. _dereq_('./core/a-assets');
  52349. _dereq_('./core/a-cubemap');
  52350. _dereq_('./core/a-mixin');
  52351. // Extras.
  52352. _dereq_('./extras/components/');
  52353. _dereq_('./extras/primitives/');
  52354. console.log('A-Frame Version: 0.8.2 (Date 2018-09-05, Commit #27ead35)');
  52355. console.log('three Version:', pkg.dependencies['three']);
  52356. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  52357. module.exports = window.AFRAME = {
  52358. AComponent: _dereq_('./core/component').Component,
  52359. AEntity: AEntity,
  52360. ANode: ANode,
  52361. ANIME: _dereq_('animejs'),
  52362. AScene: AScene,
  52363. components: components,
  52364. geometries: _dereq_('./core/geometry').geometries,
  52365. registerComponent: registerComponent,
  52366. registerElement: _dereq_('./core/a-register-element').registerElement,
  52367. registerGeometry: registerGeometry,
  52368. registerPrimitive: registerPrimitive,
  52369. registerShader: registerShader,
  52370. registerSystem: registerSystem,
  52371. primitives: {
  52372. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  52373. primitives: _dereq_('./extras/primitives/primitives').primitives
  52374. },
  52375. scenes: _dereq_('./core/scene/scenes'),
  52376. schema: _dereq_('./core/schema'),
  52377. shaders: shaders,
  52378. systems: systems,
  52379. THREE: THREE,
  52380. utils: utils,
  52381. version: pkg.version
  52382. };
  52383. },{"../package":51,"./components/index":61,"./core/a-assets":96,"./core/a-cubemap":97,"./core/a-entity":98,"./core/a-mixin":99,"./core/a-node":100,"./core/a-register-element":101,"./core/component":102,"./core/geometry":103,"./core/scene/a-scene":105,"./core/scene/scenes":108,"./core/schema":110,"./core/shader":111,"./core/system":112,"./extras/components/":113,"./extras/primitives/":116,"./extras/primitives/getMeshMixin":115,"./extras/primitives/primitives":117,"./geometries/index":139,"./lib/three":150,"./shaders/index":152,"./style/aframe.css":157,"./style/rStats.css":158,"./systems/index":161,"./utils/":172,"animejs":2,"present":31,"promise-polyfill":33,"webvr-polyfill":46}],149:[function(_dereq_,module,exports){
  52384. window.aframeStats = function (scene) {
  52385. var _rS = null;
  52386. var _scene = scene;
  52387. var _values = {
  52388. te: {
  52389. caption: 'Entities'
  52390. },
  52391. lt: {
  52392. caption: 'Load Time'
  52393. }
  52394. };
  52395. var _groups = [ {
  52396. caption: 'A-Frame',
  52397. values: [ 'te', 'lt' ]
  52398. } ];
  52399. function _update () {
  52400. _rS('te').set(getEntityCount());
  52401. if (window.performance.getEntriesByName) {
  52402. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  52403. }
  52404. }
  52405. function getEntityCount () {
  52406. var elements = _scene.querySelectorAll('*');
  52407. Array.prototype.slice.call(elements).filter(function (el) {
  52408. return el.isEntity;
  52409. });
  52410. return elements.length;
  52411. }
  52412. function _start () {}
  52413. function _end () {}
  52414. function _attach (r) {
  52415. _rS = r;
  52416. }
  52417. return {
  52418. update: _update,
  52419. start: _start,
  52420. end: _end,
  52421. attach: _attach,
  52422. values: _values,
  52423. groups: _groups,
  52424. fractions: []
  52425. };
  52426. };
  52427. if (typeof module === 'object') {
  52428. module.exports = {
  52429. aframeStats: window.aframeStats
  52430. };
  52431. }
  52432. },{}],150:[function(_dereq_,module,exports){
  52433. (function (global){
  52434. var THREE = global.THREE = _dereq_('three');
  52435. // Allow cross-origin images to be loaded.
  52436. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  52437. // Must be on `THREE.TextureLoader`.
  52438. if (THREE.TextureLoader) {
  52439. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  52440. }
  52441. // This is for images loaded from the model loaders.
  52442. if (THREE.ImageLoader) {
  52443. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  52444. }
  52445. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  52446. if (THREE.Cache) {
  52447. THREE.Cache.enabled = true;
  52448. }
  52449. // TODO: Eventually include these only if they are needed by a component.
  52450. _dereq_('three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  52451. _dereq_('three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  52452. _dereq_('three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  52453. _dereq_('three/examples/js/loaders/ColladaLoader'); // THREE.ColladaLoader
  52454. THREE.ColladaLoader.prototype.crossOrigin = 'anonymous';
  52455. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  52456. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  52457. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  52458. module.exports = THREE;
  52459. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  52460. },{"three":40,"three/examples/js/loaders/ColladaLoader":41,"three/examples/js/loaders/GLTFLoader":42,"three/examples/js/loaders/MTLLoader":43,"three/examples/js/loaders/OBJLoader":44}],151:[function(_dereq_,module,exports){
  52461. var registerShader = _dereq_('../core/shader').registerShader;
  52462. var THREE = _dereq_('../lib/three');
  52463. var utils = _dereq_('../utils/');
  52464. /**
  52465. * Flat shader using THREE.MeshBasicMaterial.
  52466. */
  52467. module.exports.Shader = registerShader('flat', {
  52468. schema: {
  52469. color: {type: 'color'},
  52470. fog: {default: true},
  52471. height: {default: 256},
  52472. offset: {type: 'vec2', default: {x: 0, y: 0}},
  52473. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  52474. src: {type: 'map'},
  52475. width: {default: 512},
  52476. wireframe: {default: false},
  52477. wireframeLinewidth: {default: 2}
  52478. },
  52479. /**
  52480. * Initializes the shader.
  52481. * Adds a reference from the scene to this entity as the camera.
  52482. */
  52483. init: function (data) {
  52484. this.textureSrc = null;
  52485. this.material = new THREE.MeshBasicMaterial(getMaterialData(data));
  52486. utils.material.updateMap(this, data);
  52487. },
  52488. update: function (data) {
  52489. this.updateMaterial(data);
  52490. utils.material.updateMap(this, data);
  52491. },
  52492. /**
  52493. * Updating existing material.
  52494. *
  52495. * @param {object} data - Material component data.
  52496. */
  52497. updateMaterial: function (data) {
  52498. var material = this.material;
  52499. data = getMaterialData(data);
  52500. Object.keys(data).forEach(function (key) {
  52501. material[key] = data[key];
  52502. });
  52503. }
  52504. });
  52505. /**
  52506. * Builds and normalize material data, normalizing stuff along the way.
  52507. *
  52508. * @param {object} data - Material data.
  52509. * @returns {object} data - Processed material data.
  52510. */
  52511. function getMaterialData (data) {
  52512. return {
  52513. fog: data.fog,
  52514. color: new THREE.Color(data.color),
  52515. wireframe: data.wireframe,
  52516. wireframeLinewidth: data.wireframeLinewidth
  52517. };
  52518. }
  52519. },{"../core/shader":111,"../lib/three":150,"../utils/":172}],152:[function(_dereq_,module,exports){
  52520. _dereq_('./flat');
  52521. _dereq_('./standard');
  52522. _dereq_('./sdf');
  52523. _dereq_('./msdf');
  52524. _dereq_('./ios10hls');
  52525. },{"./flat":151,"./ios10hls":153,"./msdf":154,"./sdf":155,"./standard":156}],153:[function(_dereq_,module,exports){
  52526. var registerShader = _dereq_('../core/shader').registerShader;
  52527. /**
  52528. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  52529. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  52530. */
  52531. module.exports.Shader = registerShader('ios10hls', {
  52532. schema: {
  52533. src: {type: 'map', is: 'uniform'},
  52534. opacity: {type: 'number', is: 'uniform', default: 1}
  52535. },
  52536. vertexShader: [
  52537. 'varying vec2 vUV;',
  52538. 'void main(void) {',
  52539. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  52540. ' vUV = uv;',
  52541. '}'
  52542. ].join('\n'),
  52543. fragmentShader: [
  52544. 'uniform sampler2D src;',
  52545. 'uniform float opacity;',
  52546. 'varying vec2 vUV;',
  52547. 'void main() {',
  52548. ' vec2 offset = vec2(0, 0);',
  52549. ' vec2 repeat = vec2(1, 1);',
  52550. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  52551. ' gl_FragColor = vec4(color.rgb, opacity);',
  52552. '}'
  52553. ].join('\n')
  52554. });
  52555. },{"../core/shader":111}],154:[function(_dereq_,module,exports){
  52556. var registerShader = _dereq_('../core/shader').registerShader;
  52557. /**
  52558. * Multi-channel signed distance field.
  52559. * Used by text component.
  52560. */
  52561. module.exports.Shader = registerShader('msdf', {
  52562. schema: {
  52563. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  52564. color: {type: 'color', is: 'uniform', default: 'white'},
  52565. map: {type: 'map', is: 'uniform'},
  52566. negate: {type: 'boolean', is: 'uniform', default: true},
  52567. opacity: {type: 'number', is: 'uniform', default: 1.0}
  52568. },
  52569. raw: true,
  52570. vertexShader: [
  52571. 'attribute vec2 uv;',
  52572. 'attribute vec3 position;',
  52573. 'uniform mat4 projectionMatrix;',
  52574. 'uniform mat4 modelViewMatrix;',
  52575. 'varying vec2 vUV;',
  52576. 'void main(void) {',
  52577. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  52578. ' vUV = uv;',
  52579. '}'
  52580. ].join('\n'),
  52581. fragmentShader: [
  52582. '#ifdef GL_OES_standard_derivatives',
  52583. '#extension GL_OES_standard_derivatives: enable',
  52584. '#endif',
  52585. 'precision highp float;',
  52586. // FIXME: Experimentally determined constants.
  52587. '#define BIG_ENOUGH 0.001',
  52588. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  52589. '#define ALL_SMOOTH 0.4',
  52590. '#define ALL_ROUGH 0.02',
  52591. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  52592. 'uniform sampler2D map;',
  52593. 'uniform vec3 color;',
  52594. 'uniform float opacity;',
  52595. 'uniform float alphaTest;',
  52596. 'uniform bool negate;',
  52597. 'varying vec2 vUV;',
  52598. 'float median(float r, float g, float b) {',
  52599. ' return max(min(r, g), min(max(r, g), b));',
  52600. '}',
  52601. 'void main() {',
  52602. ' vec3 sample = texture2D(map, vUV).rgb;',
  52603. ' if (negate) {',
  52604. ' sample = 1.0 - sample;',
  52605. ' }',
  52606. ' float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
  52607. ' float alpha = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0);',
  52608. ' float dscale = 0.353505;',
  52609. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  52610. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  52611. // When texel is too small, blend raw alpha value rather than supersampling.
  52612. // FIXME: Experimentally determined constant.
  52613. ' if (isBigEnough > BIG_ENOUGH) {',
  52614. ' float ratio = BIG_ENOUGH / isBigEnough;',
  52615. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  52616. ' }',
  52617. // When texel is big enough, do standard alpha test.
  52618. // FIXME: Experimentally determined constant.
  52619. // Looks much better if we *don't* do this, but do we get Z fighting?
  52620. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  52621. // Else, do modified alpha test.
  52622. // FIXME: Experimentally determined constant.
  52623. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  52624. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  52625. '}'
  52626. ].join('\n')
  52627. });
  52628. },{"../core/shader":111}],155:[function(_dereq_,module,exports){
  52629. var registerShader = _dereq_('../core/shader').registerShader;
  52630. /**
  52631. * Signed distance field.
  52632. * Used by text component.
  52633. */
  52634. module.exports.Shader = registerShader('sdf', {
  52635. schema: {
  52636. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  52637. color: {type: 'color', is: 'uniform', default: 'white'},
  52638. map: {type: 'map', is: 'uniform'},
  52639. opacity: {type: 'number', is: 'uniform', default: 1.0}
  52640. },
  52641. raw: true,
  52642. vertexShader: [
  52643. 'attribute vec2 uv;',
  52644. 'attribute vec3 position;',
  52645. 'uniform mat4 projectionMatrix;',
  52646. 'uniform mat4 modelViewMatrix;',
  52647. 'varying vec2 vUV;',
  52648. 'void main(void) {',
  52649. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  52650. ' vUV = uv;',
  52651. '}'
  52652. ].join('\n'),
  52653. fragmentShader: [
  52654. '#ifdef GL_OES_standard_derivatives',
  52655. '#extension GL_OES_standard_derivatives: enable',
  52656. '#endif',
  52657. 'precision highp float;',
  52658. // FIXME: experimentally determined constants
  52659. '#define BIG_ENOUGH 0.001',
  52660. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  52661. '#define ALL_SMOOTH 0.4',
  52662. '#define ALL_ROUGH 0.02',
  52663. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  52664. 'uniform sampler2D map;',
  52665. 'uniform vec3 color;',
  52666. 'uniform float opacity;',
  52667. 'uniform float alphaTest;',
  52668. 'varying vec2 vUV;',
  52669. '#ifdef GL_OES_standard_derivatives',
  52670. 'float contour(float width, float value) {',
  52671. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  52672. '}',
  52673. '#else',
  52674. 'float aastep(float value, float afwidth) {',
  52675. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  52676. '}',
  52677. '#endif',
  52678. 'void main() {',
  52679. '#ifdef GL_OES_standard_derivatives',
  52680. // when we have derivatives and can get texel size etc., that allows supersampling etc.
  52681. ' vec2 uv = vUV;',
  52682. ' vec4 texColor = texture2D(map, uv);',
  52683. ' float dist = texColor.a;',
  52684. ' float width = fwidth(dist);',
  52685. ' float alpha = contour(dist, width);',
  52686. ' float dscale = 0.353505;',
  52687. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  52688. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  52689. // when texel is too small, blend raw alpha value rather than supersampling etc.
  52690. // FIXME: experimentally determined constant
  52691. ' if (isBigEnough > BIG_ENOUGH) {',
  52692. ' float ratio = BIG_ENOUGH / isBigEnough;',
  52693. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  52694. ' }',
  52695. // otherwise do weighted supersampling
  52696. // FIXME: why this weighting?
  52697. ' else if (isBigEnough <= BIG_ENOUGH) {',
  52698. ' vec4 box = vec4 (uv - duv, uv + duv);',
  52699. ' alpha = (alpha + 0.5 * (',
  52700. ' contour(texture2D(map, box.xy).a, width)',
  52701. ' + contour(texture2D(map, box.zw).a, width)',
  52702. ' + contour(texture2D(map, box.xw).a, width)',
  52703. ' + contour(texture2D(map, box.zy).a, width)',
  52704. ' )) / 3.0;',
  52705. ' }',
  52706. // when texel is big enough, do standard alpha test
  52707. // FIXME: experimentally determined constant
  52708. // looks much better if we DON'T do this, but do we get Z fighting etc.?
  52709. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  52710. // else do modified alpha test
  52711. // FIXME: experimentally determined constant
  52712. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  52713. '#else',
  52714. ' vec4 texColor = texture2D(map, vUV);',
  52715. ' float value = texColor.a;',
  52716. // when we don't have derivatives, use approximations
  52717. // FIXME: if we understood font pixel dimensions, this could probably be improved
  52718. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  52719. ' float alpha = aastep(value, afwidth);',
  52720. // use gl_FragCoord.w to guess when we should blend
  52721. // FIXME: if we understood font pixel dimensions, this could probably be improved
  52722. ' 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);',
  52723. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  52724. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  52725. ' if (ratio < 1.0)',
  52726. ' if (alpha <= DISCARD_ALPHA) { discard; return; }',
  52727. '#endif',
  52728. ' gl_FragColor = vec4(color, opacity * alpha);',
  52729. '}'
  52730. ].join('\n')
  52731. });
  52732. },{"../core/shader":111}],156:[function(_dereq_,module,exports){
  52733. var registerShader = _dereq_('../core/shader').registerShader;
  52734. var THREE = _dereq_('../lib/three');
  52735. var utils = _dereq_('../utils/');
  52736. var CubeLoader = new THREE.CubeTextureLoader();
  52737. var texturePromises = {};
  52738. /**
  52739. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  52740. */
  52741. module.exports.Shader = registerShader('standard', {
  52742. schema: {
  52743. ambientOcclusionMap: {type: 'map'},
  52744. ambientOcclusionMapIntensity: {default: 1},
  52745. ambientOcclusionTextureOffset: {type: 'vec2'},
  52746. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52747. color: {type: 'color'},
  52748. displacementMap: {type: 'map'},
  52749. displacementScale: {default: 1},
  52750. displacementBias: {default: 0.5},
  52751. displacementTextureOffset: {type: 'vec2'},
  52752. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52753. emissive: {type: 'color', default: '#000'},
  52754. emissiveIntensity: {default: 1},
  52755. envMap: {default: ''},
  52756. fog: {default: true},
  52757. height: {default: 256},
  52758. metalness: {default: 0.0, min: 0.0, max: 1.0},
  52759. metalnessMap: {type: 'map'},
  52760. metalnessTextureOffset: {type: 'vec2'},
  52761. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52762. normalMap: {type: 'map'},
  52763. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  52764. normalTextureOffset: {type: 'vec2'},
  52765. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52766. offset: {type: 'vec2', default: {x: 0, y: 0}},
  52767. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  52768. roughness: {default: 0.5, min: 0.0, max: 1.0},
  52769. roughnessMap: {type: 'map'},
  52770. roughnessTextureOffset: {type: 'vec2'},
  52771. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52772. sphericalEnvMap: {type: 'map'},
  52773. src: {type: 'map'},
  52774. width: {default: 512},
  52775. wireframe: {default: false},
  52776. wireframeLinewidth: {default: 2}
  52777. },
  52778. /**
  52779. * Initializes the shader.
  52780. * Adds a reference from the scene to this entity as the camera.
  52781. */
  52782. init: function (data) {
  52783. this.material = new THREE.MeshStandardMaterial(getMaterialData(data));
  52784. utils.material.updateMap(this, data);
  52785. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  52786. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  52787. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  52788. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  52789. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  52790. this.updateEnvMap(data);
  52791. },
  52792. update: function (data) {
  52793. this.updateMaterial(data);
  52794. utils.material.updateMap(this, data);
  52795. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  52796. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  52797. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  52798. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  52799. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  52800. this.updateEnvMap(data);
  52801. },
  52802. /**
  52803. * Updating existing material.
  52804. *
  52805. * @param {object} data - Material component data.
  52806. * @returns {object} Material.
  52807. */
  52808. updateMaterial: function (data) {
  52809. var material = this.material;
  52810. data = getMaterialData(data);
  52811. Object.keys(data).forEach(function (key) {
  52812. material[key] = data[key];
  52813. });
  52814. },
  52815. /**
  52816. * Handle environment cubemap. Textures are cached in texturePromises.
  52817. */
  52818. updateEnvMap: function (data) {
  52819. var self = this;
  52820. var material = this.material;
  52821. var envMap = data.envMap;
  52822. var sphericalEnvMap = data.sphericalEnvMap;
  52823. // No envMap defined or already loading.
  52824. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  52825. material.envMap = null;
  52826. material.needsUpdate = true;
  52827. return;
  52828. }
  52829. this.isLoadingEnvMap = true;
  52830. // if a spherical env map is defined then use it.
  52831. if (sphericalEnvMap) {
  52832. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  52833. self.isLoadingEnvMap = false;
  52834. texture.mapping = THREE.SphericalReflectionMapping;
  52835. material.envMap = texture;
  52836. utils.material.handleTextureEvents(self.el, texture);
  52837. material.needsUpdate = true;
  52838. });
  52839. return;
  52840. }
  52841. // Another material is already loading this texture. Wait on promise.
  52842. if (texturePromises[envMap]) {
  52843. texturePromises[envMap].then(function (cube) {
  52844. self.isLoadingEnvMap = false;
  52845. material.envMap = cube;
  52846. utils.material.handleTextureEvents(self.el, cube);
  52847. material.needsUpdate = true;
  52848. });
  52849. return;
  52850. }
  52851. // Material is first to load this texture. Load and resolve texture.
  52852. texturePromises[envMap] = new Promise(function (resolve) {
  52853. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  52854. CubeLoader.load(urls, function (cube) {
  52855. // Texture loaded.
  52856. self.isLoadingEnvMap = false;
  52857. material.envMap = cube;
  52858. utils.material.handleTextureEvents(self.el, cube);
  52859. resolve(cube);
  52860. });
  52861. });
  52862. });
  52863. }
  52864. });
  52865. /**
  52866. * Builds and normalize material data, normalizing stuff along the way.
  52867. *
  52868. * @param {object} data - Material data.
  52869. * @returns {object} data - Processed material data.
  52870. */
  52871. function getMaterialData (data) {
  52872. var newData = {
  52873. color: new THREE.Color(data.color),
  52874. emissive: new THREE.Color(data.emissive),
  52875. emissiveIntensity: data.emissiveIntensity,
  52876. fog: data.fog,
  52877. metalness: data.metalness,
  52878. roughness: data.roughness,
  52879. wireframe: data.wireframe,
  52880. wireframeLinewidth: data.wireframeLinewidth
  52881. };
  52882. if (data.normalMap) { newData.normalScale = data.normalScale; }
  52883. if (data.ambientOcclusionMap) { newData.aoMapIntensity = data.ambientOcclusionMapIntensity; }
  52884. if (data.displacementMap) {
  52885. newData.displacementScale = data.displacementScale;
  52886. newData.displacementBias = data.displacementBias;
  52887. }
  52888. return newData;
  52889. }
  52890. },{"../core/shader":111,"../lib/three":150,"../utils/":172}],157:[function(_dereq_,module,exports){
  52891. var css = ".a-html{bottom:0;left:0;position:fixed;right:0;top:0}.a-body{height:100%;margin:0;overflow:hidden;padding:0;width:100%}:-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}.a-canvas.a-grab-cursor:active,.a-grabbing{cursor:grabbing;cursor:-moz-grabbing;cursor:-webkit-grabbing}a-scene.fullscreen .a-canvas{width:100%!important;height:100%!important;top:0!important;left:0!important;right:0!important;bottom:0!important;position:fixed!important}.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.embedded{right:5px;bottom:5px}.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}"; (_dereq_("browserify-css").createStyle(css, { "href": "src/style/aframe.css"})); module.exports = css;
  52892. },{"browserify-css":5}],158:[function(_dereq_,module,exports){
  52893. 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;
  52894. },{"browserify-css":5}],159:[function(_dereq_,module,exports){
  52895. var constants = _dereq_('../constants/');
  52896. var registerSystem = _dereq_('../core/system').registerSystem;
  52897. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  52898. /**
  52899. * Camera system. Manages which camera is active among multiple cameras in scene.
  52900. *
  52901. * @member {object} activeCameraEl - Active camera entity.
  52902. */
  52903. module.exports.System = registerSystem('camera', {
  52904. init: function () {
  52905. this.activeCameraEl = null;
  52906. this.render = this.render.bind(this);
  52907. this.unwrapRender = this.unwrapRender.bind(this);
  52908. this.wrapRender = this.wrapRender.bind(this);
  52909. this.initialCameraFound = false;
  52910. this.numUserCameras = 0;
  52911. this.numUserCamerasChecked = 0;
  52912. this.setupInitialCamera();
  52913. },
  52914. /**
  52915. * Setup initial camera, either searching for camera or
  52916. * creating a default camera if user has not added one during the initial scene traversal.
  52917. * We want sceneEl.camera to be ready, set, and initialized before the rest of the scene
  52918. * loads.
  52919. *
  52920. * Default camera offset height is at average eye level (~1.6m).
  52921. */
  52922. setupInitialCamera: function () {
  52923. var cameraEls;
  52924. var i;
  52925. var sceneEl = this.sceneEl;
  52926. var self = this;
  52927. // Camera already defined or the one defined it is an spectator one.
  52928. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  52929. sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el});
  52930. return;
  52931. }
  52932. // Search for initial user-defined camera.
  52933. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]');
  52934. // No user cameras, create default one.
  52935. if (!cameraEls.length) {
  52936. this.createDefaultCamera();
  52937. return;
  52938. }
  52939. this.numUserCameras = cameraEls.length;
  52940. for (i = 0; i < cameraEls.length; i++) {
  52941. cameraEls[i].addEventListener('object3dset', function (evt) {
  52942. if (evt.detail.type !== 'camera') { return; }
  52943. self.checkUserCamera(this);
  52944. });
  52945. // Load camera and wait for camera to initialize.
  52946. if (cameraEls[i].isNode) {
  52947. cameraEls[i].load();
  52948. } else {
  52949. cameraEls[i].addEventListener('nodeready', function () {
  52950. this.load();
  52951. });
  52952. }
  52953. }
  52954. },
  52955. /**
  52956. * Check if a user-defined camera entity is appropriate to be initial camera.
  52957. * (active + non-spectator).
  52958. *
  52959. * Keep track of the number of cameras we checked and whether we found one.
  52960. */
  52961. checkUserCamera: function (cameraEl) {
  52962. var cameraData;
  52963. var sceneEl = this.el.sceneEl;
  52964. this.numUserCamerasChecked++;
  52965. // Already found one.
  52966. if (this.initialCameraFound) { return; }
  52967. // Check if camera is appropriate for being the initial camera.
  52968. cameraData = cameraEl.getAttribute('camera');
  52969. if (!cameraData.active || cameraData.spectator) {
  52970. // No user cameras eligible, create default camera.
  52971. if (this.numUserCamerasChecked === this.numUserCameras) {
  52972. this.createDefaultCamera();
  52973. }
  52974. return;
  52975. }
  52976. this.initialCameraFound = true;
  52977. sceneEl.camera = cameraEl.getObject3D('camera');
  52978. sceneEl.emit('cameraready', {cameraEl: cameraEl});
  52979. },
  52980. createDefaultCamera: function () {
  52981. var defaultCameraEl;
  52982. var sceneEl = this.sceneEl;
  52983. // Set up default camera.
  52984. defaultCameraEl = document.createElement('a-entity');
  52985. defaultCameraEl.setAttribute('camera', {active: true});
  52986. defaultCameraEl.setAttribute('wasd-controls', '');
  52987. defaultCameraEl.setAttribute('look-controls', '');
  52988. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  52989. defaultCameraEl.object3D.position.set(0, constants.DEFAULT_CAMERA_HEIGHT, 0);
  52990. defaultCameraEl.addEventListener('object3dset', function (evt) {
  52991. if (evt.detail.type !== 'camera') { return; }
  52992. sceneEl.camera = evt.detail.object;
  52993. sceneEl.emit('cameraready', {cameraEl: defaultCameraEl});
  52994. });
  52995. sceneEl.appendChild(defaultCameraEl);
  52996. defaultCameraEl.load();
  52997. },
  52998. /**
  52999. * Set a different active camera.
  53000. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  53001. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  53002. * the new camera.
  53003. */
  53004. disableActiveCamera: function () {
  53005. var cameraEls;
  53006. var newActiveCameraEl;
  53007. cameraEls = this.sceneEl.querySelectorAll('[camera]');
  53008. newActiveCameraEl = cameraEls[cameraEls.length - 1];
  53009. newActiveCameraEl.setAttribute('camera', 'active', true);
  53010. },
  53011. /**
  53012. * Set active camera to be used by renderer.
  53013. * Removes the default camera (if present).
  53014. * Disables all other cameras in the scene.
  53015. *
  53016. * @param {Element} newCameraEl - Entity with camera component.
  53017. */
  53018. setActiveCamera: function (newCameraEl) {
  53019. var cameraEl;
  53020. var cameraEls;
  53021. var i;
  53022. var newCamera;
  53023. var previousCamera = this.activeCameraEl;
  53024. var sceneEl = this.sceneEl;
  53025. // Same camera.
  53026. newCamera = newCameraEl.getObject3D('camera');
  53027. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  53028. // Grab the default camera.
  53029. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  53030. var defaultCameraEl = defaultCameraWrapper &&
  53031. defaultCameraWrapper.querySelector('[camera]');
  53032. // Remove default camera if new camera is not the default camera.
  53033. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  53034. // Make new camera active.
  53035. this.activeCameraEl = newCameraEl;
  53036. this.activeCameraEl.play();
  53037. sceneEl.camera = newCamera;
  53038. // Disable current camera
  53039. if (previousCamera) {
  53040. previousCamera.setAttribute('camera', 'active', false);
  53041. }
  53042. // Disable other cameras in the scene
  53043. cameraEls = sceneEl.querySelectorAll('[camera]');
  53044. for (i = 0; i < cameraEls.length; i++) {
  53045. cameraEl = cameraEls[i];
  53046. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  53047. cameraEl.setAttribute('camera', 'active', false);
  53048. cameraEl.pause();
  53049. }
  53050. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  53051. },
  53052. /**
  53053. * Set spectator camera to render the scene on a 2D display.
  53054. *
  53055. * @param {Element} newCameraEl - Entity with camera component.
  53056. */
  53057. setSpectatorCamera: function (newCameraEl) {
  53058. var newCamera;
  53059. var previousCamera = this.spectatorCameraEl;
  53060. var sceneEl = this.sceneEl;
  53061. var spectatorCameraEl;
  53062. // Same camera.
  53063. newCamera = newCameraEl.getObject3D('camera');
  53064. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  53065. // Disable current camera
  53066. if (previousCamera) {
  53067. previousCamera.setAttribute('camera', 'spectator', false);
  53068. }
  53069. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  53070. sceneEl.addEventListener('enter-vr', this.wrapRender);
  53071. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  53072. spectatorCameraEl.setAttribute('camera', 'active', false);
  53073. spectatorCameraEl.play();
  53074. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  53075. },
  53076. /**
  53077. * Disables current spectator camera.
  53078. */
  53079. disableSpectatorCamera: function () {
  53080. this.spectatorCameraEl = undefined;
  53081. },
  53082. /**
  53083. * Wrap the render method of the renderer to render
  53084. * the spectator camera after vrDisplay.submitFrame.
  53085. */
  53086. wrapRender: function () {
  53087. if (!this.spectatorCameraEl) { return; }
  53088. this.originalRender = this.sceneEl.renderer.render;
  53089. this.sceneEl.renderer.render = this.render;
  53090. },
  53091. unwrapRender: function () {
  53092. if (!this.originalRender) { return; }
  53093. this.sceneEl.renderer.render = this.originalRender;
  53094. this.originalRender = undefined;
  53095. },
  53096. render: function (scene, camera, renderTarget) {
  53097. var isVREnabled;
  53098. var sceneEl = this.sceneEl;
  53099. var spectatorCamera;
  53100. isVREnabled = sceneEl.renderer.vr.enabled;
  53101. this.originalRender.call(sceneEl.renderer, scene, camera, renderTarget);
  53102. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  53103. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  53104. sceneEl.renderer.vr.enabled = false;
  53105. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  53106. sceneEl.renderer.vr.enabled = isVREnabled;
  53107. }
  53108. });
  53109. /**
  53110. * Remove injected default camera from scene, if present.
  53111. *
  53112. * @param {Element} sceneEl
  53113. */
  53114. function removeDefaultCamera (sceneEl) {
  53115. var defaultCamera;
  53116. var camera = sceneEl.camera;
  53117. if (!camera) { return; }
  53118. // Remove default camera if present.
  53119. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  53120. if (!defaultCamera) { return; }
  53121. sceneEl.removeChild(defaultCamera);
  53122. }
  53123. },{"../constants/":94,"../core/system":112}],160:[function(_dereq_,module,exports){
  53124. var geometries = _dereq_('../core/geometry').geometries;
  53125. var registerSystem = _dereq_('../core/system').registerSystem;
  53126. var THREE = _dereq_('../lib/three');
  53127. /**
  53128. * System for geometry component.
  53129. * Handle geometry caching.
  53130. *
  53131. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  53132. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  53133. * know whether to dispose on removal.
  53134. */
  53135. module.exports.System = registerSystem('geometry', {
  53136. init: function () {
  53137. this.cache = {};
  53138. this.cacheCount = {};
  53139. },
  53140. /**
  53141. * Reset cache. Mainly for testing.
  53142. */
  53143. clearCache: function () {
  53144. this.cache = {};
  53145. this.cacheCount = {};
  53146. },
  53147. /**
  53148. * Attempt to retrieve from cache.
  53149. *
  53150. * @returns {Object|null} A geometry if it exists, else null.
  53151. */
  53152. getOrCreateGeometry: function (data) {
  53153. var cache = this.cache;
  53154. var cachedGeometry;
  53155. var hash;
  53156. // Skip all caching logic.
  53157. if (data.skipCache) { return createGeometry(data); }
  53158. // Try to retrieve from cache first.
  53159. hash = this.hash(data);
  53160. cachedGeometry = cache[hash];
  53161. incrementCacheCount(this.cacheCount, hash);
  53162. if (cachedGeometry) { return cachedGeometry; }
  53163. // Create geometry.
  53164. cachedGeometry = createGeometry(data);
  53165. // Cache and return geometry.
  53166. cache[hash] = cachedGeometry;
  53167. return cachedGeometry;
  53168. },
  53169. /**
  53170. * Let system know that an entity is no longer using a geometry.
  53171. */
  53172. unuseGeometry: function (data) {
  53173. var cache = this.cache;
  53174. var cacheCount = this.cacheCount;
  53175. var geometry;
  53176. var hash;
  53177. if (data.skipCache) { return; }
  53178. hash = this.hash(data);
  53179. if (!cache[hash]) { return; }
  53180. decrementCacheCount(cacheCount, hash);
  53181. // Another entity is still using this geometry. No need to do anything.
  53182. if (cacheCount[hash] > 0) { return; }
  53183. // No more entities are using this geometry. Dispose.
  53184. geometry = cache[hash];
  53185. geometry.dispose();
  53186. delete cache[hash];
  53187. delete cacheCount[hash];
  53188. },
  53189. /**
  53190. * Use JSON.stringify to turn component data into hash.
  53191. * Should be deterministic within a single browser engine.
  53192. * If not, then look into json-stable-stringify.
  53193. */
  53194. hash: function (data) {
  53195. return JSON.stringify(data);
  53196. }
  53197. });
  53198. /**
  53199. * Create geometry using component data.
  53200. *
  53201. * @param {object} data - Component data.
  53202. * @returns {object} Geometry.
  53203. */
  53204. function createGeometry (data) {
  53205. var geometryType = data.primitive;
  53206. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  53207. var geometryInstance = new GeometryClass();
  53208. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  53209. geometryInstance.init(data);
  53210. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  53211. }
  53212. /**
  53213. * Decreate count of entity using a geometry.
  53214. */
  53215. function decrementCacheCount (cacheCount, hash) {
  53216. cacheCount[hash]--;
  53217. }
  53218. /**
  53219. * Increase count of entity using a geometry.
  53220. */
  53221. function incrementCacheCount (cacheCount, hash) {
  53222. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  53223. }
  53224. /**
  53225. * Transform geometry to BufferGeometry if `doBuffer`.
  53226. *
  53227. * @param {object} geometry
  53228. * @param {boolean} doBuffer
  53229. * @returns {object} Geometry.
  53230. */
  53231. function toBufferGeometry (geometry, doBuffer) {
  53232. var bufferGeometry;
  53233. if (!doBuffer) { return geometry; }
  53234. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  53235. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  53236. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  53237. return bufferGeometry;
  53238. }
  53239. },{"../core/geometry":103,"../core/system":112,"../lib/three":150}],161:[function(_dereq_,module,exports){
  53240. _dereq_('./camera');
  53241. _dereq_('./geometry');
  53242. _dereq_('./light');
  53243. _dereq_('./material');
  53244. _dereq_('./shadow');
  53245. _dereq_('./tracked-controls');
  53246. },{"./camera":159,"./geometry":160,"./light":162,"./material":163,"./shadow":164,"./tracked-controls":165}],162:[function(_dereq_,module,exports){
  53247. var registerSystem = _dereq_('../core/system').registerSystem;
  53248. var bind = _dereq_('../utils/bind');
  53249. var constants = _dereq_('../constants/');
  53250. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  53251. /**
  53252. * Light system.
  53253. *
  53254. * Prescribes default lighting if not specified (one ambient, one directional).
  53255. * Removes default lighting from the scene when a new light is added.
  53256. *
  53257. * @param {bool} defaultLights - Whether default lighting are defined.
  53258. * @param {bool} userDefinedLights - Whether user lighting is defined.
  53259. */
  53260. module.exports.System = registerSystem('light', {
  53261. schema: {
  53262. defaultLightsEnabled: {default: true}
  53263. },
  53264. init: function () {
  53265. this.defaultLights = false;
  53266. this.userDefinedLights = false;
  53267. // Wait for all entities to fully load before checking for existence of lights.
  53268. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  53269. // will do so asynchronously.
  53270. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  53271. },
  53272. /**
  53273. * Notify scene that light has been added and to remove the default.
  53274. *
  53275. * @param {object} el - element holding the light component.
  53276. */
  53277. registerLight: function (el) {
  53278. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  53279. // User added a light, remove default lights through DOM.
  53280. this.removeDefaultLights();
  53281. this.userDefinedLights = true;
  53282. }
  53283. },
  53284. removeDefaultLights: function () {
  53285. var defaultLights;
  53286. var sceneEl = this.sceneEl;
  53287. if (!this.defaultLights) { return; }
  53288. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  53289. for (var i = 0; i < defaultLights.length; i++) {
  53290. sceneEl.removeChild(defaultLights[i]);
  53291. }
  53292. this.defaultLights = false;
  53293. },
  53294. /**
  53295. * Prescibe default lights to the scene.
  53296. * Does so by injecting markup such that this state is not invisible.
  53297. * These lights are removed if the user adds any lights.
  53298. */
  53299. setupDefaultLights: function () {
  53300. var sceneEl = this.sceneEl;
  53301. var ambientLight;
  53302. var directionalLight;
  53303. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  53304. return;
  53305. }
  53306. ambientLight = document.createElement('a-entity');
  53307. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  53308. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  53309. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  53310. sceneEl.appendChild(ambientLight);
  53311. directionalLight = document.createElement('a-entity');
  53312. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  53313. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  53314. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  53315. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  53316. sceneEl.appendChild(directionalLight);
  53317. this.defaultLights = true;
  53318. }
  53319. });
  53320. },{"../constants/":94,"../core/system":112,"../utils/bind":166}],163:[function(_dereq_,module,exports){
  53321. var registerSystem = _dereq_('../core/system').registerSystem;
  53322. var THREE = _dereq_('../lib/three');
  53323. var utils = _dereq_('../utils/');
  53324. var isHLS = _dereq_('../utils/material').isHLS;
  53325. var bind = utils.bind;
  53326. var debug = utils.debug;
  53327. var error = debug('components:texture:error');
  53328. var TextureLoader = new THREE.TextureLoader();
  53329. var warn = debug('components:texture:warn');
  53330. TextureLoader.setCrossOrigin('anonymous');
  53331. /**
  53332. * System for material component.
  53333. * Handle material registration, updates (for fog), and texture caching.
  53334. *
  53335. * @member {object} materials - Registered materials.
  53336. * @member {object} textureCounts - Number of times each texture is used. Tracked
  53337. * separately from textureCache, because the cache (1) is populated in
  53338. * multiple places, and (2) may be cleared at any time.
  53339. * @member {object} textureCache - Texture cache for:
  53340. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  53341. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  53342. */
  53343. module.exports.System = registerSystem('material', {
  53344. init: function () {
  53345. this.materials = {};
  53346. this.textureCounts = {};
  53347. this.textureCache = {};
  53348. this.sceneEl.addEventListener(
  53349. 'materialtextureloaded',
  53350. bind(this.onMaterialTextureLoaded, this)
  53351. );
  53352. },
  53353. clearTextureCache: function () {
  53354. this.textureCache = {};
  53355. },
  53356. /**
  53357. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  53358. *
  53359. * @param {string, or element} src - Texture URL or element.
  53360. * @param {string} data - Relevant texture data used for caching.
  53361. * @param {function} cb - Callback to pass texture to.
  53362. */
  53363. loadTexture: function (src, data, cb) {
  53364. var self = this;
  53365. // Canvas.
  53366. if (src.tagName === 'CANVAS') {
  53367. this.loadCanvas(src, data, cb);
  53368. return;
  53369. }
  53370. // Video element.
  53371. if (src.tagName === 'VIDEO') {
  53372. if (!src.src && !src.srcObject && !src.childElementCount) {
  53373. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  53374. }
  53375. this.loadVideo(src, data, cb);
  53376. return;
  53377. }
  53378. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  53379. function loadImageCb (src) { self.loadImage(src, data, cb); }
  53380. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  53381. },
  53382. /**
  53383. * High-level function for loading image textures (THREE.Texture).
  53384. *
  53385. * @param {Element|string} src - Texture source.
  53386. * @param {object} data - Texture data.
  53387. * @param {function} cb - Callback to pass texture to.
  53388. */
  53389. loadImage: function (src, data, handleImageTextureLoaded) {
  53390. var hash = this.hash(data);
  53391. var textureCache = this.textureCache;
  53392. // Texture already being loaded or already loaded. Wait on promise.
  53393. if (textureCache[hash]) {
  53394. textureCache[hash].then(handleImageTextureLoaded);
  53395. return;
  53396. }
  53397. // Texture not yet being loaded. Start loading it.
  53398. textureCache[hash] = loadImageTexture(src, data);
  53399. textureCache[hash].then(handleImageTextureLoaded);
  53400. },
  53401. /**
  53402. * High-level function for loading canvas textures (THREE.Texture).
  53403. *
  53404. * @param {Element|string} src - Texture source.
  53405. * @param {object} data - Texture data.
  53406. * @param {function} cb - Callback to pass texture to.
  53407. */
  53408. loadCanvas: function (src, data, cb) {
  53409. var texture;
  53410. texture = new THREE.CanvasTexture(src);
  53411. setTextureProperties(texture, data);
  53412. cb(texture);
  53413. },
  53414. /**
  53415. * Load video texture (THREE.VideoTexture).
  53416. * Which is just an image texture that RAFs + needsUpdate.
  53417. * Note that creating a video texture is synchronous unlike loading an image texture.
  53418. * Made asynchronous to be consistent with image textures.
  53419. *
  53420. * @param {Element|string} src - Texture source.
  53421. * @param {object} data - Texture data.
  53422. * @param {function} cb - Callback to pass texture to.
  53423. */
  53424. loadVideo: function (src, data, cb) {
  53425. var hash;
  53426. var texture;
  53427. var textureCache = this.textureCache;
  53428. var videoEl;
  53429. var videoTextureResult;
  53430. function handleVideoTextureLoaded (result) {
  53431. result.texture.needsUpdate = true;
  53432. cb(result.texture, result.videoEl);
  53433. }
  53434. // Video element provided.
  53435. if (typeof src !== 'string') {
  53436. // Check cache before creating texture.
  53437. videoEl = src;
  53438. hash = this.hashVideo(data, videoEl);
  53439. if (textureCache[hash]) {
  53440. textureCache[hash].then(handleVideoTextureLoaded);
  53441. return;
  53442. }
  53443. // If not in cache, fix up the attributes then start to create the texture.
  53444. fixVideoAttributes(videoEl);
  53445. }
  53446. // Only URL provided. Use video element to create texture.
  53447. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  53448. // Generated video element already cached. Use that.
  53449. hash = this.hashVideo(data, videoEl);
  53450. if (textureCache[hash]) {
  53451. textureCache[hash].then(handleVideoTextureLoaded);
  53452. return;
  53453. }
  53454. // Create new video texture.
  53455. texture = new THREE.VideoTexture(videoEl);
  53456. texture.minFilter = THREE.LinearFilter;
  53457. setTextureProperties(texture, data);
  53458. // If iOS and video is HLS, do some hacks.
  53459. if (this.sceneEl.isIOS &&
  53460. isHLS(videoEl.src || videoEl.getAttribute('src'),
  53461. videoEl.type || videoEl.getAttribute('type'))) {
  53462. // Actually BGRA. Tell shader to correct later.
  53463. texture.format = THREE.RGBAFormat;
  53464. texture.needsCorrectionBGRA = true;
  53465. // Apparently needed for HLS. Tell shader to correct later.
  53466. texture.flipY = false;
  53467. texture.needsCorrectionFlipY = true;
  53468. }
  53469. // Cache as promise to be consistent with image texture caching.
  53470. videoTextureResult = {texture: texture, videoEl: videoEl};
  53471. textureCache[hash] = Promise.resolve(videoTextureResult);
  53472. handleVideoTextureLoaded(videoTextureResult);
  53473. },
  53474. /**
  53475. * Create a hash of the material properties for texture cache key.
  53476. */
  53477. hash: function (data) {
  53478. if (data.src.tagName) {
  53479. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  53480. data = utils.extendDeep({}, data);
  53481. data.src = data.src.src;
  53482. }
  53483. return JSON.stringify(data);
  53484. },
  53485. hashVideo: function (data, videoEl) {
  53486. return calculateVideoCacheHash(data, videoEl);
  53487. },
  53488. /**
  53489. * Keep track of material in case an update trigger is needed (e.g., fog).
  53490. *
  53491. * @param {object} material
  53492. */
  53493. registerMaterial: function (material) {
  53494. this.materials[material.uuid] = material;
  53495. },
  53496. /**
  53497. * Stop tracking material, and dispose of any textures not being used by
  53498. * another material component.
  53499. *
  53500. * @param {object} material
  53501. */
  53502. unregisterMaterial: function (material) {
  53503. delete this.materials[material.uuid];
  53504. // If any textures on this material are no longer in use, dispose of them.
  53505. var textureCounts = this.textureCounts;
  53506. Object.keys(material)
  53507. .filter(function (propName) {
  53508. return material[propName] && material[propName].isTexture;
  53509. })
  53510. .forEach(function (mapName) {
  53511. textureCounts[material[mapName].uuid]--;
  53512. if (textureCounts[material[mapName].uuid] <= 0) {
  53513. material[mapName].dispose();
  53514. }
  53515. });
  53516. },
  53517. /**
  53518. * Trigger update to all registered materials.
  53519. */
  53520. updateMaterials: function (material) {
  53521. var materials = this.materials;
  53522. Object.keys(materials).forEach(function (uuid) {
  53523. materials[uuid].needsUpdate = true;
  53524. });
  53525. },
  53526. /**
  53527. * Track textures used by material components, so that they can be safely
  53528. * disposed when no longer in use. Textures must be registered here, and not
  53529. * through registerMaterial(), because textures may not be attached at the
  53530. * time the material is registered.
  53531. *
  53532. * @param {Event} e
  53533. */
  53534. onMaterialTextureLoaded: function (e) {
  53535. if (!this.textureCounts[e.detail.texture.uuid]) {
  53536. this.textureCounts[e.detail.texture.uuid] = 0;
  53537. }
  53538. this.textureCounts[e.detail.texture.uuid]++;
  53539. }
  53540. });
  53541. /**
  53542. * Calculates consistent hash from a video element using its attributes.
  53543. * If the video element has an ID, use that.
  53544. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  53545. *
  53546. * @param data {object} - Texture data such as repeat.
  53547. * @param videoEl {Element} - Video element.
  53548. * @returns {string}
  53549. */
  53550. function calculateVideoCacheHash (data, videoEl) {
  53551. var i;
  53552. var id = videoEl.getAttribute('id');
  53553. var hash;
  53554. var videoAttributes;
  53555. if (id) { return id; }
  53556. // Calculate hash using sorted video attributes.
  53557. hash = '';
  53558. videoAttributes = data || {};
  53559. for (i = 0; i < videoEl.attributes.length; i++) {
  53560. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  53561. }
  53562. Object.keys(videoAttributes).sort().forEach(function (name) {
  53563. hash += name + ':' + videoAttributes[name] + ';';
  53564. });
  53565. return hash;
  53566. }
  53567. /**
  53568. * Load image texture.
  53569. *
  53570. * @private
  53571. * @param {string|object} src - An <img> element or url to an image file.
  53572. * @param {object} data - Data to set texture properties like `repeat`.
  53573. * @returns {Promise} Resolves once texture is loaded.
  53574. */
  53575. function loadImageTexture (src, data) {
  53576. return new Promise(doLoadImageTexture);
  53577. function doLoadImageTexture (resolve, reject) {
  53578. var isEl = typeof src !== 'string';
  53579. function resolveTexture (texture) {
  53580. setTextureProperties(texture, data);
  53581. texture.needsUpdate = true;
  53582. resolve(texture);
  53583. }
  53584. // Create texture from an element.
  53585. if (isEl) {
  53586. resolveTexture(new THREE.Texture(src));
  53587. return;
  53588. }
  53589. // Request and load texture from src string. THREE will create underlying element.
  53590. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  53591. TextureLoader.load(
  53592. src,
  53593. resolveTexture,
  53594. function () { /* no-op */ },
  53595. function (xhr) {
  53596. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  53597. xhr.statusText);
  53598. }
  53599. );
  53600. }
  53601. }
  53602. /**
  53603. * Set texture properties such as repeat and offset.
  53604. *
  53605. * @param {object} data - With keys like `repeat`.
  53606. */
  53607. function setTextureProperties (texture, data) {
  53608. var offset = data.offset || {x: 0, y: 0};
  53609. var repeat = data.repeat || {x: 1, y: 1};
  53610. var npot = data.npot || false;
  53611. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  53612. // and filters must not use mipmaps (i.e. Nearest or Linear).
  53613. if (npot) {
  53614. texture.wrapS = THREE.ClampToEdgeWrapping;
  53615. texture.wrapT = THREE.ClampToEdgeWrapping;
  53616. texture.magFilter = THREE.LinearFilter;
  53617. texture.minFilter = THREE.LinearFilter;
  53618. }
  53619. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  53620. if (repeat.x !== 1 || repeat.y !== 1) {
  53621. texture.wrapS = THREE.RepeatWrapping;
  53622. texture.wrapT = THREE.RepeatWrapping;
  53623. texture.repeat.set(repeat.x, repeat.y);
  53624. }
  53625. // Don't bother setting offset if it is 0/0.
  53626. if (offset.x !== 0 || offset.y !== 0) {
  53627. texture.offset.set(offset.x, offset.y);
  53628. }
  53629. }
  53630. /**
  53631. * Create video element to be used as a texture.
  53632. *
  53633. * @param {string} src - Url to a video file.
  53634. * @param {number} width - Width of the video.
  53635. * @param {number} height - Height of the video.
  53636. * @returns {Element} Video element.
  53637. */
  53638. function createVideoEl (src, width, height) {
  53639. var videoEl = document.createElement('video');
  53640. videoEl.width = width;
  53641. videoEl.height = height;
  53642. // Support inline videos for iOS webviews.
  53643. videoEl.setAttribute('playsinline', '');
  53644. videoEl.setAttribute('webkit-playsinline', '');
  53645. videoEl.autoplay = true;
  53646. videoEl.loop = true;
  53647. videoEl.crossOrigin = 'anonymous';
  53648. videoEl.addEventListener('error', function () {
  53649. warn('`$s` is not a valid video', src);
  53650. }, true);
  53651. videoEl.src = src;
  53652. return videoEl;
  53653. }
  53654. /**
  53655. * Fixes a video element's attributes to prevent developers from accidentally passing the
  53656. * wrong attribute values to commonly misused video attributes.
  53657. *
  53658. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  53659. * as booleans. Existence of those attributes will mean truthy.
  53660. *
  53661. * For example, translates <video loop="false"> to <video>.
  53662. *
  53663. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  53664. * @param {Element} videoEl - Video element.
  53665. * @returns {Element} Video element with the correct properties updated.
  53666. */
  53667. function fixVideoAttributes (videoEl) {
  53668. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  53669. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  53670. if (videoEl.getAttribute('loop') === 'false') {
  53671. videoEl.removeAttribute('loop');
  53672. }
  53673. if (videoEl.getAttribute('preload') === 'false') {
  53674. videoEl.preload = 'none';
  53675. }
  53676. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  53677. // To support inline videos in iOS webviews.
  53678. videoEl.setAttribute('playsinline', '');
  53679. videoEl.setAttribute('webkit-playsinline', '');
  53680. return videoEl;
  53681. }
  53682. },{"../core/system":112,"../lib/three":150,"../utils/":172,"../utils/material":173}],164:[function(_dereq_,module,exports){
  53683. var registerSystem = _dereq_('../core/system').registerSystem;
  53684. var THREE = _dereq_('../lib/three');
  53685. var SHADOW_MAP_TYPE_MAP = {
  53686. basic: THREE.BasicShadowMap,
  53687. pcf: THREE.PCFShadowMap,
  53688. pcfsoft: THREE.PCFSoftShadowMap
  53689. };
  53690. /**
  53691. * Shadow system.
  53692. *
  53693. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  53694. * options on the WebGLRenderer for configuring shadow appearance.
  53695. */
  53696. module.exports.System = registerSystem('shadow', {
  53697. schema: {
  53698. autoUpdate: {default: true},
  53699. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  53700. },
  53701. init: function () {
  53702. var sceneEl = this.sceneEl;
  53703. var data = this.data;
  53704. this.shadowMapEnabled = false;
  53705. if (!sceneEl.renderer) { return; } // For tests.
  53706. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  53707. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  53708. this.setShadowMapEnabled(this.shadowMapEnabled);
  53709. },
  53710. /**
  53711. * Enables/disables the renderer shadow map.
  53712. * @param {boolean} enabled
  53713. */
  53714. setShadowMapEnabled: function (enabled) {
  53715. var renderer = this.sceneEl.renderer;
  53716. this.shadowMapEnabled = enabled;
  53717. if (renderer) {
  53718. renderer.shadowMap.enabled = enabled;
  53719. }
  53720. }
  53721. });
  53722. },{"../core/system":112,"../lib/three":150}],165:[function(_dereq_,module,exports){
  53723. var registerSystem = _dereq_('../core/system').registerSystem;
  53724. var utils = _dereq_('../utils');
  53725. /**
  53726. * Tracked controls system.
  53727. * Maintain list with available tracked controllers.
  53728. */
  53729. module.exports.System = registerSystem('tracked-controls', {
  53730. init: function () {
  53731. var self = this;
  53732. this.controllers = [];
  53733. this.updateControllerList(navigator.getGamepads && navigator.getGamepads());
  53734. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  53735. if (!navigator.getVRDisplays) { return; }
  53736. this.sceneEl.addEventListener('enter-vr', function () {
  53737. navigator.getVRDisplays().then(function (displays) {
  53738. if (displays.length) { self.vrDisplay = displays[0]; }
  53739. });
  53740. });
  53741. },
  53742. tick: function () {
  53743. var gamepads;
  53744. // Call getGamepads for Chrome.
  53745. gamepads = navigator.getGamepads && navigator.getGamepads();
  53746. this.throttledUpdateControllerList(gamepads);
  53747. },
  53748. /**
  53749. * Update controller list.
  53750. */
  53751. updateControllerList: function (gamepads) {
  53752. var controllers = this.controllers;
  53753. var gamepad;
  53754. var i;
  53755. var prevCount;
  53756. if (!gamepads) { return; }
  53757. prevCount = controllers.length;
  53758. controllers.length = 0;
  53759. for (i = 0; i < gamepads.length; ++i) {
  53760. gamepad = gamepads[i];
  53761. if (gamepad && gamepad.pose) {
  53762. controllers.push(gamepad);
  53763. }
  53764. }
  53765. if (controllers.length !== prevCount) {
  53766. this.el.emit('controllersupdated', undefined, false);
  53767. }
  53768. }
  53769. });
  53770. },{"../core/system":112,"../utils":172}],166:[function(_dereq_,module,exports){
  53771. /**
  53772. * Faster version of Function.prototype.bind
  53773. * @param {Function} fn - Function to wrap.
  53774. * @param {Object} ctx - What to bind as context.
  53775. * @param {...*} arguments - Arguments to pass through.
  53776. */
  53777. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  53778. return (function (prependedArgs) {
  53779. return function bound () {
  53780. // Concat the bound function arguments with those passed to original bind
  53781. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  53782. return fn.apply(ctx, args);
  53783. };
  53784. })(Array.prototype.slice.call(arguments, 2));
  53785. };
  53786. },{}],167:[function(_dereq_,module,exports){
  53787. /* global THREE */
  53788. var debug = _dereq_('./debug');
  53789. var extend = _dereq_('object-assign');
  53790. var warn = debug('utils:coordinates:warn');
  53791. // Order of coordinates parsed by coordinates.parse.
  53792. var COORDINATE_KEYS = ['x', 'y', 'z', 'w'];
  53793. // Coordinate string regex. Handles negative, positive, and decimals.
  53794. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  53795. module.exports.regex = regex;
  53796. /**
  53797. * Parses coordinates from an "x y z" string.
  53798. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  53799. *
  53800. * @param {string} val - An "x y z" string.
  53801. * @param {string} defaults - fallback value.
  53802. * @returns {object} An object with keys [x, y, z].
  53803. */
  53804. function parse (value, defaultVec) {
  53805. var coordinate;
  53806. var vec;
  53807. if (value && value instanceof Object) {
  53808. var x = value.x === undefined ? defaultVec && defaultVec.x : value.x;
  53809. var y = value.y === undefined ? defaultVec && defaultVec.y : value.y;
  53810. var z = value.z === undefined ? defaultVec && defaultVec.z : value.z;
  53811. var w = value.w === undefined ? defaultVec && defaultVec.w : value.w;
  53812. if (x !== undefined) value.x = parseIfString(x);
  53813. if (y !== undefined) value.y = parseIfString(y);
  53814. if (z !== undefined) value.z = parseIfString(z);
  53815. if (w !== undefined) value.w = parseIfString(w);
  53816. return value;
  53817. }
  53818. if (value === null || value === undefined) {
  53819. return typeof defaultVec === 'object' ? extend({}, defaultVec) : defaultVec;
  53820. }
  53821. coordinate = value.trim().split(/\s+/g);
  53822. vec = {};
  53823. COORDINATE_KEYS.forEach(function (key, i) {
  53824. if (coordinate[i]) {
  53825. vec[key] = parseFloat(coordinate[i], 10);
  53826. } else {
  53827. var defaultVal = defaultVec && defaultVec[key];
  53828. if (defaultVal === undefined) { return; }
  53829. vec[key] = parseIfString(defaultVal);
  53830. }
  53831. });
  53832. return vec;
  53833. }
  53834. module.exports.parse = parse;
  53835. /**
  53836. * Stringify coordinates from an object with keys [x y z].
  53837. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  53838. *
  53839. * @param {object|string} data - An object with keys [x y z].
  53840. * @returns {string} An "x y z" string.
  53841. */
  53842. function stringify (data) {
  53843. if (typeof data !== 'object') { return data; }
  53844. return [data.x, data.y, data.z, data.w].join(' ').trim();
  53845. }
  53846. module.exports.stringify = stringify;
  53847. /**
  53848. * @returns {bool}
  53849. */
  53850. function isCoordinates (value) {
  53851. return regex.test(value);
  53852. }
  53853. module.exports.isCoordinates = isCoordinates;
  53854. module.exports.isCoordinate = function (value) {
  53855. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  53856. return isCoordinates(value);
  53857. };
  53858. function parseIfString (val) {
  53859. if (val.constructor === String) {
  53860. return parseFloat(val, 10);
  53861. }
  53862. return val;
  53863. }
  53864. /**
  53865. * Convert {x, y, z} object to three.js Vector3.
  53866. */
  53867. module.exports.toVector3 = function (vec3) {
  53868. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  53869. };
  53870. },{"./debug":168,"object-assign":25}],168:[function(_dereq_,module,exports){
  53871. (function (process){
  53872. var debugLib = _dereq_('debug');
  53873. var extend = _dereq_('object-assign');
  53874. var settings = {
  53875. colors: {
  53876. debug: 'gray',
  53877. error: 'red',
  53878. info: 'gray',
  53879. warn: 'orange'
  53880. }
  53881. };
  53882. /**
  53883. * Monkeypatches `debug` so we can colorize error/warning messages.
  53884. *
  53885. * (See issue: https://github.com/visionmedia/debug/issues/137)
  53886. */
  53887. var debug = function (namespace) {
  53888. var d = debugLib(namespace);
  53889. d.color = getDebugNamespaceColor(namespace);
  53890. return d;
  53891. };
  53892. extend(debug, debugLib);
  53893. /**
  53894. * Returns the type of the namespace (e.g., `error`, `warn`).
  53895. *
  53896. * @param {String} namespace
  53897. * The debug logger's namespace (e.g., `components:geometry:warn`).
  53898. * @returns {String} The type of the namespace (e.g., `warn`).
  53899. * @api private
  53900. */
  53901. function getDebugNamespaceType (namespace) {
  53902. var chunks = namespace.split(':');
  53903. return chunks[chunks.length - 1]; // Return the last one
  53904. }
  53905. /**
  53906. * Returns the color of the namespace (e.g., `orange`).
  53907. *
  53908. * @param {String} namespace
  53909. * The debug logger's namespace (e.g., `components:geometry:warn`).
  53910. * @returns {String} The color of the namespace (e.g., `orange`).
  53911. * @api private
  53912. */
  53913. function getDebugNamespaceColor (namespace) {
  53914. var type = getDebugNamespaceType(namespace);
  53915. var color = settings.colors && settings.colors[type];
  53916. return color || null;
  53917. }
  53918. /**
  53919. * Returns `localStorage` if possible.
  53920. *
  53921. * This is necessary because Safari throws when a user disables
  53922. * cookies or `localStorage` and you attempt to access it.
  53923. *
  53924. * @returns {localStorage}
  53925. * @api private
  53926. */
  53927. function storage () {
  53928. try {
  53929. return window.localStorage;
  53930. } catch (e) {
  53931. }
  53932. }
  53933. /**
  53934. * To enable console logging, type this in the Console of your Dev Tools:
  53935. *
  53936. * localStorage.logs = 1
  53937. *
  53938. * To disable console logging:
  53939. *
  53940. * localStorage.logs = 0
  53941. *
  53942. */
  53943. var ls = storage();
  53944. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  53945. debug.enable('*');
  53946. } else {
  53947. debug.enable('*:error,*:info,*:warn');
  53948. }
  53949. if (process.browser) { window.logs = debug; }
  53950. module.exports = debug;
  53951. }).call(this,_dereq_('_process'))
  53952. },{"_process":32,"debug":8,"object-assign":25}],169:[function(_dereq_,module,exports){
  53953. (function (process){
  53954. var vrDisplay;
  53955. if (navigator.getVRDisplays) {
  53956. navigator.getVRDisplays().then(function (displays) {
  53957. vrDisplay = displays.length && displays[0];
  53958. });
  53959. }
  53960. function getVRDisplay () { return vrDisplay; }
  53961. module.exports.getVRDisplay = getVRDisplay;
  53962. /**
  53963. * Determine if a headset is connected by checking if a vrDisplay is available.
  53964. */
  53965. function checkHeadsetConnected () { return !!getVRDisplay(); }
  53966. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  53967. /**
  53968. * Check for positional tracking.
  53969. */
  53970. function checkHasPositionalTracking () {
  53971. var vrDisplay = getVRDisplay();
  53972. if (isMobile() || isGearVR()) { return false; }
  53973. return vrDisplay && vrDisplay.capabilities.hasPosition;
  53974. }
  53975. module.exports.checkHasPositionalTracking = checkHasPositionalTracking;
  53976. /**
  53977. * Checks if browser is mobile.
  53978. * @return {Boolean} True if mobile browser detected.
  53979. */
  53980. var isMobile = (function () {
  53981. var _isMobile = false;
  53982. (function (a) {
  53983. // eslint-disable-next-line no-useless-escape
  53984. 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))) {
  53985. _isMobile = true;
  53986. }
  53987. if (isIOS() || isTablet() || isR7()) {
  53988. _isMobile = true;
  53989. }
  53990. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  53991. return function () { return _isMobile; };
  53992. })();
  53993. module.exports.isMobile = isMobile;
  53994. /**
  53995. * Detect tablet devices.
  53996. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  53997. */
  53998. function isTablet (mockUserAgent) {
  53999. var userAgent = mockUserAgent || window.navigator.userAgent;
  54000. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  54001. }
  54002. module.exports.isTablet = isTablet;
  54003. function isIOS () {
  54004. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  54005. }
  54006. module.exports.isIOS = isIOS;
  54007. function isGearVR () {
  54008. return /SamsungBrowser.+Mobile VR/i.test(window.navigator.userAgent);
  54009. }
  54010. module.exports.isGearVR = isGearVR;
  54011. /**
  54012. * Detect Oculus Go device
  54013. */
  54014. function isOculusGo () {
  54015. return /Pacific Build.+OculusBrowser.+SamsungBrowser.+Mobile VR/i.test(window.navigator.userAgent);
  54016. }
  54017. module.exports.isOculusGo = isOculusGo;
  54018. function isR7 () {
  54019. return /R7 Build/.test(window.navigator.userAgent);
  54020. }
  54021. module.exports.isR7 = isR7;
  54022. /**
  54023. * Checks mobile device orientation.
  54024. * @return {Boolean} True if landscape orientation.
  54025. */
  54026. module.exports.isLandscape = function () {
  54027. var orientation = window.orientation;
  54028. if (isR7()) { orientation += 90; }
  54029. return orientation === 90 || orientation === -90;
  54030. };
  54031. /**
  54032. * Check if device is iOS and older than version 10.
  54033. */
  54034. module.exports.isIOSOlderThan10 = function (userAgent) {
  54035. return /(iphone|ipod|ipad).*os.(7|8|9)/i.test(userAgent);
  54036. };
  54037. /**
  54038. * Check if running in a browser or spoofed browser (bundler).
  54039. * We need to check a node api that isn't mocked on either side.
  54040. * `require` and `module.exports` are mocked in browser by bundlers.
  54041. * `window` is mocked in node.
  54042. * `process` is also mocked by browserify, but has custom properties.
  54043. */
  54044. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  54045. /**
  54046. * Check if running in node on the server.
  54047. */
  54048. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  54049. /**
  54050. * Update an Object3D pose if a polyfilled vrDisplay is present.
  54051. */
  54052. module.exports.PolyfillControls = function PolyfillControls (object) {
  54053. var frameData;
  54054. var vrDisplay = window.webvrpolyfill.getPolyfillDisplays()[0];
  54055. if (window.VRFrameData) { frameData = new window.VRFrameData(); }
  54056. this.update = function () {
  54057. var pose;
  54058. if (!vrDisplay) { return; }
  54059. vrDisplay.getFrameData(frameData);
  54060. pose = frameData.pose;
  54061. if (pose.orientation !== null) {
  54062. object.quaternion.fromArray(pose.orientation);
  54063. }
  54064. if (pose.position !== null) {
  54065. object.position.fromArray(pose.position);
  54066. } else {
  54067. object.position.set(0, 0, 0);
  54068. }
  54069. };
  54070. };
  54071. }).call(this,_dereq_('_process'))
  54072. },{"_process":32}],170:[function(_dereq_,module,exports){
  54073. /**
  54074. * Split a delimited component property string (e.g., `material.color`) to an object
  54075. * containing `component` name and `property` name. If there is no delimiter, just return the
  54076. * string back.
  54077. *
  54078. * Cache arrays from splitting strings via delimiter to save on memory.
  54079. *
  54080. * @param {string} str - e.g., `material.opacity`.
  54081. * @param {string} delimiter - e.g., `.`.
  54082. * @returns {array} e.g., `['material', 'opacity']`.
  54083. */
  54084. var propertyPathCache = {};
  54085. function getComponentPropertyPath (str, delimiter) {
  54086. delimiter = delimiter || '.';
  54087. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  54088. if (str.indexOf(delimiter) !== -1) {
  54089. propertyPathCache[delimiter][str] = str.split(delimiter);
  54090. } else {
  54091. propertyPathCache[delimiter][str] = str;
  54092. }
  54093. return propertyPathCache[delimiter][str];
  54094. }
  54095. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  54096. module.exports.propertyPathCache = propertyPathCache;
  54097. /**
  54098. * Get component property using encoded component name + component property name with a
  54099. * delimiter.
  54100. */
  54101. module.exports.getComponentProperty = function (el, name, delimiter) {
  54102. var splitName;
  54103. delimiter = delimiter || '.';
  54104. if (name.indexOf(delimiter) !== -1) {
  54105. splitName = getComponentPropertyPath(name, delimiter);
  54106. if (splitName.constructor === String) {
  54107. return el.getAttribute(splitName);
  54108. }
  54109. return el.getAttribute(splitName[0])[splitName[1]];
  54110. }
  54111. return el.getAttribute(name);
  54112. };
  54113. /**
  54114. * Set component property using encoded component name + component property name with a
  54115. * delimiter.
  54116. */
  54117. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  54118. var splitName;
  54119. delimiter = delimiter || '.';
  54120. if (name.indexOf(delimiter) !== -1) {
  54121. splitName = getComponentPropertyPath(name, delimiter);
  54122. if (splitName.constructor === String) {
  54123. el.setAttribute(splitName, value);
  54124. } else {
  54125. el.setAttribute(splitName[0], splitName[1], value);
  54126. }
  54127. return;
  54128. }
  54129. el.setAttribute(name, value);
  54130. };
  54131. },{}],171:[function(_dereq_,module,exports){
  54132. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  54133. var width = canvasEl.style.width;
  54134. var height = canvasEl.style.height;
  54135. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  54136. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  54137. // By changing the size 1 pixel and restoring the previous value
  54138. // we trigger a size recalculation cycle.
  54139. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  54140. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  54141. setTimeout(function () {
  54142. canvasEl.style.width = width;
  54143. canvasEl.style.height = height;
  54144. }, 200);
  54145. };
  54146. },{}],172:[function(_dereq_,module,exports){
  54147. /* global location */
  54148. /* Centralized place to reference utilities since utils is exposed to the user. */
  54149. var debug = _dereq_('./debug');
  54150. var deepAssign = _dereq_('deep-assign');
  54151. var device = _dereq_('./device');
  54152. var objectAssign = _dereq_('object-assign');
  54153. var objectPool = _dereq_('./object-pool');
  54154. var warn = debug('utils:warn');
  54155. module.exports.bind = _dereq_('./bind');
  54156. module.exports.coordinates = _dereq_('./coordinates');
  54157. module.exports.debug = debug;
  54158. module.exports.device = device;
  54159. module.exports.entity = _dereq_('./entity');
  54160. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  54161. module.exports.material = _dereq_('./material');
  54162. module.exports.objectPool = objectPool;
  54163. module.exports.split = _dereq_('./split').split;
  54164. module.exports.styleParser = _dereq_('./styleParser');
  54165. module.exports.trackedControls = _dereq_('./tracked-controls');
  54166. module.exports.checkHeadsetConnected = function () {
  54167. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  54168. return device.checkHeadsetConnected(arguments);
  54169. };
  54170. module.exports.isGearVR = function () {
  54171. warn('`utils.isGearVR` has moved to `utils.device.isGearVR`');
  54172. return device.isGearVR(arguments);
  54173. };
  54174. module.exports.isIOS = function () {
  54175. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  54176. return device.isIOS(arguments);
  54177. };
  54178. module.exports.isMobile = function () {
  54179. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  54180. return device.isMobile(arguments);
  54181. };
  54182. /**
  54183. * Returns throttle function that gets called at most once every interval.
  54184. *
  54185. * @param {function} functionToThrottle
  54186. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  54187. * @param {object} optionalContext - If given, bind function to throttle to this context.
  54188. * @returns {function} Throttled function.
  54189. */
  54190. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  54191. var lastTime;
  54192. if (optionalContext) {
  54193. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  54194. }
  54195. return function () {
  54196. var time = Date.now();
  54197. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  54198. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  54199. lastTime = time;
  54200. functionToThrottle.apply(null, arguments);
  54201. }
  54202. };
  54203. };
  54204. /**
  54205. * Returns throttle function that gets called at most once every interval.
  54206. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  54207. *
  54208. * @param {function} functionToThrottle
  54209. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  54210. * @param {object} optionalContext - If given, bind function to throttle to this context.
  54211. * @returns {function} Throttled function.
  54212. */
  54213. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  54214. var lastTime;
  54215. if (optionalContext) {
  54216. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  54217. }
  54218. return function (time, delta) {
  54219. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  54220. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  54221. lastTime = time;
  54222. functionToThrottle(time, sinceLastTime);
  54223. }
  54224. };
  54225. };
  54226. /**
  54227. * Returns debounce function that gets called only once after a set of repeated calls.
  54228. *
  54229. * @param {function} functionToDebounce
  54230. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  54231. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  54232. * @returns {function} Debounced function.
  54233. */
  54234. module.exports.debounce = function (func, wait, immediate) {
  54235. var timeout;
  54236. return function () {
  54237. var context = this;
  54238. var args = arguments;
  54239. var later = function () {
  54240. timeout = null;
  54241. if (!immediate) func.apply(context, args);
  54242. };
  54243. var callNow = immediate && !timeout;
  54244. clearTimeout(timeout);
  54245. timeout = setTimeout(later, wait);
  54246. if (callNow) func.apply(context, args);
  54247. };
  54248. };
  54249. /**
  54250. * Mix the properties of source object(s) into a destination object.
  54251. *
  54252. * @param {object} dest - The object to which properties will be copied.
  54253. * @param {...object} source - The object(s) from which properties will be copied.
  54254. */
  54255. module.exports.extend = objectAssign;
  54256. module.exports.extendDeep = deepAssign;
  54257. module.exports.clone = function (obj) {
  54258. return JSON.parse(JSON.stringify(obj));
  54259. };
  54260. /**
  54261. * Checks if two values are equal.
  54262. * Includes objects and arrays and nested objects and arrays.
  54263. * Try to keep this function performant as it will be called often to see if a component
  54264. * should be updated.
  54265. *
  54266. * @param {object} a - First object.
  54267. * @param {object} b - Second object.
  54268. * @returns {boolean} Whether two objects are deeply equal.
  54269. */
  54270. var deepEqual = (function () {
  54271. var arrayPool = objectPool.createPool(function () { return []; });
  54272. return function (a, b) {
  54273. var key;
  54274. var keysA;
  54275. var keysB;
  54276. var i;
  54277. var valA;
  54278. var valB;
  54279. // If not objects or arrays, compare as values.
  54280. if (a === undefined || b === undefined || a === null || b === null ||
  54281. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  54282. (a.constructor === Array && b.constructor === Array))) {
  54283. return a === b;
  54284. }
  54285. // Different number of keys, not equal.
  54286. keysA = arrayPool.use();
  54287. keysB = arrayPool.use();
  54288. keysA.length = 0;
  54289. keysB.length = 0;
  54290. for (key in a) { keysA.push(key); }
  54291. for (key in b) { keysB.push(key); }
  54292. if (keysA.length !== keysB.length) {
  54293. arrayPool.recycle(keysA);
  54294. arrayPool.recycle(keysB);
  54295. return false;
  54296. }
  54297. // Return `false` at the first sign of inequality.
  54298. for (i = 0; i < keysA.length; ++i) {
  54299. valA = a[keysA[i]];
  54300. valB = b[keysA[i]];
  54301. // Check nested array and object.
  54302. if ((typeof valA === 'object' || typeof valB === 'object') ||
  54303. (Array.isArray(valA) && Array.isArray(valB))) {
  54304. if (valA === valB) { continue; }
  54305. if (!deepEqual(valA, valB)) {
  54306. arrayPool.recycle(keysA);
  54307. arrayPool.recycle(keysB);
  54308. return false;
  54309. }
  54310. } else if (valA !== valB) {
  54311. arrayPool.recycle(keysA);
  54312. arrayPool.recycle(keysB);
  54313. return false;
  54314. }
  54315. }
  54316. arrayPool.recycle(keysA);
  54317. arrayPool.recycle(keysB);
  54318. return true;
  54319. };
  54320. })();
  54321. module.exports.deepEqual = deepEqual;
  54322. /**
  54323. * Computes the difference between two objects.
  54324. *
  54325. * @param {object} a - First object to compare (e.g., oldData).
  54326. * @param {object} b - Second object to compare (e.g., newData).
  54327. * @returns {object}
  54328. * Difference object where set of keys note which values were not equal, and values are
  54329. * `b`'s values.
  54330. */
  54331. module.exports.diff = (function () {
  54332. var keys = [];
  54333. return function (a, b, targetObject) {
  54334. var aVal;
  54335. var bVal;
  54336. var bKey;
  54337. var diff;
  54338. var key;
  54339. var i;
  54340. var isComparingObjects;
  54341. diff = targetObject || {};
  54342. // Collect A keys.
  54343. keys.length = 0;
  54344. for (key in a) { keys.push(key); }
  54345. if (!b) { return diff; }
  54346. // Collect B keys.
  54347. for (bKey in b) {
  54348. if (keys.indexOf(bKey) === -1) {
  54349. keys.push(bKey);
  54350. }
  54351. }
  54352. for (i = 0; i < keys.length; i++) {
  54353. key = keys[i];
  54354. aVal = a[key];
  54355. bVal = b[key];
  54356. isComparingObjects = aVal && bVal &&
  54357. aVal.constructor === Object && bVal.constructor === Object;
  54358. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  54359. (!isComparingObjects && aVal !== bVal)) {
  54360. diff[key] = bVal;
  54361. }
  54362. }
  54363. return diff;
  54364. };
  54365. })();
  54366. /**
  54367. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  54368. * @param {Event} event Event object.
  54369. * @returns {Boolean} Whether the key event should be captured.
  54370. */
  54371. module.exports.shouldCaptureKeyEvent = function (event) {
  54372. if (event.metaKey) { return false; }
  54373. return document.activeElement === document.body;
  54374. };
  54375. /**
  54376. * Splits a string into an array based on a delimiter.
  54377. *
  54378. * @param {string=} [str=''] Source string
  54379. * @param {string=} [delimiter=' '] Delimiter to use
  54380. * @returns {array} Array of delimited strings
  54381. */
  54382. module.exports.splitString = function (str, delimiter) {
  54383. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  54384. // First collapse the whitespace (or whatever the delimiter is).
  54385. var regex = new RegExp(delimiter, 'g');
  54386. str = (str || '').replace(regex, delimiter);
  54387. // Then split.
  54388. return str.split(delimiter);
  54389. };
  54390. /**
  54391. * Extracts data from the element given an object that contains expected keys.
  54392. *
  54393. * @param {Element} Source element.
  54394. * @param {Object} [defaults={}] Object of default key-value pairs.
  54395. * @returns {Object}
  54396. */
  54397. module.exports.getElData = function (el, defaults) {
  54398. defaults = defaults || {};
  54399. var data = {};
  54400. Object.keys(defaults).forEach(copyAttribute);
  54401. function copyAttribute (key) {
  54402. if (el.hasAttribute(key)) {
  54403. data[key] = el.getAttribute(key);
  54404. }
  54405. }
  54406. return data;
  54407. };
  54408. /**
  54409. * Retrieves querystring value.
  54410. * @param {String} name Name of querystring key.
  54411. * @return {String} Value
  54412. */
  54413. module.exports.getUrlParameter = function (name) {
  54414. // eslint-disable-next-line no-useless-escape
  54415. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  54416. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  54417. var results = regex.exec(location.search);
  54418. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  54419. };
  54420. /**
  54421. * Detects whether context is within iframe.
  54422. */
  54423. module.exports.isIframed = function () {
  54424. return window.top !== window.self;
  54425. };
  54426. /**
  54427. * Finds all elements under the element that have the isScene
  54428. * property set to true
  54429. */
  54430. module.exports.findAllScenes = function (el) {
  54431. var matchingElements = [];
  54432. var allElements = el.getElementsByTagName('*');
  54433. for (var i = 0, n = allElements.length; i < n; i++) {
  54434. if (allElements[i].isScene) {
  54435. // Element exists with isScene set.
  54436. matchingElements.push(allElements[i]);
  54437. }
  54438. }
  54439. return matchingElements;
  54440. };
  54441. // Must be at bottom to avoid circular dependency.
  54442. module.exports.srcLoader = _dereq_('./src-loader');
  54443. },{"./bind":166,"./coordinates":167,"./debug":168,"./device":169,"./entity":170,"./forceCanvasResizeSafariMobile":171,"./material":173,"./object-pool":174,"./split":175,"./src-loader":176,"./styleParser":177,"./tracked-controls":178,"deep-assign":10,"object-assign":25}],173:[function(_dereq_,module,exports){
  54444. var THREE = _dereq_('../lib/three');
  54445. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  54446. /**
  54447. * Update `material` texture property (usually but not always `map`)
  54448. * from `data` property (usually but not always `src`)
  54449. *
  54450. * @param {object} shader - A-Frame shader instance.
  54451. * @param {object} data
  54452. */
  54453. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  54454. var el = shader.el;
  54455. var material = shader.material;
  54456. var src = data[dataName];
  54457. // Because a single material / shader may have multiple textures,
  54458. // we need to remember the source value for this data property
  54459. // to avoid redundant operations which can be expensive otherwise
  54460. // (e.g. video texture loads).
  54461. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  54462. if (!src) {
  54463. // Forget the prior material src.
  54464. delete shader.materialSrcs[materialName];
  54465. // Remove the texture.
  54466. setMap(null);
  54467. return;
  54468. }
  54469. // Don't process if material src hasn't changed.
  54470. if (src === shader.materialSrcs[materialName]) { return; }
  54471. // Remember the new src for this texture (there may be multiple).
  54472. shader.materialSrcs[materialName] = src;
  54473. // If the new material src is already a texture, just use it.
  54474. if (src instanceof THREE.Texture) { setMap(src); } else {
  54475. // Load texture for the new material src.
  54476. // (And check if we should still use it once available in callback.)
  54477. el.sceneEl.systems.material.loadTexture(src,
  54478. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  54479. checkSetMap);
  54480. }
  54481. function checkSetMap (texture) {
  54482. // If the source has been changed, don't use loaded texture.
  54483. if (shader.materialSrcs[materialName] !== src) { return; }
  54484. setMap(texture);
  54485. }
  54486. function setMap (texture) {
  54487. material[materialName] = texture;
  54488. material.needsUpdate = true;
  54489. handleTextureEvents(el, texture);
  54490. }
  54491. };
  54492. /**
  54493. * Update `material.map` given `data.src`. For standard and flat shaders.
  54494. *
  54495. * @param {object} shader - A-Frame shader instance.
  54496. * @param {object} data
  54497. */
  54498. module.exports.updateMap = function (shader, data) {
  54499. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  54500. };
  54501. /**
  54502. * Updates the material's maps which give the illusion of extra geometry.
  54503. *
  54504. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  54505. * @param {object} shader - A-Frame shader instance
  54506. * @param {object} data
  54507. */
  54508. module.exports.updateDistortionMap = function (longType, shader, data) {
  54509. var shortType = longType;
  54510. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  54511. var el = shader.el;
  54512. var material = shader.material;
  54513. var src = data[longType + 'Map'];
  54514. var info = {};
  54515. info.src = src;
  54516. // Pass through the repeat and offset to be handled by the material loader.
  54517. info.offset = data[longType + 'TextureOffset'];
  54518. info.repeat = data[longType + 'TextureRepeat'];
  54519. info.wrap = data[longType + 'TextureWrap'];
  54520. if (src) {
  54521. if (src === shader[longType + 'TextureSrc']) { return; }
  54522. // Texture added or changed.
  54523. shader[longType + 'TextureSrc'] = src;
  54524. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  54525. return;
  54526. }
  54527. // Texture removed.
  54528. if (!material.map) { return; }
  54529. setMap(null);
  54530. function setMap (texture) {
  54531. material[shortType + 'Map'] = texture;
  54532. material.needsUpdate = true;
  54533. handleTextureEvents(el, texture);
  54534. }
  54535. };
  54536. /**
  54537. * Emit event on entities on texture-related events.
  54538. *
  54539. * @param {Element} el - Entity.
  54540. * @param {object} texture - three.js Texture.
  54541. */
  54542. function handleTextureEvents (el, texture) {
  54543. if (!texture) { return; }
  54544. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  54545. // Video events.
  54546. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  54547. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  54548. // Check to see if we need to use iOS 10 HLS shader.
  54549. // Only override the shader if it is stock shader that we know doesn't correct.
  54550. if (!el.components || !el.components.material) { return; }
  54551. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  54552. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  54553. el.setAttribute('material', 'shader', 'ios10hls');
  54554. }
  54555. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  54556. });
  54557. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  54558. // Works for non-looping videos only.
  54559. el.emit('materialvideoended', {src: texture.image, texture: texture});
  54560. });
  54561. }
  54562. module.exports.handleTextureEvents = handleTextureEvents;
  54563. /**
  54564. * Given video element src and type, guess whether stream is HLS.
  54565. *
  54566. * @param {string} src - src from video element (generally URL to content).
  54567. * @param {string} type - type from video element (generally MIME type if present).
  54568. */
  54569. module.exports.isHLS = function (src, type) {
  54570. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  54571. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  54572. return false;
  54573. };
  54574. },{"../lib/three":150}],174:[function(_dereq_,module,exports){
  54575. /*
  54576. Adapted deePool by Kyle Simpson.
  54577. MIT License: http://getify.mit-license.org
  54578. */
  54579. var EMPTY_SLOT = Object.freeze(Object.create(null));
  54580. // Default object factory.
  54581. function defaultObjectFactory () { return {}; }
  54582. /**
  54583. * Create a new pool.
  54584. */
  54585. module.exports.createPool = function createPool (objectFactory) {
  54586. var objPool = [];
  54587. var nextFreeSlot = null; // Pool location to look for a free object to use.
  54588. objectFactory = objectFactory || defaultObjectFactory;
  54589. function use () {
  54590. var objToUse;
  54591. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  54592. grow(objPool.length || 5);
  54593. }
  54594. objToUse = objPool[nextFreeSlot];
  54595. objPool[nextFreeSlot++] = EMPTY_SLOT;
  54596. clearObject(objToUse);
  54597. return objToUse;
  54598. }
  54599. function recycle (obj) {
  54600. if (!(obj instanceof Object)) { return; }
  54601. if (nextFreeSlot === null || nextFreeSlot === -1) {
  54602. objPool[objPool.length] = obj;
  54603. return;
  54604. }
  54605. objPool[--nextFreeSlot] = obj;
  54606. }
  54607. function grow (count) {
  54608. var currentLength;
  54609. var i;
  54610. count = count === undefined ? objPool.length : count;
  54611. if (count > 0 && nextFreeSlot == null) {
  54612. nextFreeSlot = 0;
  54613. }
  54614. if (count > 0) {
  54615. currentLength = objPool.length;
  54616. objPool.length += Number(count);
  54617. for (i = currentLength; i < objPool.length; i++) {
  54618. // Add new obj to pool.
  54619. objPool[i] = objectFactory();
  54620. }
  54621. }
  54622. return objPool.length;
  54623. }
  54624. function size () {
  54625. return objPool.length;
  54626. }
  54627. return {
  54628. grow: grow,
  54629. pool: objPool,
  54630. recycle: recycle,
  54631. size: size,
  54632. use: use
  54633. };
  54634. };
  54635. function clearObject (obj) {
  54636. var key;
  54637. if (!(obj.constructor === Object)) { return; }
  54638. for (key in obj) { obj[key] = undefined; }
  54639. }
  54640. module.exports.clearObject = clearObject;
  54641. },{}],175:[function(_dereq_,module,exports){
  54642. /**
  54643. * String split with cached result.
  54644. */
  54645. module.exports.split = (function () {
  54646. var splitCache = {};
  54647. return function (str, delimiter) {
  54648. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  54649. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  54650. splitCache[delimiter][str] = str.split(delimiter);
  54651. return splitCache[delimiter][str];
  54652. };
  54653. })();
  54654. },{}],176:[function(_dereq_,module,exports){
  54655. /* global Image, XMLHttpRequest */
  54656. var debug = _dereq_('./debug');
  54657. var warn = debug('utils:src-loader:warn');
  54658. /**
  54659. * Validate a texture, either as a selector or as a URL.
  54660. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  54661. * callback.
  54662. *
  54663. * `src` will be passed into the callback
  54664. *
  54665. * @params {string|Element} src - URL or media element.
  54666. * @params {function} isImageCb - callback if texture is an image.
  54667. * @params {function} isVideoCb - callback if texture is a video.
  54668. */
  54669. function validateSrc (src, isImageCb, isVideoCb) {
  54670. checkIsImage(src, function isAnImageUrl (isImage) {
  54671. if (isImage) {
  54672. isImageCb(src);
  54673. return;
  54674. }
  54675. isVideoCb(src);
  54676. });
  54677. }
  54678. /**
  54679. * Validates six images as a cubemap, either as selector or comma-separated
  54680. * URLs.
  54681. *
  54682. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  54683. must be wrapped by `url()`.
  54684. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  54685. must be wrapped by `url()`.
  54686. */
  54687. function validateCubemapSrc (src, cb) {
  54688. var aCubemap;
  54689. var cubemapSrcRegex = '';
  54690. var i;
  54691. var urls;
  54692. var validatedUrls = [];
  54693. for (i = 0; i < 5; i++) {
  54694. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  54695. }
  54696. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  54697. urls = src.match(new RegExp(cubemapSrcRegex));
  54698. // `src` is a comma-separated list of URLs.
  54699. // In this case, re-use validateSrc for each side of the cube.
  54700. function isImageCb (url) {
  54701. validatedUrls.push(url);
  54702. if (validatedUrls.length === 6) {
  54703. cb(validatedUrls);
  54704. }
  54705. }
  54706. if (urls) {
  54707. for (i = 1; i < 7; i++) {
  54708. validateSrc(parseUrl(urls[i]), isImageCb);
  54709. }
  54710. return;
  54711. }
  54712. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  54713. aCubemap = validateAndGetQuerySelector(src);
  54714. if (!aCubemap) { return; }
  54715. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  54716. return cb(aCubemap.srcs);
  54717. }
  54718. // Else if aCubeMap is not a <a-cubemap>.
  54719. warn('Selector "%s" does not point to <a-cubemap>', src);
  54720. }
  54721. /**
  54722. * Parses src from `url(src)`.
  54723. * @param {string} src - String to parse.
  54724. * @return {string} The parsed src, if parseable.
  54725. */
  54726. function parseUrl (src) {
  54727. var parsedSrc = src.match(/\url\((.+)\)/);
  54728. if (!parsedSrc) { return; }
  54729. return parsedSrc[1];
  54730. }
  54731. /**
  54732. * Call back whether `src` is an image.
  54733. *
  54734. * @param {string|Element} src - URL or element that will be tested.
  54735. * @param {function} onResult - Callback with whether `src` is an image.
  54736. */
  54737. function checkIsImage (src, onResult) {
  54738. var request;
  54739. if (src.tagName) {
  54740. onResult(src.tagName === 'IMG');
  54741. return;
  54742. }
  54743. request = new XMLHttpRequest();
  54744. // Try to send HEAD request to check if image first.
  54745. request.open('HEAD', src);
  54746. request.addEventListener('load', function (event) {
  54747. var contentType;
  54748. if (request.status >= 200 && request.status < 300) {
  54749. contentType = request.getResponseHeader('Content-Type');
  54750. if (contentType == null) {
  54751. checkIsImageFallback(src, onResult);
  54752. } else {
  54753. if (contentType.startsWith('image')) {
  54754. onResult(true);
  54755. } else {
  54756. onResult(false);
  54757. }
  54758. }
  54759. } else {
  54760. checkIsImageFallback(src, onResult);
  54761. }
  54762. request.abort();
  54763. });
  54764. request.send();
  54765. }
  54766. function checkIsImageFallback (src, onResult) {
  54767. var tester = new Image();
  54768. tester.addEventListener('load', onLoad);
  54769. function onLoad () { onResult(true); }
  54770. tester.addEventListener('error', onError);
  54771. function onError () { onResult(false); }
  54772. tester.src = src;
  54773. }
  54774. /**
  54775. * Query and validate a query selector,
  54776. *
  54777. * @param {string} selector - DOM selector.
  54778. * @return {object|null|undefined} Selected DOM element if exists.
  54779. null if query yields no results.
  54780. undefined if `selector` is not a valid selector.
  54781. */
  54782. function validateAndGetQuerySelector (selector) {
  54783. try {
  54784. var el = document.querySelector(selector);
  54785. if (!el) {
  54786. warn('No element was found matching the selector: "%s"', selector);
  54787. }
  54788. return el;
  54789. } catch (e) { // Capture exception if it's not a valid selector.
  54790. warn('"%s" is not a valid selector', selector);
  54791. return undefined;
  54792. }
  54793. }
  54794. module.exports = {
  54795. parseUrl: parseUrl,
  54796. validateSrc: validateSrc,
  54797. validateCubemapSrc: validateCubemapSrc
  54798. };
  54799. },{"./debug":168}],177:[function(_dereq_,module,exports){
  54800. /* Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5"). */
  54801. var styleParser = _dereq_('style-attr');
  54802. /**
  54803. * Deserializes style-like string into an object of properties.
  54804. *
  54805. * @param {string} value - HTML attribute value.
  54806. * @returns {object} Property data.
  54807. */
  54808. module.exports.parse = function (value) {
  54809. var parsedData;
  54810. if (typeof value !== 'string') { return value; }
  54811. parsedData = styleParser.parse(value);
  54812. // The style parser returns an object { "" : "test"} when fed a string
  54813. if (parsedData['']) { return value; }
  54814. return transformKeysToCamelCase(parsedData);
  54815. };
  54816. /**
  54817. * Serialize an object of properties into a style-like string.
  54818. *
  54819. * @param {object} data - Property data.
  54820. * @returns {string}
  54821. */
  54822. module.exports.stringify = function (data) {
  54823. if (typeof data === 'string') { return data; }
  54824. return styleParser.stringify(data);
  54825. };
  54826. /**
  54827. * Converts string from hyphen to camelCase.
  54828. *
  54829. * @param {string} str - String to camelCase.
  54830. * @return {string} CamelCased string.
  54831. */
  54832. function toCamelCase (str) {
  54833. return str.replace(/-([a-z])/g, camelCase);
  54834. function camelCase (g) { return g[1].toUpperCase(); }
  54835. }
  54836. module.exports.toCamelCase = toCamelCase;
  54837. /**
  54838. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  54839. * `maxValue`).
  54840. *
  54841. * @param {object} obj - The object to camelCase keys.
  54842. * @return {object} The object with keys camelCased.
  54843. */
  54844. function transformKeysToCamelCase (obj) {
  54845. var keys = Object.keys(obj);
  54846. var camelCaseObj = {};
  54847. keys.forEach(function (key) {
  54848. var camelCaseKey = toCamelCase(key);
  54849. camelCaseObj[camelCaseKey] = obj[key];
  54850. });
  54851. return camelCaseObj;
  54852. }
  54853. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  54854. },{"style-attr":35}],178:[function(_dereq_,module,exports){
  54855. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  54856. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  54857. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  54858. /**
  54859. * Called on controller component `.play` handlers.
  54860. * Check if controller matches parameters and inject tracked-controls component.
  54861. * Handle event listeners.
  54862. * Generate controllerconnected or controllerdisconnected events.
  54863. *
  54864. * @param {object} component - Tracked controls component.
  54865. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  54866. * @param {object} queryObject - Map of values to match.
  54867. */
  54868. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  54869. var el = component.el;
  54870. var isPresent = isControllerPresent(component, idPrefix, queryObject);
  54871. // If component was previously paused and now playing, re-add event listeners.
  54872. // Handle the event listeners here since this helper method is control of calling
  54873. // `.addEventListeners` and `.removeEventListeners`.
  54874. if (component.controllerPresent && !component.controllerEventsActive) {
  54875. component.addEventListeners();
  54876. }
  54877. // Nothing changed, no need to do anything.
  54878. if (isPresent === component.controllerPresent) { return isPresent; }
  54879. component.controllerPresent = isPresent;
  54880. // Update controller presence.
  54881. if (isPresent) {
  54882. component.injectTrackedControls();
  54883. component.addEventListeners();
  54884. el.emit('controllerconnected', {name: component.name, component: component});
  54885. } else {
  54886. component.removeEventListeners();
  54887. el.emit('controllerdisconnected', {name: component.name, component: component});
  54888. }
  54889. };
  54890. /**
  54891. * Enumerate controller (that have pose) and check if they match parameters.
  54892. *
  54893. * @param {object} component - Tracked controls component.
  54894. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  54895. * @param {object} queryObject - Map of values to match.
  54896. */
  54897. function isControllerPresent (component, idPrefix, queryObject) {
  54898. var gamepads;
  54899. var sceneEl = component.el.sceneEl;
  54900. var trackedControlsSystem;
  54901. var filterControllerIndex = queryObject.index || 0;
  54902. if (!idPrefix) { return false; }
  54903. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls'];
  54904. if (!trackedControlsSystem) { return false; }
  54905. gamepads = trackedControlsSystem.controllers;
  54906. if (!gamepads.length) { return false; }
  54907. return !!findMatchingController(gamepads, null, idPrefix, queryObject.hand,
  54908. filterControllerIndex);
  54909. }
  54910. module.exports.isControllerPresent = isControllerPresent;
  54911. /**
  54912. * Walk through the given controllers to find any where the device ID equals
  54913. * filterIdExact, or startsWith filterIdPrefix.
  54914. * A controller where this considered true is considered a 'match'.
  54915. *
  54916. * For each matching controller:
  54917. * If filterHand is set, and the controller:
  54918. * is handed, we further verify that controller.hand equals filterHand.
  54919. * is unhanded (controller.hand is ''), we skip until we have found a
  54920. * number of matching controllers that equals filterControllerIndex
  54921. * If filterHand is not set, we skip until we have found the nth matching
  54922. * controller, where n equals filterControllerIndex
  54923. *
  54924. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  54925. * one or both of: [filterHand, filterControllerIndex]
  54926. *
  54927. * @param {object} controllers - Array of gamepads to search
  54928. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  54929. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  54930. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  54931. * @param {object} filterControllerIndex - Find the nth matching controller,
  54932. * where n equals filterControllerIndex. defaults to 0.
  54933. */
  54934. function findMatchingController (controllers, filterIdExact, filterIdPrefix, filterHand,
  54935. filterControllerIndex) {
  54936. var controller;
  54937. var i;
  54938. var matchingControllerOccurence = 0;
  54939. var targetControllerMatch = filterControllerIndex || 0;
  54940. for (i = 0; i < controllers.length; i++) {
  54941. controller = controllers[i];
  54942. // Determine if the controller ID matches our criteria.
  54943. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  54944. continue;
  54945. }
  54946. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  54947. // If the hand filter and controller handedness are defined we compare them.
  54948. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  54949. // If we have detected an unhanded controller and the component was asking
  54950. // for a particular hand, we need to treat the controllers in the array as
  54951. // pairs of controllers. This effectively means that we need to skip
  54952. // NUM_HANDS matches for each controller number, instead of 1.
  54953. if (filterHand && !controller.hand) {
  54954. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  54955. }
  54956. // We are looking for the nth occurence of a matching controller
  54957. // (n equals targetControllerMatch).
  54958. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  54959. ++matchingControllerOccurence;
  54960. }
  54961. return undefined;
  54962. }
  54963. module.exports.findMatchingController = findMatchingController;
  54964. /**
  54965. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  54966. *
  54967. * @param {object} component - Controller component in use.
  54968. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  54969. * @param {object} evt - Event to process.
  54970. */
  54971. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  54972. var axes;
  54973. var buttonType;
  54974. var changed;
  54975. var detail;
  54976. var j;
  54977. for (buttonType in axesMapping) {
  54978. axes = axesMapping[buttonType];
  54979. changed = false;
  54980. for (j = 0; j < axes.length; j++) {
  54981. if (evt.detail.changed[axes[j]]) { changed = true; }
  54982. }
  54983. if (!changed) { continue; }
  54984. // Axis has changed. Emit the specific moved event with axis values in detail.
  54985. detail = {};
  54986. for (j = 0; j < axes.length; j++) {
  54987. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  54988. }
  54989. component.el.emit(buttonType + 'moved', detail);
  54990. }
  54991. };
  54992. /**
  54993. * Handle a button event and reemits the events.
  54994. *
  54995. * @param {string} id - id of the button.
  54996. * @param {string} evtName - name of the reemitted event
  54997. * @param {object} component - reference to the component
  54998. * @param {string} hand - handedness of the controller: left or right.
  54999. */
  55000. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  55001. var mapping = hand ? component.mapping[hand] : component.mapping;
  55002. var buttonName = mapping.buttons[id];
  55003. component.el.emit(buttonName + evtName);
  55004. if (component.updateModel) {
  55005. component.updateModel(buttonName, evtName);
  55006. }
  55007. };
  55008. },{"../constants":94}],179:[function(_dereq_,module,exports){
  55009. window.glStats = function () {
  55010. var _rS = null;
  55011. var _totalDrawArraysCalls = 0,
  55012. _totalDrawElementsCalls = 0,
  55013. _totalUseProgramCalls = 0,
  55014. _totalFaces = 0,
  55015. _totalVertices = 0,
  55016. _totalPoints = 0,
  55017. _totalBindTexures = 0;
  55018. function _h ( f, c ) {
  55019. return function () {
  55020. c.apply( this, arguments );
  55021. f.apply( this, arguments );
  55022. };
  55023. }
  55024. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  55025. _totalDrawArraysCalls++;
  55026. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  55027. else _totalVertices += arguments[ 2 ];
  55028. } );
  55029. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  55030. _totalDrawElementsCalls++;
  55031. _totalFaces += arguments[ 1 ] / 3;
  55032. _totalVertices += arguments[ 1 ];
  55033. } );
  55034. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  55035. _totalUseProgramCalls++;
  55036. } );
  55037. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  55038. _totalBindTexures++;
  55039. } );
  55040. var _values = {
  55041. allcalls: {
  55042. over: 3000,
  55043. caption: 'Calls (hook)'
  55044. },
  55045. drawelements: {
  55046. caption: 'drawElements (hook)'
  55047. },
  55048. drawarrays: {
  55049. caption: 'drawArrays (hook)'
  55050. }
  55051. };
  55052. var _groups = [ {
  55053. caption: 'WebGL',
  55054. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  55055. } ];
  55056. var _fractions = [ {
  55057. base: 'allcalls',
  55058. steps: [ 'drawelements', 'drawarrays' ]
  55059. } ];
  55060. function _update () {
  55061. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  55062. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  55063. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  55064. _rS( 'bindTexture' ).set( _totalBindTexures );
  55065. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  55066. _rS( 'glfaces' ).set( _totalFaces );
  55067. _rS( 'glvertices' ).set( _totalVertices );
  55068. _rS( 'glpoints' ).set( _totalPoints );
  55069. }
  55070. function _start () {
  55071. _totalDrawArraysCalls = 0;
  55072. _totalDrawElementsCalls = 0;
  55073. _totalUseProgramCalls = 0;
  55074. _totalFaces = 0;
  55075. _totalVertices = 0;
  55076. _totalPoints = 0;
  55077. _totalBindTexures = 0;
  55078. }
  55079. function _end () {}
  55080. function _attach ( r ) {
  55081. _rS = r;
  55082. }
  55083. return {
  55084. update: _update,
  55085. start: _start,
  55086. end: _end,
  55087. attach: _attach,
  55088. values: _values,
  55089. groups: _groups,
  55090. fractions: _fractions
  55091. };
  55092. };
  55093. window.threeStats = function ( renderer ) {
  55094. var _rS = null;
  55095. var _values = {
  55096. 'renderer.info.memory.geometries': {
  55097. caption: 'Geometries'
  55098. },
  55099. 'renderer.info.memory.textures': {
  55100. caption: 'Textures'
  55101. },
  55102. 'renderer.info.programs': {
  55103. caption: 'Programs'
  55104. },
  55105. 'renderer.info.render.calls': {
  55106. caption: 'Calls'
  55107. },
  55108. 'renderer.info.render.triangles': {
  55109. caption: 'Triangles',
  55110. over: 1000
  55111. },
  55112. 'renderer.info.render.points': {
  55113. caption: 'Points'
  55114. }
  55115. };
  55116. var _groups = [ {
  55117. caption: 'Three.js - Memory',
  55118. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  55119. }, {
  55120. caption: 'Three.js - Render',
  55121. values: [ 'renderer.info.render.calls', 'renderer.info.render.triangles', 'renderer.info.render.points' ]
  55122. } ];
  55123. var _fractions = [];
  55124. function _update () {
  55125. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  55126. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  55127. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  55128. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  55129. _rS( 'renderer.info.render.triangles' ).set( renderer.info.render.triangles );
  55130. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  55131. }
  55132. function _start () {}
  55133. function _end () {}
  55134. function _attach ( r ) {
  55135. _rS = r;
  55136. }
  55137. return {
  55138. update: _update,
  55139. start: _start,
  55140. end: _end,
  55141. attach: _attach,
  55142. values: _values,
  55143. groups: _groups,
  55144. fractions: _fractions
  55145. };
  55146. };
  55147. /*
  55148. * From https://github.com/paulirish/memory-stats.js
  55149. */
  55150. window.BrowserStats = function () {
  55151. var _rS = null;
  55152. var _usedJSHeapSize = 0,
  55153. _totalJSHeapSize = 0;
  55154. if ( window.performance && !performance.memory ) {
  55155. performance.memory = {
  55156. usedJSHeapSize: 0,
  55157. totalJSHeapSize: 0
  55158. };
  55159. }
  55160. if ( performance.memory.totalJSHeapSize === 0 ) {
  55161. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  55162. }
  55163. var _values = {
  55164. memory: {
  55165. caption: 'Used Memory',
  55166. average: true,
  55167. avgMs: 1000,
  55168. over: 22
  55169. },
  55170. total: {
  55171. caption: 'Total Memory'
  55172. }
  55173. };
  55174. var _groups = [ {
  55175. caption: 'Browser',
  55176. values: [ 'memory', 'total' ]
  55177. } ];
  55178. var _fractions = [ {
  55179. base: 'total',
  55180. steps: [ 'memory' ]
  55181. } ];
  55182. var log1024 = Math.log( 1024 );
  55183. function _size ( v ) {
  55184. var precision = 100; //Math.pow(10, 2);
  55185. var i = Math.floor( Math.log( v ) / log1024 );
  55186. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  55187. }
  55188. function _update () {
  55189. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  55190. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  55191. _rS( 'memory' ).set( _usedJSHeapSize );
  55192. _rS( 'total' ).set( _totalJSHeapSize );
  55193. }
  55194. function _start () {
  55195. _usedJSHeapSize = 0;
  55196. }
  55197. function _end () {}
  55198. function _attach ( r ) {
  55199. _rS = r;
  55200. }
  55201. return {
  55202. update: _update,
  55203. start: _start,
  55204. end: _end,
  55205. attach: _attach,
  55206. values: _values,
  55207. groups: _groups,
  55208. fractions: _fractions
  55209. };
  55210. };
  55211. if (typeof module === 'object') {
  55212. module.exports = {
  55213. glStats: window.glStats,
  55214. threeStats: window.threeStats,
  55215. BrowserStats: window.BrowserStats
  55216. };
  55217. }
  55218. },{}],180:[function(_dereq_,module,exports){
  55219. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  55220. 'use strict';
  55221. ( function () {
  55222. if ( 'performance' in window == false ) {
  55223. window.performance = {};
  55224. }
  55225. var performance = window.performance;
  55226. if ( 'now' in performance == false ) {
  55227. var nowOffset = Date.now();
  55228. if ( performance.timing && performance.timing.navigationStart ) {
  55229. nowOffset = performance.timing.navigationStart;
  55230. }
  55231. performance.now = function now () {
  55232. return Date.now() - nowOffset;
  55233. };
  55234. }
  55235. if( !performance.mark ) {
  55236. performance.mark = function(){}
  55237. }
  55238. if( !performance.measure ) {
  55239. performance.measure = function(){}
  55240. }
  55241. } )();
  55242. window.rStats = function rStats ( settings ) {
  55243. function iterateKeys ( array, callback ) {
  55244. var keys = Object.keys( array );
  55245. for ( var j = 0, l = keys.length; j < l; j++ ) {
  55246. callback( keys[ j ] );
  55247. }
  55248. }
  55249. function importCSS ( url ) {
  55250. var element = document.createElement( 'link' );
  55251. element.href = url;
  55252. element.rel = 'stylesheet';
  55253. element.type = 'text/css';
  55254. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  55255. }
  55256. var _settings = settings || {};
  55257. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  55258. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  55259. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  55260. var _css = _settings.css || [ _cssFont, _cssRStats ];
  55261. _css.forEach(function (uri) {
  55262. importCSS( uri );
  55263. });
  55264. if ( !_settings.values ) _settings.values = {};
  55265. var _base, _div, _elHeight = 10, _elWidth = 200;
  55266. var _perfCounters = {};
  55267. function Graph ( _dom, _id, _defArg ) {
  55268. var _def = _defArg || {};
  55269. var _canvas = document.createElement( 'canvas' ),
  55270. _ctx = _canvas.getContext( '2d' ),
  55271. _max = 0,
  55272. _current = 0;
  55273. var c = _def.color ? _def.color : '#666666';
  55274. var _dotCanvas = document.createElement( 'canvas' ),
  55275. _dotCtx = _dotCanvas.getContext( '2d' );
  55276. _dotCanvas.width = 1;
  55277. _dotCanvas.height = 2 * _elHeight;
  55278. _dotCtx.fillStyle = '#444444';
  55279. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  55280. _dotCtx.fillStyle = c;
  55281. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  55282. _dotCtx.fillStyle = '#ffffff';
  55283. _dotCtx.globalAlpha = 0.5;
  55284. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  55285. _dotCtx.globalAlpha = 1;
  55286. var _alarmCanvas = document.createElement( 'canvas' ),
  55287. _alarmCtx = _alarmCanvas.getContext( '2d' );
  55288. _alarmCanvas.width = 1;
  55289. _alarmCanvas.height = 2 * _elHeight;
  55290. _alarmCtx.fillStyle = '#444444';
  55291. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  55292. _alarmCtx.fillStyle = '#b70000';
  55293. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  55294. _alarmCtx.globalAlpha = 0.5;
  55295. _alarmCtx.fillStyle = '#ffffff';
  55296. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  55297. _alarmCtx.globalAlpha = 1;
  55298. function _init () {
  55299. _canvas.width = _elWidth;
  55300. _canvas.height = _elHeight;
  55301. _canvas.style.width = _canvas.width + 'px';
  55302. _canvas.style.height = _canvas.height + 'px';
  55303. _canvas.className = 'rs-canvas';
  55304. _dom.appendChild( _canvas );
  55305. _ctx.fillStyle = '#444444';
  55306. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  55307. }
  55308. function _draw ( v, alarm ) {
  55309. _current += ( v - _current ) * 0.1;
  55310. _max *= 0.99;
  55311. if ( _current > _max ) _max = _current;
  55312. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  55313. if ( alarm ) {
  55314. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  55315. } else {
  55316. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  55317. }
  55318. }
  55319. _init();
  55320. return {
  55321. draw: _draw
  55322. };
  55323. }
  55324. function StackGraph ( _dom, _num ) {
  55325. var _canvas = document.createElement( 'canvas' ),
  55326. _ctx = _canvas.getContext( '2d' );
  55327. function _init () {
  55328. _canvas.width = _elWidth;
  55329. _canvas.height = _elHeight * _num;
  55330. _canvas.style.width = _canvas.width + 'px';
  55331. _canvas.style.height = _canvas.height + 'px';
  55332. _canvas.className = 'rs-canvas';
  55333. _dom.appendChild( _canvas );
  55334. _ctx.fillStyle = '#444444';
  55335. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  55336. }
  55337. function _draw ( v ) {
  55338. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  55339. var th = 0;
  55340. iterateKeys( v, function ( j ) {
  55341. var h = v[ j ] * _canvas.height;
  55342. _ctx.fillStyle = _colours[ j ];
  55343. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  55344. th += h;
  55345. } );
  55346. }
  55347. _init();
  55348. return {
  55349. draw: _draw
  55350. };
  55351. }
  55352. function PerfCounter ( id, group ) {
  55353. var _id = id,
  55354. _time,
  55355. _value = 0,
  55356. _total = 0,
  55357. _averageValue = 0,
  55358. _accumValue = 0,
  55359. _accumStart = performance.now(),
  55360. _accumSamples = 0,
  55361. _dom = document.createElement( 'div' ),
  55362. _spanId = document.createElement( 'span' ),
  55363. _spanValue = document.createElement( 'div' ),
  55364. _spanValueText = document.createTextNode( '' ),
  55365. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  55366. _graph = new Graph( _dom, _id, _def ),
  55367. _started = false;
  55368. _spanId.className = 'rs-counter-id';
  55369. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  55370. _spanValue.className = 'rs-counter-value';
  55371. _spanValue.appendChild( _spanValueText );
  55372. _dom.appendChild( _spanId );
  55373. _dom.appendChild( _spanValue );
  55374. if ( group ) group.div.appendChild( _dom );
  55375. else _div.appendChild( _dom );
  55376. _time = performance.now();
  55377. function _average ( v ) {
  55378. if ( _def && _def.average ) {
  55379. _accumValue += v;
  55380. _accumSamples++;
  55381. var t = performance.now();
  55382. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  55383. _averageValue = _accumValue / _accumSamples;
  55384. _accumValue = 0;
  55385. _accumStart = t;
  55386. _accumSamples = 0;
  55387. }
  55388. }
  55389. }
  55390. function _start () {
  55391. _time = performance.now();
  55392. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  55393. _started = true;
  55394. }
  55395. function _end () {
  55396. _value = performance.now() - _time;
  55397. if( _settings.userTimingAPI ) {
  55398. performance.mark( _id + '-end' );
  55399. if( _started ) {
  55400. performance.measure( _id, _id + '-start', _id + '-end' );
  55401. }
  55402. }
  55403. _average( _value );
  55404. }
  55405. function _tick () {
  55406. _end();
  55407. _start();
  55408. }
  55409. function _draw () {
  55410. var v = ( _def && _def.average ) ? _averageValue : _value;
  55411. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  55412. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  55413. _graph.draw( _value, a );
  55414. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  55415. }
  55416. function _frame () {
  55417. var t = performance.now();
  55418. var e = t - _time;
  55419. _total++;
  55420. if ( e > 1000 ) {
  55421. if ( _def && _def.interpolate === false ) {
  55422. _value = _total;
  55423. } else {
  55424. _value = _total * 1000 / e;
  55425. }
  55426. _total = 0;
  55427. _time = t;
  55428. _average( _value );
  55429. }
  55430. }
  55431. function _set ( v ) {
  55432. _value = v;
  55433. _average( _value );
  55434. }
  55435. return {
  55436. set: _set,
  55437. start: _start,
  55438. tick: _tick,
  55439. end: _end,
  55440. frame: _frame,
  55441. value: function () {
  55442. return _value;
  55443. },
  55444. draw: _draw
  55445. };
  55446. }
  55447. function sample () {
  55448. var _value = 0;
  55449. function _set ( v ) {
  55450. _value = v;
  55451. }
  55452. return {
  55453. set: _set,
  55454. value: function () {
  55455. return _value;
  55456. }
  55457. };
  55458. }
  55459. function _perf ( idArg ) {
  55460. var id = idArg.toLowerCase();
  55461. if ( id === undefined ) id = 'default';
  55462. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  55463. var group = null;
  55464. if ( _settings && _settings.groups ) {
  55465. iterateKeys( _settings.groups, function ( j ) {
  55466. var g = _settings.groups[ parseInt( j, 10 ) ];
  55467. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  55468. group = g;
  55469. }
  55470. } );
  55471. }
  55472. var p = new PerfCounter( id, group );
  55473. _perfCounters[ id ] = p;
  55474. return p;
  55475. }
  55476. function _init () {
  55477. if ( _settings.plugins ) {
  55478. if ( !_settings.values ) _settings.values = {};
  55479. if ( !_settings.groups ) _settings.groups = [];
  55480. if ( !_settings.fractions ) _settings.fractions = [];
  55481. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  55482. _settings.plugins[ j ].attach( _perf );
  55483. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  55484. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  55485. } );
  55486. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  55487. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  55488. }
  55489. } else {
  55490. _settings.plugins = {};
  55491. }
  55492. _base = document.createElement( 'div' );
  55493. _base.className = 'rs-base';
  55494. _div = document.createElement( 'div' );
  55495. _div.className = 'rs-container';
  55496. _div.style.height = 'auto';
  55497. _base.appendChild( _div );
  55498. document.body.appendChild( _base );
  55499. if ( !_settings ) return;
  55500. if ( _settings.groups ) {
  55501. iterateKeys( _settings.groups, function ( j ) {
  55502. var g = _settings.groups[ parseInt( j, 10 ) ];
  55503. var div = document.createElement( 'div' );
  55504. div.className = 'rs-group';
  55505. g.div = div;
  55506. var h1 = document.createElement( 'h1' );
  55507. h1.textContent = g.caption;
  55508. h1.addEventListener( 'click', function ( e ) {
  55509. this.classList.toggle( 'hidden' );
  55510. e.preventDefault();
  55511. }.bind( div ) );
  55512. _div.appendChild( h1 );
  55513. _div.appendChild( div );
  55514. } );
  55515. }
  55516. if ( _settings.fractions ) {
  55517. iterateKeys( _settings.fractions, function ( j ) {
  55518. var f = _settings.fractions[ parseInt( j, 10 ) ];
  55519. var div = document.createElement( 'div' );
  55520. div.className = 'rs-fraction';
  55521. var legend = document.createElement( 'div' );
  55522. legend.className = 'rs-legend';
  55523. var h = 0;
  55524. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  55525. var p = document.createElement( 'p' );
  55526. p.textContent = _settings.fractions[ j ].steps[ k ];
  55527. p.style.color = _colours[ h ];
  55528. legend.appendChild( p );
  55529. h++;
  55530. } );
  55531. div.appendChild( legend );
  55532. div.style.height = h * _elHeight + 'px';
  55533. f.div = div;
  55534. var graph = new StackGraph( div, h );
  55535. f.graph = graph;
  55536. _div.appendChild( div );
  55537. } );
  55538. }
  55539. }
  55540. function _update () {
  55541. iterateKeys( _settings.plugins, function ( j ) {
  55542. _settings.plugins[ j ].update();
  55543. } );
  55544. iterateKeys( _perfCounters, function ( j ) {
  55545. _perfCounters[ j ].draw();
  55546. } );
  55547. if ( _settings && _settings.fractions ) {
  55548. iterateKeys( _settings.fractions, function ( j ) {
  55549. var f = _settings.fractions[ parseInt( j, 10 ) ];
  55550. var v = [];
  55551. var base = _perfCounters[ f.base.toLowerCase() ];
  55552. if ( base ) {
  55553. base = base.value();
  55554. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  55555. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  55556. var val = _perfCounters[ s ];
  55557. if ( val ) {
  55558. v.push( val.value() / base );
  55559. }
  55560. } );
  55561. }
  55562. f.graph.draw( v );
  55563. } );
  55564. }
  55565. /*if( _height != _div.clientHeight ) {
  55566. _height = _div.clientHeight;
  55567. _base.style.height = _height + 2 * _elHeight + 'px';
  55568. console.log( _base.clientHeight );
  55569. }*/
  55570. }
  55571. _init();
  55572. return function ( id ) {
  55573. if ( id ) return _perf( id );
  55574. return {
  55575. element: _base,
  55576. update: _update
  55577. };
  55578. };
  55579. }
  55580. if (typeof module === 'object') {
  55581. module.exports = window.rStats;
  55582. }
  55583. },{}],181:[function(_dereq_,module,exports){
  55584. /*
  55585. * Copyright 2015 Google Inc. All Rights Reserved.
  55586. * Licensed under the Apache License, Version 2.0 (the "License");
  55587. * you may not use this file except in compliance with the License.
  55588. * You may obtain a copy of the License at
  55589. *
  55590. * http://www.apache.org/licenses/LICENSE-2.0
  55591. *
  55592. * Unless required by applicable law or agreed to in writing, software
  55593. * distributed under the License is distributed on an "AS IS" BASIS,
  55594. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  55595. * See the License for the specific language governing permissions and
  55596. * limitations under the License.
  55597. */
  55598. var Util = {};
  55599. Util.base64 = function(mimeType, base64) {
  55600. return 'data:' + mimeType + ';base64,' + base64;
  55601. };
  55602. Util.isMobile = function() {
  55603. var check = false;
  55604. (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);
  55605. return check;
  55606. };
  55607. Util.isIOS = function() {
  55608. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  55609. };
  55610. Util.isIFrame = function() {
  55611. try {
  55612. return window.self !== window.top;
  55613. } catch (e) {
  55614. return true;
  55615. }
  55616. };
  55617. Util.appendQueryParameter = function(url, key, value) {
  55618. // Determine delimiter based on if the URL already GET parameters in it.
  55619. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  55620. url += delimiter + key + '=' + value;
  55621. return url;
  55622. };
  55623. // From http://goo.gl/4WX3tg
  55624. Util.getQueryParameter = function(name) {
  55625. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  55626. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  55627. results = regex.exec(location.search);
  55628. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  55629. };
  55630. Util.isLandscapeMode = function() {
  55631. return (window.orientation == 90 || window.orientation == -90);
  55632. };
  55633. module.exports = Util;
  55634. },{}],182:[function(_dereq_,module,exports){
  55635. /*
  55636. * Copyright 2015 Google Inc. All Rights Reserved.
  55637. * Licensed under the Apache License, Version 2.0 (the "License");
  55638. * you may not use this file except in compliance with the License.
  55639. * You may obtain a copy of the License at
  55640. *
  55641. * http://www.apache.org/licenses/LICENSE-2.0
  55642. *
  55643. * Unless required by applicable law or agreed to in writing, software
  55644. * distributed under the License is distributed on an "AS IS" BASIS,
  55645. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  55646. * See the License for the specific language governing permissions and
  55647. * limitations under the License.
  55648. */
  55649. var Util = _dereq_('./util.js');
  55650. /**
  55651. * Android and iOS compatible wakelock implementation.
  55652. *
  55653. * Refactored thanks to dkovalev@.
  55654. */
  55655. function AndroidWakeLock() {
  55656. var video = document.createElement('video');
  55657. video.addEventListener('ended', function() {
  55658. video.play();
  55659. });
  55660. this.request = function() {
  55661. if (video.paused) {
  55662. // Base64 version of videos_src/no-sleep-60s.webm.
  55663. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  55664. video.play();
  55665. }
  55666. };
  55667. this.release = function() {
  55668. video.pause();
  55669. video.src = '';
  55670. };
  55671. }
  55672. function iOSWakeLock() {
  55673. var timer = null;
  55674. this.request = function() {
  55675. if (!timer) {
  55676. timer = setInterval(function() {
  55677. window.location.href = '/';
  55678. setTimeout(window.stop, 0);
  55679. }, 15000);
  55680. }
  55681. }
  55682. this.release = function() {
  55683. if (timer) {
  55684. clearInterval(timer);
  55685. timer = null;
  55686. }
  55687. }
  55688. }
  55689. function getWakeLock() {
  55690. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  55691. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  55692. return iOSWakeLock;
  55693. } else {
  55694. return AndroidWakeLock;
  55695. }
  55696. }
  55697. module.exports = getWakeLock();
  55698. },{"./util.js":181}]},{},[148])(148)
  55699. });
  55700. //# sourceMappingURL=aframe-master.js.map