aframe-master.js 2.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189
  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. (function (process){
  3. /**
  4. * Tween.js - Licensed under the MIT license
  5. * https://github.com/tweenjs/tween.js
  6. * ----------------------------------------------
  7. *
  8. * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors.
  9. * Thank you all, you're awesome!
  10. */
  11. var _Group = function () {
  12. this._tweens = {};
  13. this._tweensAddedDuringUpdate = {};
  14. };
  15. _Group.prototype = {
  16. getAll: function () {
  17. return Object.keys(this._tweens).map(function (tweenId) {
  18. return this._tweens[tweenId];
  19. }.bind(this));
  20. },
  21. removeAll: function () {
  22. this._tweens = {};
  23. },
  24. add: function (tween) {
  25. this._tweens[tween.getId()] = tween;
  26. this._tweensAddedDuringUpdate[tween.getId()] = tween;
  27. },
  28. remove: function (tween) {
  29. delete this._tweens[tween.getId()];
  30. delete this._tweensAddedDuringUpdate[tween.getId()];
  31. },
  32. update: function (time, preserve) {
  33. var tweenIds = Object.keys(this._tweens);
  34. if (tweenIds.length === 0) {
  35. return false;
  36. }
  37. time = time !== undefined ? time : TWEEN.now();
  38. // Tweens are updated in "batches". If you add a new tween during an update, then the
  39. // new tween will be updated in the next batch.
  40. // If you remove a tween during an update, it will normally still be updated. However,
  41. // if the removed tween was added during the current batch, then it will not be updated.
  42. while (tweenIds.length > 0) {
  43. this._tweensAddedDuringUpdate = {};
  44. for (var i = 0; i < tweenIds.length; i++) {
  45. if (this._tweens[tweenIds[i]].update(time) === false) {
  46. this._tweens[tweenIds[i]]._isPlaying = false;
  47. if (!preserve) {
  48. delete this._tweens[tweenIds[i]];
  49. }
  50. }
  51. }
  52. tweenIds = Object.keys(this._tweensAddedDuringUpdate);
  53. }
  54. return true;
  55. }
  56. };
  57. var TWEEN = new _Group();
  58. TWEEN.Group = _Group;
  59. TWEEN._nextId = 0;
  60. TWEEN.nextId = function () {
  61. return TWEEN._nextId++;
  62. };
  63. // Include a performance.now polyfill.
  64. // In node.js, use process.hrtime.
  65. if (typeof (window) === 'undefined' && typeof (process) !== 'undefined') {
  66. TWEEN.now = function () {
  67. var time = process.hrtime();
  68. // Convert [seconds, nanoseconds] to milliseconds.
  69. return time[0] * 1000 + time[1] / 1000000;
  70. };
  71. }
  72. // In a browser, use window.performance.now if it is available.
  73. else if (typeof (window) !== 'undefined' &&
  74. window.performance !== undefined &&
  75. window.performance.now !== undefined) {
  76. // This must be bound, because directly assigning this function
  77. // leads to an invocation exception in Chrome.
  78. TWEEN.now = window.performance.now.bind(window.performance);
  79. }
  80. // Use Date.now if it is available.
  81. else if (Date.now !== undefined) {
  82. TWEEN.now = Date.now;
  83. }
  84. // Otherwise, use 'new Date().getTime()'.
  85. else {
  86. TWEEN.now = function () {
  87. return new Date().getTime();
  88. };
  89. }
  90. TWEEN.Tween = function (object, group) {
  91. this._object = object;
  92. this._valuesStart = {};
  93. this._valuesEnd = {};
  94. this._valuesStartRepeat = {};
  95. this._duration = 1000;
  96. this._repeat = 0;
  97. this._repeatDelayTime = undefined;
  98. this._yoyo = false;
  99. this._isPlaying = false;
  100. this._reversed = false;
  101. this._delayTime = 0;
  102. this._startTime = null;
  103. this._easingFunction = TWEEN.Easing.Linear.None;
  104. this._interpolationFunction = TWEEN.Interpolation.Linear;
  105. this._chainedTweens = [];
  106. this._onStartCallback = null;
  107. this._onStartCallbackFired = false;
  108. this._onUpdateCallback = null;
  109. this._onCompleteCallback = null;
  110. this._onStopCallback = null;
  111. this._group = group || TWEEN;
  112. this._id = TWEEN.nextId();
  113. };
  114. TWEEN.Tween.prototype = {
  115. getId: function getId() {
  116. return this._id;
  117. },
  118. isPlaying: function isPlaying() {
  119. return this._isPlaying;
  120. },
  121. to: function to(properties, duration) {
  122. this._valuesEnd = properties;
  123. if (duration !== undefined) {
  124. this._duration = duration;
  125. }
  126. return this;
  127. },
  128. start: function start(time) {
  129. this._group.add(this);
  130. this._isPlaying = true;
  131. this._onStartCallbackFired = false;
  132. this._startTime = time !== undefined ? time : TWEEN.now();
  133. this._startTime += this._delayTime;
  134. for (var property in this._valuesEnd) {
  135. // Check if an Array was provided as property value
  136. if (this._valuesEnd[property] instanceof Array) {
  137. if (this._valuesEnd[property].length === 0) {
  138. continue;
  139. }
  140. // Create a local copy of the Array with the start value at the front
  141. this._valuesEnd[property] = [this._object[property]].concat(this._valuesEnd[property]);
  142. }
  143. // If `to()` specifies a property that doesn't exist in the source object,
  144. // we should not set that property in the object
  145. if (this._object[property] === undefined) {
  146. continue;
  147. }
  148. // Save the starting value.
  149. this._valuesStart[property] = this._object[property];
  150. if ((this._valuesStart[property] instanceof Array) === false) {
  151. this._valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
  152. }
  153. this._valuesStartRepeat[property] = this._valuesStart[property] || 0;
  154. }
  155. return this;
  156. },
  157. stop: function stop() {
  158. if (!this._isPlaying) {
  159. return this;
  160. }
  161. this._group.remove(this);
  162. this._isPlaying = false;
  163. if (this._onStopCallback !== null) {
  164. this._onStopCallback.call(this._object, this._object);
  165. }
  166. this.stopChainedTweens();
  167. return this;
  168. },
  169. end: function end() {
  170. this.update(this._startTime + this._duration);
  171. return this;
  172. },
  173. stopChainedTweens: function stopChainedTweens() {
  174. for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
  175. this._chainedTweens[i].stop();
  176. }
  177. },
  178. delay: function delay(amount) {
  179. this._delayTime = amount;
  180. return this;
  181. },
  182. repeat: function repeat(times) {
  183. this._repeat = times;
  184. return this;
  185. },
  186. repeatDelay: function repeatDelay(amount) {
  187. this._repeatDelayTime = amount;
  188. return this;
  189. },
  190. yoyo: function yoyo(yoyo) {
  191. this._yoyo = yoyo;
  192. return this;
  193. },
  194. easing: function easing(easing) {
  195. this._easingFunction = easing;
  196. return this;
  197. },
  198. interpolation: function interpolation(interpolation) {
  199. this._interpolationFunction = interpolation;
  200. return this;
  201. },
  202. chain: function chain() {
  203. this._chainedTweens = arguments;
  204. return this;
  205. },
  206. onStart: function onStart(callback) {
  207. this._onStartCallback = callback;
  208. return this;
  209. },
  210. onUpdate: function onUpdate(callback) {
  211. this._onUpdateCallback = callback;
  212. return this;
  213. },
  214. onComplete: function onComplete(callback) {
  215. this._onCompleteCallback = callback;
  216. return this;
  217. },
  218. onStop: function onStop(callback) {
  219. this._onStopCallback = callback;
  220. return this;
  221. },
  222. update: function update(time) {
  223. var property;
  224. var elapsed;
  225. var value;
  226. if (time < this._startTime) {
  227. return true;
  228. }
  229. if (this._onStartCallbackFired === false) {
  230. if (this._onStartCallback !== null) {
  231. this._onStartCallback.call(this._object, this._object);
  232. }
  233. this._onStartCallbackFired = true;
  234. }
  235. elapsed = (time - this._startTime) / this._duration;
  236. elapsed = elapsed > 1 ? 1 : elapsed;
  237. value = this._easingFunction(elapsed);
  238. for (property in this._valuesEnd) {
  239. // Don't update properties that do not exist in the source object
  240. if (this._valuesStart[property] === undefined) {
  241. continue;
  242. }
  243. var start = this._valuesStart[property] || 0;
  244. var end = this._valuesEnd[property];
  245. if (end instanceof Array) {
  246. this._object[property] = this._interpolationFunction(end, value);
  247. } else {
  248. // Parses relative end values with start as base (e.g.: +10, -3)
  249. if (typeof (end) === 'string') {
  250. if (end.charAt(0) === '+' || end.charAt(0) === '-') {
  251. end = start + parseFloat(end);
  252. } else {
  253. end = parseFloat(end);
  254. }
  255. }
  256. // Protect against non numeric properties.
  257. if (typeof (end) === 'number') {
  258. this._object[property] = start + (end - start) * value;
  259. }
  260. }
  261. }
  262. if (this._onUpdateCallback !== null) {
  263. this._onUpdateCallback.call(this._object, value);
  264. }
  265. if (elapsed === 1) {
  266. if (this._repeat > 0) {
  267. if (isFinite(this._repeat)) {
  268. this._repeat--;
  269. }
  270. // Reassign starting values, restart by making startTime = now
  271. for (property in this._valuesStartRepeat) {
  272. if (typeof (this._valuesEnd[property]) === 'string') {
  273. this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property]);
  274. }
  275. if (this._yoyo) {
  276. var tmp = this._valuesStartRepeat[property];
  277. this._valuesStartRepeat[property] = this._valuesEnd[property];
  278. this._valuesEnd[property] = tmp;
  279. }
  280. this._valuesStart[property] = this._valuesStartRepeat[property];
  281. }
  282. if (this._yoyo) {
  283. this._reversed = !this._reversed;
  284. }
  285. if (this._repeatDelayTime !== undefined) {
  286. this._startTime = time + this._repeatDelayTime;
  287. } else {
  288. this._startTime = time + this._delayTime;
  289. }
  290. return true;
  291. } else {
  292. if (this._onCompleteCallback !== null) {
  293. this._onCompleteCallback.call(this._object, this._object);
  294. }
  295. for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
  296. // Make the chained tweens start exactly at the time they should,
  297. // even if the `update()` method was called way past the duration of the tween
  298. this._chainedTweens[i].start(this._startTime + this._duration);
  299. }
  300. return false;
  301. }
  302. }
  303. return true;
  304. }
  305. };
  306. TWEEN.Easing = {
  307. Linear: {
  308. None: function (k) {
  309. return k;
  310. }
  311. },
  312. Quadratic: {
  313. In: function (k) {
  314. return k * k;
  315. },
  316. Out: function (k) {
  317. return k * (2 - k);
  318. },
  319. InOut: function (k) {
  320. if ((k *= 2) < 1) {
  321. return 0.5 * k * k;
  322. }
  323. return - 0.5 * (--k * (k - 2) - 1);
  324. }
  325. },
  326. Cubic: {
  327. In: function (k) {
  328. return k * k * k;
  329. },
  330. Out: function (k) {
  331. return --k * k * k + 1;
  332. },
  333. InOut: function (k) {
  334. if ((k *= 2) < 1) {
  335. return 0.5 * k * k * k;
  336. }
  337. return 0.5 * ((k -= 2) * k * k + 2);
  338. }
  339. },
  340. Quartic: {
  341. In: function (k) {
  342. return k * k * k * k;
  343. },
  344. Out: function (k) {
  345. return 1 - (--k * k * k * k);
  346. },
  347. InOut: function (k) {
  348. if ((k *= 2) < 1) {
  349. return 0.5 * k * k * k * k;
  350. }
  351. return - 0.5 * ((k -= 2) * k * k * k - 2);
  352. }
  353. },
  354. Quintic: {
  355. In: function (k) {
  356. return k * k * k * k * k;
  357. },
  358. Out: function (k) {
  359. return --k * k * k * k * k + 1;
  360. },
  361. InOut: function (k) {
  362. if ((k *= 2) < 1) {
  363. return 0.5 * k * k * k * k * k;
  364. }
  365. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  366. }
  367. },
  368. Sinusoidal: {
  369. In: function (k) {
  370. return 1 - Math.cos(k * Math.PI / 2);
  371. },
  372. Out: function (k) {
  373. return Math.sin(k * Math.PI / 2);
  374. },
  375. InOut: function (k) {
  376. return 0.5 * (1 - Math.cos(Math.PI * k));
  377. }
  378. },
  379. Exponential: {
  380. In: function (k) {
  381. return k === 0 ? 0 : Math.pow(1024, k - 1);
  382. },
  383. Out: function (k) {
  384. return k === 1 ? 1 : 1 - Math.pow(2, - 10 * k);
  385. },
  386. InOut: function (k) {
  387. if (k === 0) {
  388. return 0;
  389. }
  390. if (k === 1) {
  391. return 1;
  392. }
  393. if ((k *= 2) < 1) {
  394. return 0.5 * Math.pow(1024, k - 1);
  395. }
  396. return 0.5 * (- Math.pow(2, - 10 * (k - 1)) + 2);
  397. }
  398. },
  399. Circular: {
  400. In: function (k) {
  401. return 1 - Math.sqrt(1 - k * k);
  402. },
  403. Out: function (k) {
  404. return Math.sqrt(1 - (--k * k));
  405. },
  406. InOut: function (k) {
  407. if ((k *= 2) < 1) {
  408. return - 0.5 * (Math.sqrt(1 - k * k) - 1);
  409. }
  410. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  411. }
  412. },
  413. Elastic: {
  414. In: function (k) {
  415. if (k === 0) {
  416. return 0;
  417. }
  418. if (k === 1) {
  419. return 1;
  420. }
  421. return -Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);
  422. },
  423. Out: function (k) {
  424. if (k === 0) {
  425. return 0;
  426. }
  427. if (k === 1) {
  428. return 1;
  429. }
  430. return Math.pow(2, -10 * k) * Math.sin((k - 0.1) * 5 * Math.PI) + 1;
  431. },
  432. InOut: function (k) {
  433. if (k === 0) {
  434. return 0;
  435. }
  436. if (k === 1) {
  437. return 1;
  438. }
  439. k *= 2;
  440. if (k < 1) {
  441. return -0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);
  442. }
  443. return 0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1;
  444. }
  445. },
  446. Back: {
  447. In: function (k) {
  448. var s = 1.70158;
  449. return k * k * ((s + 1) * k - s);
  450. },
  451. Out: function (k) {
  452. var s = 1.70158;
  453. return --k * k * ((s + 1) * k + s) + 1;
  454. },
  455. InOut: function (k) {
  456. var s = 1.70158 * 1.525;
  457. if ((k *= 2) < 1) {
  458. return 0.5 * (k * k * ((s + 1) * k - s));
  459. }
  460. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  461. }
  462. },
  463. Bounce: {
  464. In: function (k) {
  465. return 1 - TWEEN.Easing.Bounce.Out(1 - k);
  466. },
  467. Out: function (k) {
  468. if (k < (1 / 2.75)) {
  469. return 7.5625 * k * k;
  470. } else if (k < (2 / 2.75)) {
  471. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  472. } else if (k < (2.5 / 2.75)) {
  473. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  474. } else {
  475. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  476. }
  477. },
  478. InOut: function (k) {
  479. if (k < 0.5) {
  480. return TWEEN.Easing.Bounce.In(k * 2) * 0.5;
  481. }
  482. return TWEEN.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5;
  483. }
  484. }
  485. };
  486. TWEEN.Interpolation = {
  487. Linear: function (v, k) {
  488. var m = v.length - 1;
  489. var f = m * k;
  490. var i = Math.floor(f);
  491. var fn = TWEEN.Interpolation.Utils.Linear;
  492. if (k < 0) {
  493. return fn(v[0], v[1], f);
  494. }
  495. if (k > 1) {
  496. return fn(v[m], v[m - 1], m - f);
  497. }
  498. return fn(v[i], v[i + 1 > m ? m : i + 1], f - i);
  499. },
  500. Bezier: function (v, k) {
  501. var b = 0;
  502. var n = v.length - 1;
  503. var pw = Math.pow;
  504. var bn = TWEEN.Interpolation.Utils.Bernstein;
  505. for (var i = 0; i <= n; i++) {
  506. b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i);
  507. }
  508. return b;
  509. },
  510. CatmullRom: function (v, k) {
  511. var m = v.length - 1;
  512. var f = m * k;
  513. var i = Math.floor(f);
  514. var fn = TWEEN.Interpolation.Utils.CatmullRom;
  515. if (v[0] === v[m]) {
  516. if (k < 0) {
  517. i = Math.floor(f = m * (1 + k));
  518. }
  519. return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
  520. } else {
  521. if (k < 0) {
  522. return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]);
  523. }
  524. if (k > 1) {
  525. return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
  526. }
  527. return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);
  528. }
  529. },
  530. Utils: {
  531. Linear: function (p0, p1, t) {
  532. return (p1 - p0) * t + p0;
  533. },
  534. Bernstein: function (n, i) {
  535. var fc = TWEEN.Interpolation.Utils.Factorial;
  536. return fc(n) / fc(i) / fc(n - i);
  537. },
  538. Factorial: (function () {
  539. var a = [1];
  540. return function (n) {
  541. var s = 1;
  542. if (a[n]) {
  543. return a[n];
  544. }
  545. for (var i = n; i > 1; i--) {
  546. s *= i;
  547. }
  548. a[n] = s;
  549. return s;
  550. };
  551. })(),
  552. CatmullRom: function (p0, p1, p2, p3, t) {
  553. var v0 = (p2 - p0) * 0.5;
  554. var v1 = (p3 - p1) * 0.5;
  555. var t2 = t * t;
  556. var t3 = t * t2;
  557. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (- 3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  558. }
  559. }
  560. };
  561. // UMD (Universal Module Definition)
  562. (function (root) {
  563. if (typeof define === 'function' && define.amd) {
  564. // AMD
  565. define([], function () {
  566. return TWEEN;
  567. });
  568. } else if (typeof module !== 'undefined' && typeof exports === 'object') {
  569. // Node.js
  570. module.exports = TWEEN;
  571. } else if (root !== undefined) {
  572. // Global variable
  573. root.TWEEN = TWEEN;
  574. }
  575. })(this);
  576. }).call(this,_dereq_('_process'))
  577. },{"_process":32}],2:[function(_dereq_,module,exports){
  578. var str = Object.prototype.toString
  579. module.exports = anArray
  580. function anArray(arr) {
  581. return (
  582. arr.BYTES_PER_ELEMENT
  583. && str.call(arr.buffer) === '[object ArrayBuffer]'
  584. || Array.isArray(arr)
  585. )
  586. }
  587. },{}],3:[function(_dereq_,module,exports){
  588. module.exports = function numtype(num, def) {
  589. return typeof num === 'number'
  590. ? num
  591. : (typeof def === 'number' ? def : 0)
  592. }
  593. },{}],4:[function(_dereq_,module,exports){
  594. 'use strict'
  595. exports.byteLength = byteLength
  596. exports.toByteArray = toByteArray
  597. exports.fromByteArray = fromByteArray
  598. var lookup = []
  599. var revLookup = []
  600. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  601. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  602. for (var i = 0, len = code.length; i < len; ++i) {
  603. lookup[i] = code[i]
  604. revLookup[code.charCodeAt(i)] = i
  605. }
  606. // Support decoding URL-safe base64 strings, as Node.js does.
  607. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  608. revLookup['-'.charCodeAt(0)] = 62
  609. revLookup['_'.charCodeAt(0)] = 63
  610. function placeHoldersCount (b64) {
  611. var len = b64.length
  612. if (len % 4 > 0) {
  613. throw new Error('Invalid string. Length must be a multiple of 4')
  614. }
  615. // the number of equal signs (place holders)
  616. // if there are two placeholders, than the two characters before it
  617. // represent one byte
  618. // if there is only one, then the three characters before it represent 2 bytes
  619. // this is just a cheap hack to not do indexOf twice
  620. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  621. }
  622. function byteLength (b64) {
  623. // base64 is 4/3 + up to two characters of the original data
  624. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  625. }
  626. function toByteArray (b64) {
  627. var i, l, tmp, placeHolders, arr
  628. var len = b64.length
  629. placeHolders = placeHoldersCount(b64)
  630. arr = new Arr((len * 3 / 4) - placeHolders)
  631. // if there are placeholders, only get up to the last complete 4 chars
  632. l = placeHolders > 0 ? len - 4 : len
  633. var L = 0
  634. for (i = 0; i < l; i += 4) {
  635. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  636. arr[L++] = (tmp >> 16) & 0xFF
  637. arr[L++] = (tmp >> 8) & 0xFF
  638. arr[L++] = tmp & 0xFF
  639. }
  640. if (placeHolders === 2) {
  641. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  642. arr[L++] = tmp & 0xFF
  643. } else if (placeHolders === 1) {
  644. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  645. arr[L++] = (tmp >> 8) & 0xFF
  646. arr[L++] = tmp & 0xFF
  647. }
  648. return arr
  649. }
  650. function tripletToBase64 (num) {
  651. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  652. }
  653. function encodeChunk (uint8, start, end) {
  654. var tmp
  655. var output = []
  656. for (var i = start; i < end; i += 3) {
  657. tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF)
  658. output.push(tripletToBase64(tmp))
  659. }
  660. return output.join('')
  661. }
  662. function fromByteArray (uint8) {
  663. var tmp
  664. var len = uint8.length
  665. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  666. var output = ''
  667. var parts = []
  668. var maxChunkLength = 16383 // must be multiple of 3
  669. // go through the array every three bytes, we'll deal with trailing stuff later
  670. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  671. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  672. }
  673. // pad the end with zeros, but make sure to not forget the extra bytes
  674. if (extraBytes === 1) {
  675. tmp = uint8[len - 1]
  676. output += lookup[tmp >> 2]
  677. output += lookup[(tmp << 4) & 0x3F]
  678. output += '=='
  679. } else if (extraBytes === 2) {
  680. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  681. output += lookup[tmp >> 10]
  682. output += lookup[(tmp >> 4) & 0x3F]
  683. output += lookup[(tmp << 2) & 0x3F]
  684. output += '='
  685. }
  686. parts.push(output)
  687. return parts.join('')
  688. }
  689. },{}],5:[function(_dereq_,module,exports){
  690. 'use strict';
  691. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  692. module.exports = {
  693. // Create a <link> tag with optional data attributes
  694. createLink: function(href, attributes) {
  695. var head = document.head || document.getElementsByTagName('head')[0];
  696. var link = document.createElement('link');
  697. link.href = href;
  698. link.rel = 'stylesheet';
  699. for (var key in attributes) {
  700. if ( ! attributes.hasOwnProperty(key)) {
  701. continue;
  702. }
  703. var value = attributes[key];
  704. link.setAttribute('data-' + key, value);
  705. }
  706. head.appendChild(link);
  707. },
  708. // Create a <style> tag with optional data attributes
  709. createStyle: function(cssText, attributes) {
  710. var head = document.head || document.getElementsByTagName('head')[0],
  711. style = document.createElement('style');
  712. style.type = 'text/css';
  713. for (var key in attributes) {
  714. if ( ! attributes.hasOwnProperty(key)) {
  715. continue;
  716. }
  717. var value = attributes[key];
  718. style.setAttribute('data-' + key, value);
  719. }
  720. if (style.sheet) { // for jsdom and IE9+
  721. style.innerHTML = cssText;
  722. style.sheet.cssText = cssText;
  723. head.appendChild(style);
  724. } else if (style.styleSheet) { // for IE8 and below
  725. head.appendChild(style);
  726. style.styleSheet.cssText = cssText;
  727. } else { // for Chrome, Firefox, and Safari
  728. style.appendChild(document.createTextNode(cssText));
  729. head.appendChild(style);
  730. }
  731. }
  732. };
  733. },{}],6:[function(_dereq_,module,exports){
  734. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  735. module.exports = function (a, b) {
  736. if (!Buffer.isBuffer(a)) return undefined;
  737. if (!Buffer.isBuffer(b)) return undefined;
  738. if (typeof a.equals === 'function') return a.equals(b);
  739. if (a.length !== b.length) return false;
  740. for (var i = 0; i < a.length; i++) {
  741. if (a[i] !== b[i]) return false;
  742. }
  743. return true;
  744. };
  745. },{"buffer":7}],7:[function(_dereq_,module,exports){
  746. (function (global){
  747. /*!
  748. * The buffer module from node.js, for the browser.
  749. *
  750. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  751. * @license MIT
  752. */
  753. /* eslint-disable no-proto */
  754. 'use strict'
  755. var base64 = _dereq_('base64-js')
  756. var ieee754 = _dereq_('ieee754')
  757. var isArray = _dereq_('isarray')
  758. exports.Buffer = Buffer
  759. exports.SlowBuffer = SlowBuffer
  760. exports.INSPECT_MAX_BYTES = 50
  761. /**
  762. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  763. * === true Use Uint8Array implementation (fastest)
  764. * === false Use Object implementation (most compatible, even IE6)
  765. *
  766. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  767. * Opera 11.6+, iOS 4.2+.
  768. *
  769. * Due to various browser bugs, sometimes the Object implementation will be used even
  770. * when the browser supports typed arrays.
  771. *
  772. * Note:
  773. *
  774. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  775. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  776. *
  777. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  778. *
  779. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  780. * incorrect length in some situations.
  781. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  782. * get the Object implementation, which is slower but behaves correctly.
  783. */
  784. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  785. ? global.TYPED_ARRAY_SUPPORT
  786. : typedArraySupport()
  787. /*
  788. * Export kMaxLength after typed array support is determined.
  789. */
  790. exports.kMaxLength = kMaxLength()
  791. function typedArraySupport () {
  792. try {
  793. var arr = new Uint8Array(1)
  794. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  795. return arr.foo() === 42 && // typed array instances can be augmented
  796. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  797. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  798. } catch (e) {
  799. return false
  800. }
  801. }
  802. function kMaxLength () {
  803. return Buffer.TYPED_ARRAY_SUPPORT
  804. ? 0x7fffffff
  805. : 0x3fffffff
  806. }
  807. function createBuffer (that, length) {
  808. if (kMaxLength() < length) {
  809. throw new RangeError('Invalid typed array length')
  810. }
  811. if (Buffer.TYPED_ARRAY_SUPPORT) {
  812. // Return an augmented `Uint8Array` instance, for best performance
  813. that = new Uint8Array(length)
  814. that.__proto__ = Buffer.prototype
  815. } else {
  816. // Fallback: Return an object instance of the Buffer class
  817. if (that === null) {
  818. that = new Buffer(length)
  819. }
  820. that.length = length
  821. }
  822. return that
  823. }
  824. /**
  825. * The Buffer constructor returns instances of `Uint8Array` that have their
  826. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  827. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  828. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  829. * returns a single octet.
  830. *
  831. * The `Uint8Array` prototype remains unmodified.
  832. */
  833. function Buffer (arg, encodingOrOffset, length) {
  834. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  835. return new Buffer(arg, encodingOrOffset, length)
  836. }
  837. // Common case.
  838. if (typeof arg === 'number') {
  839. if (typeof encodingOrOffset === 'string') {
  840. throw new Error(
  841. 'If encoding is specified then the first argument must be a string'
  842. )
  843. }
  844. return allocUnsafe(this, arg)
  845. }
  846. return from(this, arg, encodingOrOffset, length)
  847. }
  848. Buffer.poolSize = 8192 // not used by this implementation
  849. // TODO: Legacy, not needed anymore. Remove in next major version.
  850. Buffer._augment = function (arr) {
  851. arr.__proto__ = Buffer.prototype
  852. return arr
  853. }
  854. function from (that, value, encodingOrOffset, length) {
  855. if (typeof value === 'number') {
  856. throw new TypeError('"value" argument must not be a number')
  857. }
  858. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  859. return fromArrayBuffer(that, value, encodingOrOffset, length)
  860. }
  861. if (typeof value === 'string') {
  862. return fromString(that, value, encodingOrOffset)
  863. }
  864. return fromObject(that, value)
  865. }
  866. /**
  867. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  868. * if value is a number.
  869. * Buffer.from(str[, encoding])
  870. * Buffer.from(array)
  871. * Buffer.from(buffer)
  872. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  873. **/
  874. Buffer.from = function (value, encodingOrOffset, length) {
  875. return from(null, value, encodingOrOffset, length)
  876. }
  877. if (Buffer.TYPED_ARRAY_SUPPORT) {
  878. Buffer.prototype.__proto__ = Uint8Array.prototype
  879. Buffer.__proto__ = Uint8Array
  880. if (typeof Symbol !== 'undefined' && Symbol.species &&
  881. Buffer[Symbol.species] === Buffer) {
  882. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  883. Object.defineProperty(Buffer, Symbol.species, {
  884. value: null,
  885. configurable: true
  886. })
  887. }
  888. }
  889. function assertSize (size) {
  890. if (typeof size !== 'number') {
  891. throw new TypeError('"size" argument must be a number')
  892. } else if (size < 0) {
  893. throw new RangeError('"size" argument must not be negative')
  894. }
  895. }
  896. function alloc (that, size, fill, encoding) {
  897. assertSize(size)
  898. if (size <= 0) {
  899. return createBuffer(that, size)
  900. }
  901. if (fill !== undefined) {
  902. // Only pay attention to encoding if it's a string. This
  903. // prevents accidentally sending in a number that would
  904. // be interpretted as a start offset.
  905. return typeof encoding === 'string'
  906. ? createBuffer(that, size).fill(fill, encoding)
  907. : createBuffer(that, size).fill(fill)
  908. }
  909. return createBuffer(that, size)
  910. }
  911. /**
  912. * Creates a new filled Buffer instance.
  913. * alloc(size[, fill[, encoding]])
  914. **/
  915. Buffer.alloc = function (size, fill, encoding) {
  916. return alloc(null, size, fill, encoding)
  917. }
  918. function allocUnsafe (that, size) {
  919. assertSize(size)
  920. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  921. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  922. for (var i = 0; i < size; ++i) {
  923. that[i] = 0
  924. }
  925. }
  926. return that
  927. }
  928. /**
  929. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  930. * */
  931. Buffer.allocUnsafe = function (size) {
  932. return allocUnsafe(null, size)
  933. }
  934. /**
  935. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  936. */
  937. Buffer.allocUnsafeSlow = function (size) {
  938. return allocUnsafe(null, size)
  939. }
  940. function fromString (that, string, encoding) {
  941. if (typeof encoding !== 'string' || encoding === '') {
  942. encoding = 'utf8'
  943. }
  944. if (!Buffer.isEncoding(encoding)) {
  945. throw new TypeError('"encoding" must be a valid string encoding')
  946. }
  947. var length = byteLength(string, encoding) | 0
  948. that = createBuffer(that, length)
  949. var actual = that.write(string, encoding)
  950. if (actual !== length) {
  951. // Writing a hex string, for example, that contains invalid characters will
  952. // cause everything after the first invalid character to be ignored. (e.g.
  953. // 'abxxcd' will be treated as 'ab')
  954. that = that.slice(0, actual)
  955. }
  956. return that
  957. }
  958. function fromArrayLike (that, array) {
  959. var length = array.length < 0 ? 0 : checked(array.length) | 0
  960. that = createBuffer(that, length)
  961. for (var i = 0; i < length; i += 1) {
  962. that[i] = array[i] & 255
  963. }
  964. return that
  965. }
  966. function fromArrayBuffer (that, array, byteOffset, length) {
  967. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  968. if (byteOffset < 0 || array.byteLength < byteOffset) {
  969. throw new RangeError('\'offset\' is out of bounds')
  970. }
  971. if (array.byteLength < byteOffset + (length || 0)) {
  972. throw new RangeError('\'length\' is out of bounds')
  973. }
  974. if (byteOffset === undefined && length === undefined) {
  975. array = new Uint8Array(array)
  976. } else if (length === undefined) {
  977. array = new Uint8Array(array, byteOffset)
  978. } else {
  979. array = new Uint8Array(array, byteOffset, length)
  980. }
  981. if (Buffer.TYPED_ARRAY_SUPPORT) {
  982. // Return an augmented `Uint8Array` instance, for best performance
  983. that = array
  984. that.__proto__ = Buffer.prototype
  985. } else {
  986. // Fallback: Return an object instance of the Buffer class
  987. that = fromArrayLike(that, array)
  988. }
  989. return that
  990. }
  991. function fromObject (that, obj) {
  992. if (Buffer.isBuffer(obj)) {
  993. var len = checked(obj.length) | 0
  994. that = createBuffer(that, len)
  995. if (that.length === 0) {
  996. return that
  997. }
  998. obj.copy(that, 0, 0, len)
  999. return that
  1000. }
  1001. if (obj) {
  1002. if ((typeof ArrayBuffer !== 'undefined' &&
  1003. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  1004. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  1005. return createBuffer(that, 0)
  1006. }
  1007. return fromArrayLike(that, obj)
  1008. }
  1009. if (obj.type === 'Buffer' && isArray(obj.data)) {
  1010. return fromArrayLike(that, obj.data)
  1011. }
  1012. }
  1013. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  1014. }
  1015. function checked (length) {
  1016. // Note: cannot use `length < kMaxLength()` here because that fails when
  1017. // length is NaN (which is otherwise coerced to zero.)
  1018. if (length >= kMaxLength()) {
  1019. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  1020. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  1021. }
  1022. return length | 0
  1023. }
  1024. function SlowBuffer (length) {
  1025. if (+length != length) { // eslint-disable-line eqeqeq
  1026. length = 0
  1027. }
  1028. return Buffer.alloc(+length)
  1029. }
  1030. Buffer.isBuffer = function isBuffer (b) {
  1031. return !!(b != null && b._isBuffer)
  1032. }
  1033. Buffer.compare = function compare (a, b) {
  1034. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  1035. throw new TypeError('Arguments must be Buffers')
  1036. }
  1037. if (a === b) return 0
  1038. var x = a.length
  1039. var y = b.length
  1040. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  1041. if (a[i] !== b[i]) {
  1042. x = a[i]
  1043. y = b[i]
  1044. break
  1045. }
  1046. }
  1047. if (x < y) return -1
  1048. if (y < x) return 1
  1049. return 0
  1050. }
  1051. Buffer.isEncoding = function isEncoding (encoding) {
  1052. switch (String(encoding).toLowerCase()) {
  1053. case 'hex':
  1054. case 'utf8':
  1055. case 'utf-8':
  1056. case 'ascii':
  1057. case 'latin1':
  1058. case 'binary':
  1059. case 'base64':
  1060. case 'ucs2':
  1061. case 'ucs-2':
  1062. case 'utf16le':
  1063. case 'utf-16le':
  1064. return true
  1065. default:
  1066. return false
  1067. }
  1068. }
  1069. Buffer.concat = function concat (list, length) {
  1070. if (!isArray(list)) {
  1071. throw new TypeError('"list" argument must be an Array of Buffers')
  1072. }
  1073. if (list.length === 0) {
  1074. return Buffer.alloc(0)
  1075. }
  1076. var i
  1077. if (length === undefined) {
  1078. length = 0
  1079. for (i = 0; i < list.length; ++i) {
  1080. length += list[i].length
  1081. }
  1082. }
  1083. var buffer = Buffer.allocUnsafe(length)
  1084. var pos = 0
  1085. for (i = 0; i < list.length; ++i) {
  1086. var buf = list[i]
  1087. if (!Buffer.isBuffer(buf)) {
  1088. throw new TypeError('"list" argument must be an Array of Buffers')
  1089. }
  1090. buf.copy(buffer, pos)
  1091. pos += buf.length
  1092. }
  1093. return buffer
  1094. }
  1095. function byteLength (string, encoding) {
  1096. if (Buffer.isBuffer(string)) {
  1097. return string.length
  1098. }
  1099. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  1100. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  1101. return string.byteLength
  1102. }
  1103. if (typeof string !== 'string') {
  1104. string = '' + string
  1105. }
  1106. var len = string.length
  1107. if (len === 0) return 0
  1108. // Use a for loop to avoid recursion
  1109. var loweredCase = false
  1110. for (;;) {
  1111. switch (encoding) {
  1112. case 'ascii':
  1113. case 'latin1':
  1114. case 'binary':
  1115. return len
  1116. case 'utf8':
  1117. case 'utf-8':
  1118. case undefined:
  1119. return utf8ToBytes(string).length
  1120. case 'ucs2':
  1121. case 'ucs-2':
  1122. case 'utf16le':
  1123. case 'utf-16le':
  1124. return len * 2
  1125. case 'hex':
  1126. return len >>> 1
  1127. case 'base64':
  1128. return base64ToBytes(string).length
  1129. default:
  1130. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  1131. encoding = ('' + encoding).toLowerCase()
  1132. loweredCase = true
  1133. }
  1134. }
  1135. }
  1136. Buffer.byteLength = byteLength
  1137. function slowToString (encoding, start, end) {
  1138. var loweredCase = false
  1139. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  1140. // property of a typed array.
  1141. // This behaves neither like String nor Uint8Array in that we set start/end
  1142. // to their upper/lower bounds if the value passed is out of range.
  1143. // undefined is handled specially as per ECMA-262 6th Edition,
  1144. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  1145. if (start === undefined || start < 0) {
  1146. start = 0
  1147. }
  1148. // Return early if start > this.length. Done here to prevent potential uint32
  1149. // coercion fail below.
  1150. if (start > this.length) {
  1151. return ''
  1152. }
  1153. if (end === undefined || end > this.length) {
  1154. end = this.length
  1155. }
  1156. if (end <= 0) {
  1157. return ''
  1158. }
  1159. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  1160. end >>>= 0
  1161. start >>>= 0
  1162. if (end <= start) {
  1163. return ''
  1164. }
  1165. if (!encoding) encoding = 'utf8'
  1166. while (true) {
  1167. switch (encoding) {
  1168. case 'hex':
  1169. return hexSlice(this, start, end)
  1170. case 'utf8':
  1171. case 'utf-8':
  1172. return utf8Slice(this, start, end)
  1173. case 'ascii':
  1174. return asciiSlice(this, start, end)
  1175. case 'latin1':
  1176. case 'binary':
  1177. return latin1Slice(this, start, end)
  1178. case 'base64':
  1179. return base64Slice(this, start, end)
  1180. case 'ucs2':
  1181. case 'ucs-2':
  1182. case 'utf16le':
  1183. case 'utf-16le':
  1184. return utf16leSlice(this, start, end)
  1185. default:
  1186. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1187. encoding = (encoding + '').toLowerCase()
  1188. loweredCase = true
  1189. }
  1190. }
  1191. }
  1192. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  1193. // Buffer instances.
  1194. Buffer.prototype._isBuffer = true
  1195. function swap (b, n, m) {
  1196. var i = b[n]
  1197. b[n] = b[m]
  1198. b[m] = i
  1199. }
  1200. Buffer.prototype.swap16 = function swap16 () {
  1201. var len = this.length
  1202. if (len % 2 !== 0) {
  1203. throw new RangeError('Buffer size must be a multiple of 16-bits')
  1204. }
  1205. for (var i = 0; i < len; i += 2) {
  1206. swap(this, i, i + 1)
  1207. }
  1208. return this
  1209. }
  1210. Buffer.prototype.swap32 = function swap32 () {
  1211. var len = this.length
  1212. if (len % 4 !== 0) {
  1213. throw new RangeError('Buffer size must be a multiple of 32-bits')
  1214. }
  1215. for (var i = 0; i < len; i += 4) {
  1216. swap(this, i, i + 3)
  1217. swap(this, i + 1, i + 2)
  1218. }
  1219. return this
  1220. }
  1221. Buffer.prototype.swap64 = function swap64 () {
  1222. var len = this.length
  1223. if (len % 8 !== 0) {
  1224. throw new RangeError('Buffer size must be a multiple of 64-bits')
  1225. }
  1226. for (var i = 0; i < len; i += 8) {
  1227. swap(this, i, i + 7)
  1228. swap(this, i + 1, i + 6)
  1229. swap(this, i + 2, i + 5)
  1230. swap(this, i + 3, i + 4)
  1231. }
  1232. return this
  1233. }
  1234. Buffer.prototype.toString = function toString () {
  1235. var length = this.length | 0
  1236. if (length === 0) return ''
  1237. if (arguments.length === 0) return utf8Slice(this, 0, length)
  1238. return slowToString.apply(this, arguments)
  1239. }
  1240. Buffer.prototype.equals = function equals (b) {
  1241. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  1242. if (this === b) return true
  1243. return Buffer.compare(this, b) === 0
  1244. }
  1245. Buffer.prototype.inspect = function inspect () {
  1246. var str = ''
  1247. var max = exports.INSPECT_MAX_BYTES
  1248. if (this.length > 0) {
  1249. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  1250. if (this.length > max) str += ' ... '
  1251. }
  1252. return '<Buffer ' + str + '>'
  1253. }
  1254. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  1255. if (!Buffer.isBuffer(target)) {
  1256. throw new TypeError('Argument must be a Buffer')
  1257. }
  1258. if (start === undefined) {
  1259. start = 0
  1260. }
  1261. if (end === undefined) {
  1262. end = target ? target.length : 0
  1263. }
  1264. if (thisStart === undefined) {
  1265. thisStart = 0
  1266. }
  1267. if (thisEnd === undefined) {
  1268. thisEnd = this.length
  1269. }
  1270. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  1271. throw new RangeError('out of range index')
  1272. }
  1273. if (thisStart >= thisEnd && start >= end) {
  1274. return 0
  1275. }
  1276. if (thisStart >= thisEnd) {
  1277. return -1
  1278. }
  1279. if (start >= end) {
  1280. return 1
  1281. }
  1282. start >>>= 0
  1283. end >>>= 0
  1284. thisStart >>>= 0
  1285. thisEnd >>>= 0
  1286. if (this === target) return 0
  1287. var x = thisEnd - thisStart
  1288. var y = end - start
  1289. var len = Math.min(x, y)
  1290. var thisCopy = this.slice(thisStart, thisEnd)
  1291. var targetCopy = target.slice(start, end)
  1292. for (var i = 0; i < len; ++i) {
  1293. if (thisCopy[i] !== targetCopy[i]) {
  1294. x = thisCopy[i]
  1295. y = targetCopy[i]
  1296. break
  1297. }
  1298. }
  1299. if (x < y) return -1
  1300. if (y < x) return 1
  1301. return 0
  1302. }
  1303. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  1304. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  1305. //
  1306. // Arguments:
  1307. // - buffer - a Buffer to search
  1308. // - val - a string, Buffer, or number
  1309. // - byteOffset - an index into `buffer`; will be clamped to an int32
  1310. // - encoding - an optional encoding, relevant is val is a string
  1311. // - dir - true for indexOf, false for lastIndexOf
  1312. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  1313. // Empty buffer means no match
  1314. if (buffer.length === 0) return -1
  1315. // Normalize byteOffset
  1316. if (typeof byteOffset === 'string') {
  1317. encoding = byteOffset
  1318. byteOffset = 0
  1319. } else if (byteOffset > 0x7fffffff) {
  1320. byteOffset = 0x7fffffff
  1321. } else if (byteOffset < -0x80000000) {
  1322. byteOffset = -0x80000000
  1323. }
  1324. byteOffset = +byteOffset // Coerce to Number.
  1325. if (isNaN(byteOffset)) {
  1326. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  1327. byteOffset = dir ? 0 : (buffer.length - 1)
  1328. }
  1329. // Normalize byteOffset: negative offsets start from the end of the buffer
  1330. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  1331. if (byteOffset >= buffer.length) {
  1332. if (dir) return -1
  1333. else byteOffset = buffer.length - 1
  1334. } else if (byteOffset < 0) {
  1335. if (dir) byteOffset = 0
  1336. else return -1
  1337. }
  1338. // Normalize val
  1339. if (typeof val === 'string') {
  1340. val = Buffer.from(val, encoding)
  1341. }
  1342. // Finally, search either indexOf (if dir is true) or lastIndexOf
  1343. if (Buffer.isBuffer(val)) {
  1344. // Special case: looking for empty string/buffer always fails
  1345. if (val.length === 0) {
  1346. return -1
  1347. }
  1348. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  1349. } else if (typeof val === 'number') {
  1350. val = val & 0xFF // Search for a byte value [0-255]
  1351. if (Buffer.TYPED_ARRAY_SUPPORT &&
  1352. typeof Uint8Array.prototype.indexOf === 'function') {
  1353. if (dir) {
  1354. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  1355. } else {
  1356. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  1357. }
  1358. }
  1359. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  1360. }
  1361. throw new TypeError('val must be string, number or Buffer')
  1362. }
  1363. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  1364. var indexSize = 1
  1365. var arrLength = arr.length
  1366. var valLength = val.length
  1367. if (encoding !== undefined) {
  1368. encoding = String(encoding).toLowerCase()
  1369. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  1370. encoding === 'utf16le' || encoding === 'utf-16le') {
  1371. if (arr.length < 2 || val.length < 2) {
  1372. return -1
  1373. }
  1374. indexSize = 2
  1375. arrLength /= 2
  1376. valLength /= 2
  1377. byteOffset /= 2
  1378. }
  1379. }
  1380. function read (buf, i) {
  1381. if (indexSize === 1) {
  1382. return buf[i]
  1383. } else {
  1384. return buf.readUInt16BE(i * indexSize)
  1385. }
  1386. }
  1387. var i
  1388. if (dir) {
  1389. var foundIndex = -1
  1390. for (i = byteOffset; i < arrLength; i++) {
  1391. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  1392. if (foundIndex === -1) foundIndex = i
  1393. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  1394. } else {
  1395. if (foundIndex !== -1) i -= i - foundIndex
  1396. foundIndex = -1
  1397. }
  1398. }
  1399. } else {
  1400. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  1401. for (i = byteOffset; i >= 0; i--) {
  1402. var found = true
  1403. for (var j = 0; j < valLength; j++) {
  1404. if (read(arr, i + j) !== read(val, j)) {
  1405. found = false
  1406. break
  1407. }
  1408. }
  1409. if (found) return i
  1410. }
  1411. }
  1412. return -1
  1413. }
  1414. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  1415. return this.indexOf(val, byteOffset, encoding) !== -1
  1416. }
  1417. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  1418. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  1419. }
  1420. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  1421. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  1422. }
  1423. function hexWrite (buf, string, offset, length) {
  1424. offset = Number(offset) || 0
  1425. var remaining = buf.length - offset
  1426. if (!length) {
  1427. length = remaining
  1428. } else {
  1429. length = Number(length)
  1430. if (length > remaining) {
  1431. length = remaining
  1432. }
  1433. }
  1434. // must be an even number of digits
  1435. var strLen = string.length
  1436. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  1437. if (length > strLen / 2) {
  1438. length = strLen / 2
  1439. }
  1440. for (var i = 0; i < length; ++i) {
  1441. var parsed = parseInt(string.substr(i * 2, 2), 16)
  1442. if (isNaN(parsed)) return i
  1443. buf[offset + i] = parsed
  1444. }
  1445. return i
  1446. }
  1447. function utf8Write (buf, string, offset, length) {
  1448. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  1449. }
  1450. function asciiWrite (buf, string, offset, length) {
  1451. return blitBuffer(asciiToBytes(string), buf, offset, length)
  1452. }
  1453. function latin1Write (buf, string, offset, length) {
  1454. return asciiWrite(buf, string, offset, length)
  1455. }
  1456. function base64Write (buf, string, offset, length) {
  1457. return blitBuffer(base64ToBytes(string), buf, offset, length)
  1458. }
  1459. function ucs2Write (buf, string, offset, length) {
  1460. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  1461. }
  1462. Buffer.prototype.write = function write (string, offset, length, encoding) {
  1463. // Buffer#write(string)
  1464. if (offset === undefined) {
  1465. encoding = 'utf8'
  1466. length = this.length
  1467. offset = 0
  1468. // Buffer#write(string, encoding)
  1469. } else if (length === undefined && typeof offset === 'string') {
  1470. encoding = offset
  1471. length = this.length
  1472. offset = 0
  1473. // Buffer#write(string, offset[, length][, encoding])
  1474. } else if (isFinite(offset)) {
  1475. offset = offset | 0
  1476. if (isFinite(length)) {
  1477. length = length | 0
  1478. if (encoding === undefined) encoding = 'utf8'
  1479. } else {
  1480. encoding = length
  1481. length = undefined
  1482. }
  1483. // legacy write(string, encoding, offset, length) - remove in v0.13
  1484. } else {
  1485. throw new Error(
  1486. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  1487. )
  1488. }
  1489. var remaining = this.length - offset
  1490. if (length === undefined || length > remaining) length = remaining
  1491. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  1492. throw new RangeError('Attempt to write outside buffer bounds')
  1493. }
  1494. if (!encoding) encoding = 'utf8'
  1495. var loweredCase = false
  1496. for (;;) {
  1497. switch (encoding) {
  1498. case 'hex':
  1499. return hexWrite(this, string, offset, length)
  1500. case 'utf8':
  1501. case 'utf-8':
  1502. return utf8Write(this, string, offset, length)
  1503. case 'ascii':
  1504. return asciiWrite(this, string, offset, length)
  1505. case 'latin1':
  1506. case 'binary':
  1507. return latin1Write(this, string, offset, length)
  1508. case 'base64':
  1509. // Warning: maxLength not taken into account in base64Write
  1510. return base64Write(this, string, offset, length)
  1511. case 'ucs2':
  1512. case 'ucs-2':
  1513. case 'utf16le':
  1514. case 'utf-16le':
  1515. return ucs2Write(this, string, offset, length)
  1516. default:
  1517. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1518. encoding = ('' + encoding).toLowerCase()
  1519. loweredCase = true
  1520. }
  1521. }
  1522. }
  1523. Buffer.prototype.toJSON = function toJSON () {
  1524. return {
  1525. type: 'Buffer',
  1526. data: Array.prototype.slice.call(this._arr || this, 0)
  1527. }
  1528. }
  1529. function base64Slice (buf, start, end) {
  1530. if (start === 0 && end === buf.length) {
  1531. return base64.fromByteArray(buf)
  1532. } else {
  1533. return base64.fromByteArray(buf.slice(start, end))
  1534. }
  1535. }
  1536. function utf8Slice (buf, start, end) {
  1537. end = Math.min(buf.length, end)
  1538. var res = []
  1539. var i = start
  1540. while (i < end) {
  1541. var firstByte = buf[i]
  1542. var codePoint = null
  1543. var bytesPerSequence = (firstByte > 0xEF) ? 4
  1544. : (firstByte > 0xDF) ? 3
  1545. : (firstByte > 0xBF) ? 2
  1546. : 1
  1547. if (i + bytesPerSequence <= end) {
  1548. var secondByte, thirdByte, fourthByte, tempCodePoint
  1549. switch (bytesPerSequence) {
  1550. case 1:
  1551. if (firstByte < 0x80) {
  1552. codePoint = firstByte
  1553. }
  1554. break
  1555. case 2:
  1556. secondByte = buf[i + 1]
  1557. if ((secondByte & 0xC0) === 0x80) {
  1558. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1559. if (tempCodePoint > 0x7F) {
  1560. codePoint = tempCodePoint
  1561. }
  1562. }
  1563. break
  1564. case 3:
  1565. secondByte = buf[i + 1]
  1566. thirdByte = buf[i + 2]
  1567. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1568. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1569. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1570. codePoint = tempCodePoint
  1571. }
  1572. }
  1573. break
  1574. case 4:
  1575. secondByte = buf[i + 1]
  1576. thirdByte = buf[i + 2]
  1577. fourthByte = buf[i + 3]
  1578. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1579. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1580. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1581. codePoint = tempCodePoint
  1582. }
  1583. }
  1584. }
  1585. }
  1586. if (codePoint === null) {
  1587. // we did not generate a valid codePoint so insert a
  1588. // replacement char (U+FFFD) and advance only 1 byte
  1589. codePoint = 0xFFFD
  1590. bytesPerSequence = 1
  1591. } else if (codePoint > 0xFFFF) {
  1592. // encode to utf16 (surrogate pair dance)
  1593. codePoint -= 0x10000
  1594. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1595. codePoint = 0xDC00 | codePoint & 0x3FF
  1596. }
  1597. res.push(codePoint)
  1598. i += bytesPerSequence
  1599. }
  1600. return decodeCodePointsArray(res)
  1601. }
  1602. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1603. // the lowest limit is Chrome, with 0x10000 args.
  1604. // We go 1 magnitude less, for safety
  1605. var MAX_ARGUMENTS_LENGTH = 0x1000
  1606. function decodeCodePointsArray (codePoints) {
  1607. var len = codePoints.length
  1608. if (len <= MAX_ARGUMENTS_LENGTH) {
  1609. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1610. }
  1611. // Decode in chunks to avoid "call stack size exceeded".
  1612. var res = ''
  1613. var i = 0
  1614. while (i < len) {
  1615. res += String.fromCharCode.apply(
  1616. String,
  1617. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1618. )
  1619. }
  1620. return res
  1621. }
  1622. function asciiSlice (buf, start, end) {
  1623. var ret = ''
  1624. end = Math.min(buf.length, end)
  1625. for (var i = start; i < end; ++i) {
  1626. ret += String.fromCharCode(buf[i] & 0x7F)
  1627. }
  1628. return ret
  1629. }
  1630. function latin1Slice (buf, start, end) {
  1631. var ret = ''
  1632. end = Math.min(buf.length, end)
  1633. for (var i = start; i < end; ++i) {
  1634. ret += String.fromCharCode(buf[i])
  1635. }
  1636. return ret
  1637. }
  1638. function hexSlice (buf, start, end) {
  1639. var len = buf.length
  1640. if (!start || start < 0) start = 0
  1641. if (!end || end < 0 || end > len) end = len
  1642. var out = ''
  1643. for (var i = start; i < end; ++i) {
  1644. out += toHex(buf[i])
  1645. }
  1646. return out
  1647. }
  1648. function utf16leSlice (buf, start, end) {
  1649. var bytes = buf.slice(start, end)
  1650. var res = ''
  1651. for (var i = 0; i < bytes.length; i += 2) {
  1652. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1653. }
  1654. return res
  1655. }
  1656. Buffer.prototype.slice = function slice (start, end) {
  1657. var len = this.length
  1658. start = ~~start
  1659. end = end === undefined ? len : ~~end
  1660. if (start < 0) {
  1661. start += len
  1662. if (start < 0) start = 0
  1663. } else if (start > len) {
  1664. start = len
  1665. }
  1666. if (end < 0) {
  1667. end += len
  1668. if (end < 0) end = 0
  1669. } else if (end > len) {
  1670. end = len
  1671. }
  1672. if (end < start) end = start
  1673. var newBuf
  1674. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1675. newBuf = this.subarray(start, end)
  1676. newBuf.__proto__ = Buffer.prototype
  1677. } else {
  1678. var sliceLen = end - start
  1679. newBuf = new Buffer(sliceLen, undefined)
  1680. for (var i = 0; i < sliceLen; ++i) {
  1681. newBuf[i] = this[i + start]
  1682. }
  1683. }
  1684. return newBuf
  1685. }
  1686. /*
  1687. * Need to make sure that buffer isn't trying to write out of bounds.
  1688. */
  1689. function checkOffset (offset, ext, length) {
  1690. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1691. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1692. }
  1693. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1694. offset = offset | 0
  1695. byteLength = byteLength | 0
  1696. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1697. var val = this[offset]
  1698. var mul = 1
  1699. var i = 0
  1700. while (++i < byteLength && (mul *= 0x100)) {
  1701. val += this[offset + i] * mul
  1702. }
  1703. return val
  1704. }
  1705. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1706. offset = offset | 0
  1707. byteLength = byteLength | 0
  1708. if (!noAssert) {
  1709. checkOffset(offset, byteLength, this.length)
  1710. }
  1711. var val = this[offset + --byteLength]
  1712. var mul = 1
  1713. while (byteLength > 0 && (mul *= 0x100)) {
  1714. val += this[offset + --byteLength] * mul
  1715. }
  1716. return val
  1717. }
  1718. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1719. if (!noAssert) checkOffset(offset, 1, this.length)
  1720. return this[offset]
  1721. }
  1722. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1723. if (!noAssert) checkOffset(offset, 2, this.length)
  1724. return this[offset] | (this[offset + 1] << 8)
  1725. }
  1726. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1727. if (!noAssert) checkOffset(offset, 2, this.length)
  1728. return (this[offset] << 8) | this[offset + 1]
  1729. }
  1730. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1731. if (!noAssert) checkOffset(offset, 4, this.length)
  1732. return ((this[offset]) |
  1733. (this[offset + 1] << 8) |
  1734. (this[offset + 2] << 16)) +
  1735. (this[offset + 3] * 0x1000000)
  1736. }
  1737. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1738. if (!noAssert) checkOffset(offset, 4, this.length)
  1739. return (this[offset] * 0x1000000) +
  1740. ((this[offset + 1] << 16) |
  1741. (this[offset + 2] << 8) |
  1742. this[offset + 3])
  1743. }
  1744. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1745. offset = offset | 0
  1746. byteLength = byteLength | 0
  1747. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1748. var val = this[offset]
  1749. var mul = 1
  1750. var i = 0
  1751. while (++i < byteLength && (mul *= 0x100)) {
  1752. val += this[offset + i] * mul
  1753. }
  1754. mul *= 0x80
  1755. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1756. return val
  1757. }
  1758. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1759. offset = offset | 0
  1760. byteLength = byteLength | 0
  1761. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1762. var i = byteLength
  1763. var mul = 1
  1764. var val = this[offset + --i]
  1765. while (i > 0 && (mul *= 0x100)) {
  1766. val += this[offset + --i] * mul
  1767. }
  1768. mul *= 0x80
  1769. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1770. return val
  1771. }
  1772. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1773. if (!noAssert) checkOffset(offset, 1, this.length)
  1774. if (!(this[offset] & 0x80)) return (this[offset])
  1775. return ((0xff - this[offset] + 1) * -1)
  1776. }
  1777. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1778. if (!noAssert) checkOffset(offset, 2, this.length)
  1779. var val = this[offset] | (this[offset + 1] << 8)
  1780. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1781. }
  1782. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1783. if (!noAssert) checkOffset(offset, 2, this.length)
  1784. var val = this[offset + 1] | (this[offset] << 8)
  1785. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1786. }
  1787. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1788. if (!noAssert) checkOffset(offset, 4, this.length)
  1789. return (this[offset]) |
  1790. (this[offset + 1] << 8) |
  1791. (this[offset + 2] << 16) |
  1792. (this[offset + 3] << 24)
  1793. }
  1794. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1795. if (!noAssert) checkOffset(offset, 4, this.length)
  1796. return (this[offset] << 24) |
  1797. (this[offset + 1] << 16) |
  1798. (this[offset + 2] << 8) |
  1799. (this[offset + 3])
  1800. }
  1801. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1802. if (!noAssert) checkOffset(offset, 4, this.length)
  1803. return ieee754.read(this, offset, true, 23, 4)
  1804. }
  1805. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1806. if (!noAssert) checkOffset(offset, 4, this.length)
  1807. return ieee754.read(this, offset, false, 23, 4)
  1808. }
  1809. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1810. if (!noAssert) checkOffset(offset, 8, this.length)
  1811. return ieee754.read(this, offset, true, 52, 8)
  1812. }
  1813. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1814. if (!noAssert) checkOffset(offset, 8, this.length)
  1815. return ieee754.read(this, offset, false, 52, 8)
  1816. }
  1817. function checkInt (buf, value, offset, ext, max, min) {
  1818. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1819. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1820. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1821. }
  1822. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1823. value = +value
  1824. offset = offset | 0
  1825. byteLength = byteLength | 0
  1826. if (!noAssert) {
  1827. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1828. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1829. }
  1830. var mul = 1
  1831. var i = 0
  1832. this[offset] = value & 0xFF
  1833. while (++i < byteLength && (mul *= 0x100)) {
  1834. this[offset + i] = (value / mul) & 0xFF
  1835. }
  1836. return offset + byteLength
  1837. }
  1838. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1839. value = +value
  1840. offset = offset | 0
  1841. byteLength = byteLength | 0
  1842. if (!noAssert) {
  1843. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1844. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1845. }
  1846. var i = byteLength - 1
  1847. var mul = 1
  1848. this[offset + i] = value & 0xFF
  1849. while (--i >= 0 && (mul *= 0x100)) {
  1850. this[offset + i] = (value / mul) & 0xFF
  1851. }
  1852. return offset + byteLength
  1853. }
  1854. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1855. value = +value
  1856. offset = offset | 0
  1857. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1858. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1859. this[offset] = (value & 0xff)
  1860. return offset + 1
  1861. }
  1862. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1863. if (value < 0) value = 0xffff + value + 1
  1864. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1865. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1866. (littleEndian ? i : 1 - i) * 8
  1867. }
  1868. }
  1869. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1870. value = +value
  1871. offset = offset | 0
  1872. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1873. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1874. this[offset] = (value & 0xff)
  1875. this[offset + 1] = (value >>> 8)
  1876. } else {
  1877. objectWriteUInt16(this, value, offset, true)
  1878. }
  1879. return offset + 2
  1880. }
  1881. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1882. value = +value
  1883. offset = offset | 0
  1884. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1885. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1886. this[offset] = (value >>> 8)
  1887. this[offset + 1] = (value & 0xff)
  1888. } else {
  1889. objectWriteUInt16(this, value, offset, false)
  1890. }
  1891. return offset + 2
  1892. }
  1893. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1894. if (value < 0) value = 0xffffffff + value + 1
  1895. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1896. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1897. }
  1898. }
  1899. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1900. value = +value
  1901. offset = offset | 0
  1902. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1903. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1904. this[offset + 3] = (value >>> 24)
  1905. this[offset + 2] = (value >>> 16)
  1906. this[offset + 1] = (value >>> 8)
  1907. this[offset] = (value & 0xff)
  1908. } else {
  1909. objectWriteUInt32(this, value, offset, true)
  1910. }
  1911. return offset + 4
  1912. }
  1913. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1914. value = +value
  1915. offset = offset | 0
  1916. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1917. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1918. this[offset] = (value >>> 24)
  1919. this[offset + 1] = (value >>> 16)
  1920. this[offset + 2] = (value >>> 8)
  1921. this[offset + 3] = (value & 0xff)
  1922. } else {
  1923. objectWriteUInt32(this, value, offset, false)
  1924. }
  1925. return offset + 4
  1926. }
  1927. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1928. value = +value
  1929. offset = offset | 0
  1930. if (!noAssert) {
  1931. var limit = Math.pow(2, 8 * byteLength - 1)
  1932. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1933. }
  1934. var i = 0
  1935. var mul = 1
  1936. var sub = 0
  1937. this[offset] = value & 0xFF
  1938. while (++i < byteLength && (mul *= 0x100)) {
  1939. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1940. sub = 1
  1941. }
  1942. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1943. }
  1944. return offset + byteLength
  1945. }
  1946. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1947. value = +value
  1948. offset = offset | 0
  1949. if (!noAssert) {
  1950. var limit = Math.pow(2, 8 * byteLength - 1)
  1951. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1952. }
  1953. var i = byteLength - 1
  1954. var mul = 1
  1955. var sub = 0
  1956. this[offset + i] = value & 0xFF
  1957. while (--i >= 0 && (mul *= 0x100)) {
  1958. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1959. sub = 1
  1960. }
  1961. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1962. }
  1963. return offset + byteLength
  1964. }
  1965. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1966. value = +value
  1967. offset = offset | 0
  1968. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1969. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1970. if (value < 0) value = 0xff + value + 1
  1971. this[offset] = (value & 0xff)
  1972. return offset + 1
  1973. }
  1974. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1975. value = +value
  1976. offset = offset | 0
  1977. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1978. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1979. this[offset] = (value & 0xff)
  1980. this[offset + 1] = (value >>> 8)
  1981. } else {
  1982. objectWriteUInt16(this, value, offset, true)
  1983. }
  1984. return offset + 2
  1985. }
  1986. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1987. value = +value
  1988. offset = offset | 0
  1989. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1990. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1991. this[offset] = (value >>> 8)
  1992. this[offset + 1] = (value & 0xff)
  1993. } else {
  1994. objectWriteUInt16(this, value, offset, false)
  1995. }
  1996. return offset + 2
  1997. }
  1998. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1999. value = +value
  2000. offset = offset | 0
  2001. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  2002. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2003. this[offset] = (value & 0xff)
  2004. this[offset + 1] = (value >>> 8)
  2005. this[offset + 2] = (value >>> 16)
  2006. this[offset + 3] = (value >>> 24)
  2007. } else {
  2008. objectWriteUInt32(this, value, offset, true)
  2009. }
  2010. return offset + 4
  2011. }
  2012. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  2013. value = +value
  2014. offset = offset | 0
  2015. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  2016. if (value < 0) value = 0xffffffff + value + 1
  2017. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2018. this[offset] = (value >>> 24)
  2019. this[offset + 1] = (value >>> 16)
  2020. this[offset + 2] = (value >>> 8)
  2021. this[offset + 3] = (value & 0xff)
  2022. } else {
  2023. objectWriteUInt32(this, value, offset, false)
  2024. }
  2025. return offset + 4
  2026. }
  2027. function checkIEEE754 (buf, value, offset, ext, max, min) {
  2028. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2029. if (offset < 0) throw new RangeError('Index out of range')
  2030. }
  2031. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  2032. if (!noAssert) {
  2033. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  2034. }
  2035. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  2036. return offset + 4
  2037. }
  2038. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  2039. return writeFloat(this, value, offset, true, noAssert)
  2040. }
  2041. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  2042. return writeFloat(this, value, offset, false, noAssert)
  2043. }
  2044. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  2045. if (!noAssert) {
  2046. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  2047. }
  2048. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  2049. return offset + 8
  2050. }
  2051. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  2052. return writeDouble(this, value, offset, true, noAssert)
  2053. }
  2054. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  2055. return writeDouble(this, value, offset, false, noAssert)
  2056. }
  2057. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  2058. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  2059. if (!start) start = 0
  2060. if (!end && end !== 0) end = this.length
  2061. if (targetStart >= target.length) targetStart = target.length
  2062. if (!targetStart) targetStart = 0
  2063. if (end > 0 && end < start) end = start
  2064. // Copy 0 bytes; we're done
  2065. if (end === start) return 0
  2066. if (target.length === 0 || this.length === 0) return 0
  2067. // Fatal error conditions
  2068. if (targetStart < 0) {
  2069. throw new RangeError('targetStart out of bounds')
  2070. }
  2071. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  2072. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  2073. // Are we oob?
  2074. if (end > this.length) end = this.length
  2075. if (target.length - targetStart < end - start) {
  2076. end = target.length - targetStart + start
  2077. }
  2078. var len = end - start
  2079. var i
  2080. if (this === target && start < targetStart && targetStart < end) {
  2081. // descending copy from end
  2082. for (i = len - 1; i >= 0; --i) {
  2083. target[i + targetStart] = this[i + start]
  2084. }
  2085. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  2086. // ascending copy from start
  2087. for (i = 0; i < len; ++i) {
  2088. target[i + targetStart] = this[i + start]
  2089. }
  2090. } else {
  2091. Uint8Array.prototype.set.call(
  2092. target,
  2093. this.subarray(start, start + len),
  2094. targetStart
  2095. )
  2096. }
  2097. return len
  2098. }
  2099. // Usage:
  2100. // buffer.fill(number[, offset[, end]])
  2101. // buffer.fill(buffer[, offset[, end]])
  2102. // buffer.fill(string[, offset[, end]][, encoding])
  2103. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  2104. // Handle string cases:
  2105. if (typeof val === 'string') {
  2106. if (typeof start === 'string') {
  2107. encoding = start
  2108. start = 0
  2109. end = this.length
  2110. } else if (typeof end === 'string') {
  2111. encoding = end
  2112. end = this.length
  2113. }
  2114. if (val.length === 1) {
  2115. var code = val.charCodeAt(0)
  2116. if (code < 256) {
  2117. val = code
  2118. }
  2119. }
  2120. if (encoding !== undefined && typeof encoding !== 'string') {
  2121. throw new TypeError('encoding must be a string')
  2122. }
  2123. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  2124. throw new TypeError('Unknown encoding: ' + encoding)
  2125. }
  2126. } else if (typeof val === 'number') {
  2127. val = val & 255
  2128. }
  2129. // Invalid ranges are not set to a default, so can range check early.
  2130. if (start < 0 || this.length < start || this.length < end) {
  2131. throw new RangeError('Out of range index')
  2132. }
  2133. if (end <= start) {
  2134. return this
  2135. }
  2136. start = start >>> 0
  2137. end = end === undefined ? this.length : end >>> 0
  2138. if (!val) val = 0
  2139. var i
  2140. if (typeof val === 'number') {
  2141. for (i = start; i < end; ++i) {
  2142. this[i] = val
  2143. }
  2144. } else {
  2145. var bytes = Buffer.isBuffer(val)
  2146. ? val
  2147. : utf8ToBytes(new Buffer(val, encoding).toString())
  2148. var len = bytes.length
  2149. for (i = 0; i < end - start; ++i) {
  2150. this[i + start] = bytes[i % len]
  2151. }
  2152. }
  2153. return this
  2154. }
  2155. // HELPER FUNCTIONS
  2156. // ================
  2157. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  2158. function base64clean (str) {
  2159. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  2160. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  2161. // Node converts strings with length < 2 to ''
  2162. if (str.length < 2) return ''
  2163. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  2164. while (str.length % 4 !== 0) {
  2165. str = str + '='
  2166. }
  2167. return str
  2168. }
  2169. function stringtrim (str) {
  2170. if (str.trim) return str.trim()
  2171. return str.replace(/^\s+|\s+$/g, '')
  2172. }
  2173. function toHex (n) {
  2174. if (n < 16) return '0' + n.toString(16)
  2175. return n.toString(16)
  2176. }
  2177. function utf8ToBytes (string, units) {
  2178. units = units || Infinity
  2179. var codePoint
  2180. var length = string.length
  2181. var leadSurrogate = null
  2182. var bytes = []
  2183. for (var i = 0; i < length; ++i) {
  2184. codePoint = string.charCodeAt(i)
  2185. // is surrogate component
  2186. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  2187. // last char was a lead
  2188. if (!leadSurrogate) {
  2189. // no lead yet
  2190. if (codePoint > 0xDBFF) {
  2191. // unexpected trail
  2192. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2193. continue
  2194. } else if (i + 1 === length) {
  2195. // unpaired lead
  2196. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2197. continue
  2198. }
  2199. // valid lead
  2200. leadSurrogate = codePoint
  2201. continue
  2202. }
  2203. // 2 leads in a row
  2204. if (codePoint < 0xDC00) {
  2205. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2206. leadSurrogate = codePoint
  2207. continue
  2208. }
  2209. // valid surrogate pair
  2210. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  2211. } else if (leadSurrogate) {
  2212. // valid bmp char, but last char was a lead
  2213. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2214. }
  2215. leadSurrogate = null
  2216. // encode utf8
  2217. if (codePoint < 0x80) {
  2218. if ((units -= 1) < 0) break
  2219. bytes.push(codePoint)
  2220. } else if (codePoint < 0x800) {
  2221. if ((units -= 2) < 0) break
  2222. bytes.push(
  2223. codePoint >> 0x6 | 0xC0,
  2224. codePoint & 0x3F | 0x80
  2225. )
  2226. } else if (codePoint < 0x10000) {
  2227. if ((units -= 3) < 0) break
  2228. bytes.push(
  2229. codePoint >> 0xC | 0xE0,
  2230. codePoint >> 0x6 & 0x3F | 0x80,
  2231. codePoint & 0x3F | 0x80
  2232. )
  2233. } else if (codePoint < 0x110000) {
  2234. if ((units -= 4) < 0) break
  2235. bytes.push(
  2236. codePoint >> 0x12 | 0xF0,
  2237. codePoint >> 0xC & 0x3F | 0x80,
  2238. codePoint >> 0x6 & 0x3F | 0x80,
  2239. codePoint & 0x3F | 0x80
  2240. )
  2241. } else {
  2242. throw new Error('Invalid code point')
  2243. }
  2244. }
  2245. return bytes
  2246. }
  2247. function asciiToBytes (str) {
  2248. var byteArray = []
  2249. for (var i = 0; i < str.length; ++i) {
  2250. // Node's code seems to be doing this and not & 0x7F..
  2251. byteArray.push(str.charCodeAt(i) & 0xFF)
  2252. }
  2253. return byteArray
  2254. }
  2255. function utf16leToBytes (str, units) {
  2256. var c, hi, lo
  2257. var byteArray = []
  2258. for (var i = 0; i < str.length; ++i) {
  2259. if ((units -= 2) < 0) break
  2260. c = str.charCodeAt(i)
  2261. hi = c >> 8
  2262. lo = c % 256
  2263. byteArray.push(lo)
  2264. byteArray.push(hi)
  2265. }
  2266. return byteArray
  2267. }
  2268. function base64ToBytes (str) {
  2269. return base64.toByteArray(base64clean(str))
  2270. }
  2271. function blitBuffer (src, dst, offset, length) {
  2272. for (var i = 0; i < length; ++i) {
  2273. if ((i + offset >= dst.length) || (i >= src.length)) break
  2274. dst[i + offset] = src[i]
  2275. }
  2276. return i
  2277. }
  2278. function isnan (val) {
  2279. return val !== val // eslint-disable-line no-self-compare
  2280. }
  2281. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2282. },{"base64-js":4,"ieee754":16,"isarray":21}],8:[function(_dereq_,module,exports){
  2283. /**
  2284. * This is the web browser implementation of `debug()`.
  2285. *
  2286. * Expose `debug()` as the module.
  2287. */
  2288. exports = module.exports = _dereq_('./debug');
  2289. exports.log = log;
  2290. exports.formatArgs = formatArgs;
  2291. exports.save = save;
  2292. exports.load = load;
  2293. exports.useColors = useColors;
  2294. exports.storage = 'undefined' != typeof chrome
  2295. && 'undefined' != typeof chrome.storage
  2296. ? chrome.storage.local
  2297. : localstorage();
  2298. /**
  2299. * Colors.
  2300. */
  2301. exports.colors = [
  2302. 'lightseagreen',
  2303. 'forestgreen',
  2304. 'goldenrod',
  2305. 'dodgerblue',
  2306. 'darkorchid',
  2307. 'crimson'
  2308. ];
  2309. /**
  2310. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  2311. * and the Firebug extension (any Firefox version) are known
  2312. * to support "%c" CSS customizations.
  2313. *
  2314. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  2315. */
  2316. function useColors() {
  2317. // is webkit? http://stackoverflow.com/a/16459606/376773
  2318. return ('WebkitAppearance' in document.documentElement.style) ||
  2319. // is firebug? http://stackoverflow.com/a/398120/376773
  2320. (window.console && (console.firebug || (console.exception && console.table))) ||
  2321. // is firefox >= v31?
  2322. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  2323. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  2324. }
  2325. /**
  2326. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  2327. */
  2328. exports.formatters.j = function(v) {
  2329. return JSON.stringify(v);
  2330. };
  2331. /**
  2332. * Colorize log arguments if enabled.
  2333. *
  2334. * @api public
  2335. */
  2336. function formatArgs() {
  2337. var args = arguments;
  2338. var useColors = this.useColors;
  2339. args[0] = (useColors ? '%c' : '')
  2340. + this.namespace
  2341. + (useColors ? ' %c' : ' ')
  2342. + args[0]
  2343. + (useColors ? '%c ' : ' ');
  2344. if (!useColors) return args;
  2345. var c = 'color: ' + this.color;
  2346. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  2347. // the final "%c" is somewhat tricky, because there could be other
  2348. // arguments passed either before or after the %c, so we need to
  2349. // figure out the correct index to insert the CSS into
  2350. var index = 0;
  2351. var lastC = 0;
  2352. args[0].replace(/%[a-z%]/g, function(match) {
  2353. if ('%%' === match) return;
  2354. index++;
  2355. if ('%c' === match) {
  2356. // we only are interested in the *last* %c
  2357. // (the user may have provided their own)
  2358. lastC = index;
  2359. }
  2360. });
  2361. args.splice(lastC, 0, c);
  2362. return args;
  2363. }
  2364. /**
  2365. * Invokes `console.log()` when available.
  2366. * No-op when `console.log` is not a "function".
  2367. *
  2368. * @api public
  2369. */
  2370. function log() {
  2371. // this hackery is required for IE8/9, where
  2372. // the `console.log` function doesn't have 'apply'
  2373. return 'object' === typeof console
  2374. && console.log
  2375. && Function.prototype.apply.call(console.log, console, arguments);
  2376. }
  2377. /**
  2378. * Save `namespaces`.
  2379. *
  2380. * @param {String} namespaces
  2381. * @api private
  2382. */
  2383. function save(namespaces) {
  2384. try {
  2385. if (null == namespaces) {
  2386. exports.storage.removeItem('debug');
  2387. } else {
  2388. exports.storage.debug = namespaces;
  2389. }
  2390. } catch(e) {}
  2391. }
  2392. /**
  2393. * Load `namespaces`.
  2394. *
  2395. * @return {String} returns the previously persisted debug modes
  2396. * @api private
  2397. */
  2398. function load() {
  2399. var r;
  2400. try {
  2401. r = exports.storage.debug;
  2402. } catch(e) {}
  2403. return r;
  2404. }
  2405. /**
  2406. * Enable namespaces listed in `localStorage.debug` initially.
  2407. */
  2408. exports.enable(load());
  2409. /**
  2410. * Localstorage attempts to return the localstorage.
  2411. *
  2412. * This is necessary because safari throws
  2413. * when a user disables cookies/localstorage
  2414. * and you attempt to access it.
  2415. *
  2416. * @return {LocalStorage}
  2417. * @api private
  2418. */
  2419. function localstorage(){
  2420. try {
  2421. return window.localStorage;
  2422. } catch (e) {}
  2423. }
  2424. },{"./debug":9}],9:[function(_dereq_,module,exports){
  2425. /**
  2426. * This is the common logic for both the Node.js and web browser
  2427. * implementations of `debug()`.
  2428. *
  2429. * Expose `debug()` as the module.
  2430. */
  2431. exports = module.exports = debug;
  2432. exports.coerce = coerce;
  2433. exports.disable = disable;
  2434. exports.enable = enable;
  2435. exports.enabled = enabled;
  2436. /**
  2437. * The currently active debug mode names, and names to skip.
  2438. */
  2439. exports.names = [];
  2440. exports.skips = [];
  2441. /**
  2442. * Map of special "%n" handling functions, for the debug "format" argument.
  2443. *
  2444. * Valid key names are a single, lowercased letter, i.e. "n".
  2445. */
  2446. exports.formatters = {};
  2447. /**
  2448. * Previously assigned color.
  2449. */
  2450. var prevColor = 0;
  2451. /**
  2452. * Select a color.
  2453. *
  2454. * @return {Number}
  2455. * @api private
  2456. */
  2457. function selectColor() {
  2458. return exports.colors[prevColor++ % exports.colors.length];
  2459. }
  2460. /**
  2461. * Create a debugger with the given `namespace`.
  2462. *
  2463. * @param {String} namespace
  2464. * @return {Function}
  2465. * @api public
  2466. */
  2467. function debug(namespace) {
  2468. // define the `disabled` version
  2469. function disabled() {
  2470. }
  2471. disabled.enabled = false;
  2472. // define the `enabled` version
  2473. function enabled() {
  2474. var self = enabled;
  2475. // add the `color` if not set
  2476. if (null == self.useColors) self.useColors = exports.useColors();
  2477. if (null == self.color && self.useColors) self.color = selectColor();
  2478. var args = Array.prototype.slice.call(arguments);
  2479. args[0] = exports.coerce(args[0]);
  2480. if ('string' !== typeof args[0]) {
  2481. // anything else let's inspect with %o
  2482. args = ['%o'].concat(args);
  2483. }
  2484. // apply any `formatters` transformations
  2485. var index = 0;
  2486. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  2487. // if we encounter an escaped % then don't increase the array index
  2488. if (match === '%%') return match;
  2489. index++;
  2490. var formatter = exports.formatters[format];
  2491. if ('function' === typeof formatter) {
  2492. var val = args[index];
  2493. match = formatter.call(self, val);
  2494. // now we need to remove `args[index]` since it's inlined in the `format`
  2495. args.splice(index, 1);
  2496. index--;
  2497. }
  2498. return match;
  2499. });
  2500. if ('function' === typeof exports.formatArgs) {
  2501. args = exports.formatArgs.apply(self, args);
  2502. }
  2503. var logFn = enabled.log || exports.log || console.log.bind(console);
  2504. logFn.apply(self, args);
  2505. }
  2506. enabled.enabled = true;
  2507. var fn = exports.enabled(namespace) ? enabled : disabled;
  2508. fn.namespace = namespace;
  2509. return fn;
  2510. }
  2511. /**
  2512. * Enables a debug mode by namespaces. This can include modes
  2513. * separated by a colon and wildcards.
  2514. *
  2515. * @param {String} namespaces
  2516. * @api public
  2517. */
  2518. function enable(namespaces) {
  2519. exports.save(namespaces);
  2520. var split = (namespaces || '').split(/[\s,]+/);
  2521. var len = split.length;
  2522. for (var i = 0; i < len; i++) {
  2523. if (!split[i]) continue; // ignore empty strings
  2524. namespaces = split[i].replace(/\*/g, '.*?');
  2525. if (namespaces[0] === '-') {
  2526. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2527. } else {
  2528. exports.names.push(new RegExp('^' + namespaces + '$'));
  2529. }
  2530. }
  2531. }
  2532. /**
  2533. * Disable debug output.
  2534. *
  2535. * @api public
  2536. */
  2537. function disable() {
  2538. exports.enable('');
  2539. }
  2540. /**
  2541. * Returns true if the given mode name is enabled, false otherwise.
  2542. *
  2543. * @param {String} name
  2544. * @return {Boolean}
  2545. * @api public
  2546. */
  2547. function enabled(name) {
  2548. var i, len;
  2549. for (i = 0, len = exports.skips.length; i < len; i++) {
  2550. if (exports.skips[i].test(name)) {
  2551. return false;
  2552. }
  2553. }
  2554. for (i = 0, len = exports.names.length; i < len; i++) {
  2555. if (exports.names[i].test(name)) {
  2556. return true;
  2557. }
  2558. }
  2559. return false;
  2560. }
  2561. /**
  2562. * Coerce `val`.
  2563. *
  2564. * @param {Mixed} val
  2565. * @return {Mixed}
  2566. * @api private
  2567. */
  2568. function coerce(val) {
  2569. if (val instanceof Error) return val.stack || val.message;
  2570. return val;
  2571. }
  2572. },{}],10:[function(_dereq_,module,exports){
  2573. 'use strict';
  2574. var isObj = _dereq_('is-obj');
  2575. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2576. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2577. function toObject(val) {
  2578. if (val === null || val === undefined) {
  2579. throw new TypeError('Sources cannot be null or undefined');
  2580. }
  2581. return Object(val);
  2582. }
  2583. function assignKey(to, from, key) {
  2584. var val = from[key];
  2585. if (val === undefined || val === null) {
  2586. return;
  2587. }
  2588. if (hasOwnProperty.call(to, key)) {
  2589. if (to[key] === undefined || to[key] === null) {
  2590. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2591. }
  2592. }
  2593. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2594. to[key] = val;
  2595. } else {
  2596. to[key] = assign(Object(to[key]), from[key]);
  2597. }
  2598. }
  2599. function assign(to, from) {
  2600. if (to === from) {
  2601. return to;
  2602. }
  2603. from = Object(from);
  2604. for (var key in from) {
  2605. if (hasOwnProperty.call(from, key)) {
  2606. assignKey(to, from, key);
  2607. }
  2608. }
  2609. if (Object.getOwnPropertySymbols) {
  2610. var symbols = Object.getOwnPropertySymbols(from);
  2611. for (var i = 0; i < symbols.length; i++) {
  2612. if (propIsEnumerable.call(from, symbols[i])) {
  2613. assignKey(to, from, symbols[i]);
  2614. }
  2615. }
  2616. }
  2617. return to;
  2618. }
  2619. module.exports = function deepAssign(target) {
  2620. target = toObject(target);
  2621. for (var s = 1; s < arguments.length; s++) {
  2622. assign(target, arguments[s]);
  2623. }
  2624. return target;
  2625. };
  2626. },{"is-obj":20}],11:[function(_dereq_,module,exports){
  2627. /*! (C) WebReflection Mit Style License */
  2628. (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");
  2629. },{}],12:[function(_dereq_,module,exports){
  2630. module.exports = function(dtype) {
  2631. switch (dtype) {
  2632. case 'int8':
  2633. return Int8Array
  2634. case 'int16':
  2635. return Int16Array
  2636. case 'int32':
  2637. return Int32Array
  2638. case 'uint8':
  2639. return Uint8Array
  2640. case 'uint16':
  2641. return Uint16Array
  2642. case 'uint32':
  2643. return Uint32Array
  2644. case 'float32':
  2645. return Float32Array
  2646. case 'float64':
  2647. return Float64Array
  2648. case 'array':
  2649. return Array
  2650. case 'uint8_clamped':
  2651. return Uint8ClampedArray
  2652. }
  2653. }
  2654. },{}],13:[function(_dereq_,module,exports){
  2655. /*eslint new-cap:0*/
  2656. var dtype = _dereq_('dtype')
  2657. module.exports = flattenVertexData
  2658. function flattenVertexData (data, output, offset) {
  2659. if (!data) throw new TypeError('must specify data as first parameter')
  2660. offset = +(offset || 0) | 0
  2661. if (Array.isArray(data) && Array.isArray(data[0])) {
  2662. var dim = data[0].length
  2663. var length = data.length * dim
  2664. // no output specified, create a new typed array
  2665. if (!output || typeof output === 'string') {
  2666. output = new (dtype(output || 'float32'))(length + offset)
  2667. }
  2668. var dstLength = output.length - offset
  2669. if (length !== dstLength) {
  2670. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2671. ' does not match destination length ' + dstLength)
  2672. }
  2673. for (var i = 0, k = offset; i < data.length; i++) {
  2674. for (var j = 0; j < dim; j++) {
  2675. output[k++] = data[i][j]
  2676. }
  2677. }
  2678. } else {
  2679. if (!output || typeof output === 'string') {
  2680. // no output, create a new one
  2681. var Ctor = dtype(output || 'float32')
  2682. if (offset === 0) {
  2683. output = new Ctor(data)
  2684. } else {
  2685. output = new Ctor(data.length + offset)
  2686. output.set(data, offset)
  2687. }
  2688. } else {
  2689. // store output in existing array
  2690. output.set(data, offset)
  2691. }
  2692. }
  2693. return output
  2694. }
  2695. },{"dtype":12}],14:[function(_dereq_,module,exports){
  2696. var isFunction = _dereq_('is-function')
  2697. module.exports = forEach
  2698. var toString = Object.prototype.toString
  2699. var hasOwnProperty = Object.prototype.hasOwnProperty
  2700. function forEach(list, iterator, context) {
  2701. if (!isFunction(iterator)) {
  2702. throw new TypeError('iterator must be a function')
  2703. }
  2704. if (arguments.length < 3) {
  2705. context = this
  2706. }
  2707. if (toString.call(list) === '[object Array]')
  2708. forEachArray(list, iterator, context)
  2709. else if (typeof list === 'string')
  2710. forEachString(list, iterator, context)
  2711. else
  2712. forEachObject(list, iterator, context)
  2713. }
  2714. function forEachArray(array, iterator, context) {
  2715. for (var i = 0, len = array.length; i < len; i++) {
  2716. if (hasOwnProperty.call(array, i)) {
  2717. iterator.call(context, array[i], i, array)
  2718. }
  2719. }
  2720. }
  2721. function forEachString(string, iterator, context) {
  2722. for (var i = 0, len = string.length; i < len; i++) {
  2723. // no such thing as a sparse string.
  2724. iterator.call(context, string.charAt(i), i, string)
  2725. }
  2726. }
  2727. function forEachObject(object, iterator, context) {
  2728. for (var k in object) {
  2729. if (hasOwnProperty.call(object, k)) {
  2730. iterator.call(context, object[k], k, object)
  2731. }
  2732. }
  2733. }
  2734. },{"is-function":19}],15:[function(_dereq_,module,exports){
  2735. (function (global){
  2736. var win;
  2737. if (typeof window !== "undefined") {
  2738. win = window;
  2739. } else if (typeof global !== "undefined") {
  2740. win = global;
  2741. } else if (typeof self !== "undefined"){
  2742. win = self;
  2743. } else {
  2744. win = {};
  2745. }
  2746. module.exports = win;
  2747. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2748. },{}],16:[function(_dereq_,module,exports){
  2749. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2750. var e, m
  2751. var eLen = nBytes * 8 - mLen - 1
  2752. var eMax = (1 << eLen) - 1
  2753. var eBias = eMax >> 1
  2754. var nBits = -7
  2755. var i = isLE ? (nBytes - 1) : 0
  2756. var d = isLE ? -1 : 1
  2757. var s = buffer[offset + i]
  2758. i += d
  2759. e = s & ((1 << (-nBits)) - 1)
  2760. s >>= (-nBits)
  2761. nBits += eLen
  2762. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2763. m = e & ((1 << (-nBits)) - 1)
  2764. e >>= (-nBits)
  2765. nBits += mLen
  2766. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2767. if (e === 0) {
  2768. e = 1 - eBias
  2769. } else if (e === eMax) {
  2770. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2771. } else {
  2772. m = m + Math.pow(2, mLen)
  2773. e = e - eBias
  2774. }
  2775. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2776. }
  2777. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2778. var e, m, c
  2779. var eLen = nBytes * 8 - mLen - 1
  2780. var eMax = (1 << eLen) - 1
  2781. var eBias = eMax >> 1
  2782. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2783. var i = isLE ? 0 : (nBytes - 1)
  2784. var d = isLE ? 1 : -1
  2785. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2786. value = Math.abs(value)
  2787. if (isNaN(value) || value === Infinity) {
  2788. m = isNaN(value) ? 1 : 0
  2789. e = eMax
  2790. } else {
  2791. e = Math.floor(Math.log(value) / Math.LN2)
  2792. if (value * (c = Math.pow(2, -e)) < 1) {
  2793. e--
  2794. c *= 2
  2795. }
  2796. if (e + eBias >= 1) {
  2797. value += rt / c
  2798. } else {
  2799. value += rt * Math.pow(2, 1 - eBias)
  2800. }
  2801. if (value * c >= 2) {
  2802. e++
  2803. c /= 2
  2804. }
  2805. if (e + eBias >= eMax) {
  2806. m = 0
  2807. e = eMax
  2808. } else if (e + eBias >= 1) {
  2809. m = (value * c - 1) * Math.pow(2, mLen)
  2810. e = e + eBias
  2811. } else {
  2812. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2813. e = 0
  2814. }
  2815. }
  2816. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2817. e = (e << mLen) | m
  2818. eLen += mLen
  2819. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2820. buffer[offset + i - d] |= s * 128
  2821. }
  2822. },{}],17:[function(_dereq_,module,exports){
  2823. if (typeof Object.create === 'function') {
  2824. // implementation from standard node.js 'util' module
  2825. module.exports = function inherits(ctor, superCtor) {
  2826. ctor.super_ = superCtor
  2827. ctor.prototype = Object.create(superCtor.prototype, {
  2828. constructor: {
  2829. value: ctor,
  2830. enumerable: false,
  2831. writable: true,
  2832. configurable: true
  2833. }
  2834. });
  2835. };
  2836. } else {
  2837. // old school shim for old browsers
  2838. module.exports = function inherits(ctor, superCtor) {
  2839. ctor.super_ = superCtor
  2840. var TempCtor = function () {}
  2841. TempCtor.prototype = superCtor.prototype
  2842. ctor.prototype = new TempCtor()
  2843. ctor.prototype.constructor = ctor
  2844. }
  2845. }
  2846. },{}],18:[function(_dereq_,module,exports){
  2847. /*!
  2848. * Determine if an object is a Buffer
  2849. *
  2850. * @author Feross Aboukhadijeh <https://feross.org>
  2851. * @license MIT
  2852. */
  2853. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2854. // Object.prototype.constructor. Remove this eventually
  2855. module.exports = function (obj) {
  2856. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2857. }
  2858. function isBuffer (obj) {
  2859. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2860. }
  2861. // For Node v0.10 support. Remove this eventually.
  2862. function isSlowBuffer (obj) {
  2863. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2864. }
  2865. },{}],19:[function(_dereq_,module,exports){
  2866. module.exports = isFunction
  2867. var toString = Object.prototype.toString
  2868. function isFunction (fn) {
  2869. var string = toString.call(fn)
  2870. return string === '[object Function]' ||
  2871. (typeof fn === 'function' && string !== '[object RegExp]') ||
  2872. (typeof window !== 'undefined' &&
  2873. // IE8 and below
  2874. (fn === window.setTimeout ||
  2875. fn === window.alert ||
  2876. fn === window.confirm ||
  2877. fn === window.prompt))
  2878. };
  2879. },{}],20:[function(_dereq_,module,exports){
  2880. 'use strict';
  2881. module.exports = function (x) {
  2882. var type = typeof x;
  2883. return x !== null && (type === 'object' || type === 'function');
  2884. };
  2885. },{}],21:[function(_dereq_,module,exports){
  2886. var toString = {}.toString;
  2887. module.exports = Array.isArray || function (arr) {
  2888. return toString.call(arr) == '[object Array]';
  2889. };
  2890. },{}],22:[function(_dereq_,module,exports){
  2891. var wordWrap = _dereq_('word-wrapper')
  2892. var xtend = _dereq_('xtend')
  2893. var number = _dereq_('as-number')
  2894. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  2895. var M_WIDTHS = ['m', 'w']
  2896. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  2897. var TAB_ID = '\t'.charCodeAt(0)
  2898. var SPACE_ID = ' '.charCodeAt(0)
  2899. var ALIGN_LEFT = 0,
  2900. ALIGN_CENTER = 1,
  2901. ALIGN_RIGHT = 2
  2902. module.exports = function createLayout(opt) {
  2903. return new TextLayout(opt)
  2904. }
  2905. function TextLayout(opt) {
  2906. this.glyphs = []
  2907. this._measure = this.computeMetrics.bind(this)
  2908. this.update(opt)
  2909. }
  2910. TextLayout.prototype.update = function(opt) {
  2911. opt = xtend({
  2912. measure: this._measure
  2913. }, opt)
  2914. this._opt = opt
  2915. this._opt.tabSize = number(this._opt.tabSize, 4)
  2916. if (!opt.font)
  2917. throw new Error('must provide a valid bitmap font')
  2918. var glyphs = this.glyphs
  2919. var text = opt.text||''
  2920. var font = opt.font
  2921. this._setupSpaceGlyphs(font)
  2922. var lines = wordWrap.lines(text, opt)
  2923. var minWidth = opt.width || 0
  2924. //clear glyphs
  2925. glyphs.length = 0
  2926. //get max line width
  2927. var maxLineWidth = lines.reduce(function(prev, line) {
  2928. return Math.max(prev, line.width, minWidth)
  2929. }, 0)
  2930. //the pen position
  2931. var x = 0
  2932. var y = 0
  2933. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  2934. var baseline = font.common.base
  2935. var descender = lineHeight-baseline
  2936. var letterSpacing = opt.letterSpacing || 0
  2937. var height = lineHeight * lines.length - descender
  2938. var align = getAlignType(this._opt.align)
  2939. //draw text along baseline
  2940. y -= height
  2941. //the metrics for this text layout
  2942. this._width = maxLineWidth
  2943. this._height = height
  2944. this._descender = lineHeight - baseline
  2945. this._baseline = baseline
  2946. this._xHeight = getXHeight(font)
  2947. this._capHeight = getCapHeight(font)
  2948. this._lineHeight = lineHeight
  2949. this._ascender = lineHeight - descender - this._xHeight
  2950. //layout each glyph
  2951. var self = this
  2952. lines.forEach(function(line, lineIndex) {
  2953. var start = line.start
  2954. var end = line.end
  2955. var lineWidth = line.width
  2956. var lastGlyph
  2957. //for each glyph in that line...
  2958. for (var i=start; i<end; i++) {
  2959. var id = text.charCodeAt(i)
  2960. var glyph = self.getGlyph(font, id)
  2961. if (glyph) {
  2962. if (lastGlyph)
  2963. x += getKerning(font, lastGlyph.id, glyph.id)
  2964. var tx = x
  2965. if (align === ALIGN_CENTER)
  2966. tx += (maxLineWidth-lineWidth)/2
  2967. else if (align === ALIGN_RIGHT)
  2968. tx += (maxLineWidth-lineWidth)
  2969. glyphs.push({
  2970. position: [tx, y],
  2971. data: glyph,
  2972. index: i,
  2973. line: lineIndex
  2974. })
  2975. //move pen forward
  2976. x += glyph.xadvance + letterSpacing
  2977. lastGlyph = glyph
  2978. }
  2979. }
  2980. //next line down
  2981. y += lineHeight
  2982. x = 0
  2983. })
  2984. this._linesTotal = lines.length;
  2985. }
  2986. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  2987. //These are fallbacks, when the font doesn't include
  2988. //' ' or '\t' glyphs
  2989. this._fallbackSpaceGlyph = null
  2990. this._fallbackTabGlyph = null
  2991. if (!font.chars || font.chars.length === 0)
  2992. return
  2993. //try to get space glyph
  2994. //then fall back to the 'm' or 'w' glyphs
  2995. //then fall back to the first glyph available
  2996. var space = getGlyphById(font, SPACE_ID)
  2997. || getMGlyph(font)
  2998. || font.chars[0]
  2999. //and create a fallback for tab
  3000. var tabWidth = this._opt.tabSize * space.xadvance
  3001. this._fallbackSpaceGlyph = space
  3002. this._fallbackTabGlyph = xtend(space, {
  3003. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  3004. xoffset: 0, yoffset: 0, width: 0, height: 0
  3005. })
  3006. }
  3007. TextLayout.prototype.getGlyph = function(font, id) {
  3008. var glyph = getGlyphById(font, id)
  3009. if (glyph)
  3010. return glyph
  3011. else if (id === TAB_ID)
  3012. return this._fallbackTabGlyph
  3013. else if (id === SPACE_ID)
  3014. return this._fallbackSpaceGlyph
  3015. return null
  3016. }
  3017. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  3018. var letterSpacing = this._opt.letterSpacing || 0
  3019. var font = this._opt.font
  3020. var curPen = 0
  3021. var curWidth = 0
  3022. var count = 0
  3023. var glyph
  3024. var lastGlyph
  3025. if (!font.chars || font.chars.length === 0) {
  3026. return {
  3027. start: start,
  3028. end: start,
  3029. width: 0
  3030. }
  3031. }
  3032. end = Math.min(text.length, end)
  3033. for (var i=start; i < end; i++) {
  3034. var id = text.charCodeAt(i)
  3035. var glyph = this.getGlyph(font, id)
  3036. if (glyph) {
  3037. //move pen forward
  3038. var xoff = glyph.xoffset
  3039. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  3040. curPen += kern
  3041. var nextPen = curPen + glyph.xadvance + letterSpacing
  3042. var nextWidth = curPen + glyph.width
  3043. //we've hit our limit; we can't move onto the next glyph
  3044. if (nextWidth >= width || nextPen >= width)
  3045. break
  3046. //otherwise continue along our line
  3047. curPen = nextPen
  3048. curWidth = nextWidth
  3049. lastGlyph = glyph
  3050. }
  3051. count++
  3052. }
  3053. //make sure rightmost edge lines up with rendered glyphs
  3054. if (lastGlyph)
  3055. curWidth += lastGlyph.xoffset
  3056. return {
  3057. start: start,
  3058. end: start + count,
  3059. width: curWidth
  3060. }
  3061. }
  3062. //getters for the private vars
  3063. ;['width', 'height',
  3064. 'descender', 'ascender',
  3065. 'xHeight', 'baseline',
  3066. 'capHeight',
  3067. 'lineHeight' ].forEach(addGetter)
  3068. function addGetter(name) {
  3069. Object.defineProperty(TextLayout.prototype, name, {
  3070. get: wrapper(name),
  3071. configurable: true
  3072. })
  3073. }
  3074. //create lookups for private vars
  3075. function wrapper(name) {
  3076. return (new Function([
  3077. 'return function '+name+'() {',
  3078. ' return this._'+name,
  3079. '}'
  3080. ].join('\n')))()
  3081. }
  3082. function getGlyphById(font, id) {
  3083. if (!font.chars || font.chars.length === 0)
  3084. return null
  3085. var glyphIdx = findChar(font.chars, id)
  3086. if (glyphIdx >= 0)
  3087. return font.chars[glyphIdx]
  3088. return null
  3089. }
  3090. function getXHeight(font) {
  3091. for (var i=0; i<X_HEIGHTS.length; i++) {
  3092. var id = X_HEIGHTS[i].charCodeAt(0)
  3093. var idx = findChar(font.chars, id)
  3094. if (idx >= 0)
  3095. return font.chars[idx].height
  3096. }
  3097. return 0
  3098. }
  3099. function getMGlyph(font) {
  3100. for (var i=0; i<M_WIDTHS.length; i++) {
  3101. var id = M_WIDTHS[i].charCodeAt(0)
  3102. var idx = findChar(font.chars, id)
  3103. if (idx >= 0)
  3104. return font.chars[idx]
  3105. }
  3106. return 0
  3107. }
  3108. function getCapHeight(font) {
  3109. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  3110. var id = CAP_HEIGHTS[i].charCodeAt(0)
  3111. var idx = findChar(font.chars, id)
  3112. if (idx >= 0)
  3113. return font.chars[idx].height
  3114. }
  3115. return 0
  3116. }
  3117. function getKerning(font, left, right) {
  3118. if (!font.kernings || font.kernings.length === 0)
  3119. return 0
  3120. var table = font.kernings
  3121. for (var i=0; i<table.length; i++) {
  3122. var kern = table[i]
  3123. if (kern.first === left && kern.second === right)
  3124. return kern.amount
  3125. }
  3126. return 0
  3127. }
  3128. function getAlignType(align) {
  3129. if (align === 'center')
  3130. return ALIGN_CENTER
  3131. else if (align === 'right')
  3132. return ALIGN_RIGHT
  3133. return ALIGN_LEFT
  3134. }
  3135. function findChar (array, value, start) {
  3136. start = start || 0
  3137. for (var i = start; i < array.length; i++) {
  3138. if (array[i].id === value) {
  3139. return i
  3140. }
  3141. }
  3142. return -1
  3143. }
  3144. },{"as-number":3,"word-wrapper":47,"xtend":50}],23:[function(_dereq_,module,exports){
  3145. (function (Buffer){
  3146. var xhr = _dereq_('xhr')
  3147. var noop = function(){}
  3148. var parseASCII = _dereq_('parse-bmfont-ascii')
  3149. var parseXML = _dereq_('parse-bmfont-xml')
  3150. var readBinary = _dereq_('parse-bmfont-binary')
  3151. var isBinaryFormat = _dereq_('./lib/is-binary')
  3152. var xtend = _dereq_('xtend')
  3153. var xml2 = (function hasXML2() {
  3154. return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  3155. })()
  3156. module.exports = function(opt, cb) {
  3157. cb = typeof cb === 'function' ? cb : noop
  3158. if (typeof opt === 'string')
  3159. opt = { uri: opt }
  3160. else if (!opt)
  3161. opt = {}
  3162. var expectBinary = opt.binary
  3163. if (expectBinary)
  3164. opt = getBinaryOpts(opt)
  3165. xhr(opt, function(err, res, body) {
  3166. if (err)
  3167. return cb(err)
  3168. if (!/^2/.test(res.statusCode))
  3169. return cb(new Error('http status code: '+res.statusCode))
  3170. if (!body)
  3171. return cb(new Error('no body result'))
  3172. var binary = false
  3173. //if the response type is an array buffer,
  3174. //we need to convert it into a regular Buffer object
  3175. if (isArrayBuffer(body)) {
  3176. var array = new Uint8Array(body)
  3177. body = new Buffer(array, 'binary')
  3178. }
  3179. //now check the string/Buffer response
  3180. //and see if it has a binary BMF header
  3181. if (isBinaryFormat(body)) {
  3182. binary = true
  3183. //if we have a string, turn it into a Buffer
  3184. if (typeof body === 'string')
  3185. body = new Buffer(body, 'binary')
  3186. }
  3187. //we are not parsing a binary format, just ASCII/XML/etc
  3188. if (!binary) {
  3189. //might still be a buffer if responseType is 'arraybuffer'
  3190. if (Buffer.isBuffer(body))
  3191. body = body.toString(opt.encoding)
  3192. body = body.trim()
  3193. }
  3194. var result
  3195. try {
  3196. var type = res.headers['content-type']
  3197. if (binary)
  3198. result = readBinary(body)
  3199. else if (/json/.test(type) || body.charAt(0) === '{')
  3200. result = JSON.parse(body)
  3201. else if (/xml/.test(type) || body.charAt(0) === '<')
  3202. result = parseXML(body)
  3203. else
  3204. result = parseASCII(body)
  3205. } catch (e) {
  3206. cb(new Error('error parsing font '+e.message))
  3207. cb = noop
  3208. }
  3209. cb(null, result)
  3210. })
  3211. }
  3212. function isArrayBuffer(arr) {
  3213. var str = Object.prototype.toString
  3214. return str.call(arr) === '[object ArrayBuffer]'
  3215. }
  3216. function getBinaryOpts(opt) {
  3217. //IE10+ and other modern browsers support array buffers
  3218. if (xml2)
  3219. return xtend(opt, { responseType: 'arraybuffer' })
  3220. if (typeof self.XMLHttpRequest === 'undefined')
  3221. throw new Error('your browser does not support XHR loading')
  3222. //IE9 and XML1 browsers could still use an override
  3223. var req = new self.XMLHttpRequest()
  3224. req.overrideMimeType('text/plain; charset=x-user-defined')
  3225. return xtend({
  3226. xhr: req
  3227. }, opt)
  3228. }
  3229. }).call(this,_dereq_("buffer").Buffer)
  3230. },{"./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){
  3231. (function (Buffer){
  3232. var equal = _dereq_('buffer-equal')
  3233. var HEADER = new Buffer([66, 77, 70, 3])
  3234. module.exports = function(buf) {
  3235. if (typeof buf === 'string')
  3236. return buf.substring(0, 3) === 'BMF'
  3237. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  3238. }
  3239. }).call(this,_dereq_("buffer").Buffer)
  3240. },{"buffer":7,"buffer-equal":6}],25:[function(_dereq_,module,exports){
  3241. /*
  3242. object-assign
  3243. (c) Sindre Sorhus
  3244. @license MIT
  3245. */
  3246. 'use strict';
  3247. /* eslint-disable no-unused-vars */
  3248. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  3249. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3250. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  3251. function toObject(val) {
  3252. if (val === null || val === undefined) {
  3253. throw new TypeError('Object.assign cannot be called with null or undefined');
  3254. }
  3255. return Object(val);
  3256. }
  3257. function shouldUseNative() {
  3258. try {
  3259. if (!Object.assign) {
  3260. return false;
  3261. }
  3262. // Detect buggy property enumeration order in older V8 versions.
  3263. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  3264. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  3265. test1[5] = 'de';
  3266. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  3267. return false;
  3268. }
  3269. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3270. var test2 = {};
  3271. for (var i = 0; i < 10; i++) {
  3272. test2['_' + String.fromCharCode(i)] = i;
  3273. }
  3274. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  3275. return test2[n];
  3276. });
  3277. if (order2.join('') !== '0123456789') {
  3278. return false;
  3279. }
  3280. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3281. var test3 = {};
  3282. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  3283. test3[letter] = letter;
  3284. });
  3285. if (Object.keys(Object.assign({}, test3)).join('') !==
  3286. 'abcdefghijklmnopqrst') {
  3287. return false;
  3288. }
  3289. return true;
  3290. } catch (err) {
  3291. // We don't expect any of the above to throw, but better to be safe.
  3292. return false;
  3293. }
  3294. }
  3295. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  3296. var from;
  3297. var to = toObject(target);
  3298. var symbols;
  3299. for (var s = 1; s < arguments.length; s++) {
  3300. from = Object(arguments[s]);
  3301. for (var key in from) {
  3302. if (hasOwnProperty.call(from, key)) {
  3303. to[key] = from[key];
  3304. }
  3305. }
  3306. if (getOwnPropertySymbols) {
  3307. symbols = getOwnPropertySymbols(from);
  3308. for (var i = 0; i < symbols.length; i++) {
  3309. if (propIsEnumerable.call(from, symbols[i])) {
  3310. to[symbols[i]] = from[symbols[i]];
  3311. }
  3312. }
  3313. }
  3314. }
  3315. return to;
  3316. };
  3317. },{}],26:[function(_dereq_,module,exports){
  3318. module.exports = function parseBMFontAscii(data) {
  3319. if (!data)
  3320. throw new Error('no data provided')
  3321. data = data.toString().trim()
  3322. var output = {
  3323. pages: [],
  3324. chars: [],
  3325. kernings: []
  3326. }
  3327. var lines = data.split(/\r\n?|\n/g)
  3328. if (lines.length === 0)
  3329. throw new Error('no data in BMFont file')
  3330. for (var i = 0; i < lines.length; i++) {
  3331. var lineData = splitLine(lines[i], i)
  3332. if (!lineData) //skip empty lines
  3333. continue
  3334. if (lineData.key === 'page') {
  3335. if (typeof lineData.data.id !== 'number')
  3336. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  3337. if (typeof lineData.data.file !== 'string')
  3338. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  3339. output.pages[lineData.data.id] = lineData.data.file
  3340. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  3341. //... do nothing for these two ...
  3342. } else if (lineData.key === 'char') {
  3343. output.chars.push(lineData.data)
  3344. } else if (lineData.key === 'kerning') {
  3345. output.kernings.push(lineData.data)
  3346. } else {
  3347. output[lineData.key] = lineData.data
  3348. }
  3349. }
  3350. return output
  3351. }
  3352. function splitLine(line, idx) {
  3353. line = line.replace(/\t+/g, ' ').trim()
  3354. if (!line)
  3355. return null
  3356. var space = line.indexOf(' ')
  3357. if (space === -1)
  3358. throw new Error("no named row at line " + idx)
  3359. var key = line.substring(0, space)
  3360. line = line.substring(space + 1)
  3361. //clear "letter" field as it is non-standard and
  3362. //requires additional complexity to parse " / = symbols
  3363. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  3364. line = line.split("=")
  3365. line = line.map(function(str) {
  3366. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  3367. })
  3368. var data = []
  3369. for (var i = 0; i < line.length; i++) {
  3370. var dt = line[i]
  3371. if (i === 0) {
  3372. data.push({
  3373. key: dt[0],
  3374. data: ""
  3375. })
  3376. } else if (i === line.length - 1) {
  3377. data[data.length - 1].data = parseData(dt[0])
  3378. } else {
  3379. data[data.length - 1].data = parseData(dt[0])
  3380. data.push({
  3381. key: dt[1],
  3382. data: ""
  3383. })
  3384. }
  3385. }
  3386. var out = {
  3387. key: key,
  3388. data: {}
  3389. }
  3390. data.forEach(function(v) {
  3391. out.data[v.key] = v.data;
  3392. })
  3393. return out
  3394. }
  3395. function parseData(data) {
  3396. if (!data || data.length === 0)
  3397. return ""
  3398. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  3399. return data.substring(1, data.length - 1)
  3400. if (data.indexOf(',') !== -1)
  3401. return parseIntList(data)
  3402. return parseInt(data, 10)
  3403. }
  3404. function parseIntList(data) {
  3405. return data.split(',').map(function(val) {
  3406. return parseInt(val, 10)
  3407. })
  3408. }
  3409. },{}],27:[function(_dereq_,module,exports){
  3410. var HEADER = [66, 77, 70]
  3411. module.exports = function readBMFontBinary(buf) {
  3412. if (buf.length < 6)
  3413. throw new Error('invalid buffer length for BMFont')
  3414. var header = HEADER.every(function(byte, i) {
  3415. return buf.readUInt8(i) === byte
  3416. })
  3417. if (!header)
  3418. throw new Error('BMFont missing BMF byte header')
  3419. var i = 3
  3420. var vers = buf.readUInt8(i++)
  3421. if (vers > 3)
  3422. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  3423. var target = { kernings: [], chars: [] }
  3424. for (var b=0; b<5; b++)
  3425. i += readBlock(target, buf, i)
  3426. return target
  3427. }
  3428. function readBlock(target, buf, i) {
  3429. if (i > buf.length-1)
  3430. return 0
  3431. var blockID = buf.readUInt8(i++)
  3432. var blockSize = buf.readInt32LE(i)
  3433. i += 4
  3434. switch(blockID) {
  3435. case 1:
  3436. target.info = readInfo(buf, i)
  3437. break
  3438. case 2:
  3439. target.common = readCommon(buf, i)
  3440. break
  3441. case 3:
  3442. target.pages = readPages(buf, i, blockSize)
  3443. break
  3444. case 4:
  3445. target.chars = readChars(buf, i, blockSize)
  3446. break
  3447. case 5:
  3448. target.kernings = readKernings(buf, i, blockSize)
  3449. break
  3450. }
  3451. return 5 + blockSize
  3452. }
  3453. function readInfo(buf, i) {
  3454. var info = {}
  3455. info.size = buf.readInt16LE(i)
  3456. var bitField = buf.readUInt8(i+2)
  3457. info.smooth = (bitField >> 7) & 1
  3458. info.unicode = (bitField >> 6) & 1
  3459. info.italic = (bitField >> 5) & 1
  3460. info.bold = (bitField >> 4) & 1
  3461. //fixedHeight is only mentioned in binary spec
  3462. if ((bitField >> 3) & 1)
  3463. info.fixedHeight = 1
  3464. info.charset = buf.readUInt8(i+3) || ''
  3465. info.stretchH = buf.readUInt16LE(i+4)
  3466. info.aa = buf.readUInt8(i+6)
  3467. info.padding = [
  3468. buf.readInt8(i+7),
  3469. buf.readInt8(i+8),
  3470. buf.readInt8(i+9),
  3471. buf.readInt8(i+10)
  3472. ]
  3473. info.spacing = [
  3474. buf.readInt8(i+11),
  3475. buf.readInt8(i+12)
  3476. ]
  3477. info.outline = buf.readUInt8(i+13)
  3478. info.face = readStringNT(buf, i+14)
  3479. return info
  3480. }
  3481. function readCommon(buf, i) {
  3482. var common = {}
  3483. common.lineHeight = buf.readUInt16LE(i)
  3484. common.base = buf.readUInt16LE(i+2)
  3485. common.scaleW = buf.readUInt16LE(i+4)
  3486. common.scaleH = buf.readUInt16LE(i+6)
  3487. common.pages = buf.readUInt16LE(i+8)
  3488. var bitField = buf.readUInt8(i+10)
  3489. common.packed = 0
  3490. common.alphaChnl = buf.readUInt8(i+11)
  3491. common.redChnl = buf.readUInt8(i+12)
  3492. common.greenChnl = buf.readUInt8(i+13)
  3493. common.blueChnl = buf.readUInt8(i+14)
  3494. return common
  3495. }
  3496. function readPages(buf, i, size) {
  3497. var pages = []
  3498. var text = readNameNT(buf, i)
  3499. var len = text.length+1
  3500. var count = size / len
  3501. for (var c=0; c<count; c++) {
  3502. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  3503. i += len
  3504. }
  3505. return pages
  3506. }
  3507. function readChars(buf, i, blockSize) {
  3508. var chars = []
  3509. var count = blockSize / 20
  3510. for (var c=0; c<count; c++) {
  3511. var char = {}
  3512. var off = c*20
  3513. char.id = buf.readUInt32LE(i + 0 + off)
  3514. char.x = buf.readUInt16LE(i + 4 + off)
  3515. char.y = buf.readUInt16LE(i + 6 + off)
  3516. char.width = buf.readUInt16LE(i + 8 + off)
  3517. char.height = buf.readUInt16LE(i + 10 + off)
  3518. char.xoffset = buf.readInt16LE(i + 12 + off)
  3519. char.yoffset = buf.readInt16LE(i + 14 + off)
  3520. char.xadvance = buf.readInt16LE(i + 16 + off)
  3521. char.page = buf.readUInt8(i + 18 + off)
  3522. char.chnl = buf.readUInt8(i + 19 + off)
  3523. chars[c] = char
  3524. }
  3525. return chars
  3526. }
  3527. function readKernings(buf, i, blockSize) {
  3528. var kernings = []
  3529. var count = blockSize / 10
  3530. for (var c=0; c<count; c++) {
  3531. var kern = {}
  3532. var off = c*10
  3533. kern.first = buf.readUInt32LE(i + 0 + off)
  3534. kern.second = buf.readUInt32LE(i + 4 + off)
  3535. kern.amount = buf.readInt16LE(i + 8 + off)
  3536. kernings[c] = kern
  3537. }
  3538. return kernings
  3539. }
  3540. function readNameNT(buf, offset) {
  3541. var pos=offset
  3542. for (; pos<buf.length; pos++) {
  3543. if (buf[pos] === 0x00)
  3544. break
  3545. }
  3546. return buf.slice(offset, pos)
  3547. }
  3548. function readStringNT(buf, offset) {
  3549. return readNameNT(buf, offset).toString('utf8')
  3550. }
  3551. },{}],28:[function(_dereq_,module,exports){
  3552. var parseAttributes = _dereq_('./parse-attribs')
  3553. var parseFromString = _dereq_('xml-parse-from-string')
  3554. //In some cases element.attribute.nodeName can return
  3555. //all lowercase values.. so we need to map them to the correct
  3556. //case
  3557. var NAME_MAP = {
  3558. scaleh: 'scaleH',
  3559. scalew: 'scaleW',
  3560. stretchh: 'stretchH',
  3561. lineheight: 'lineHeight',
  3562. alphachnl: 'alphaChnl',
  3563. redchnl: 'redChnl',
  3564. greenchnl: 'greenChnl',
  3565. bluechnl: 'blueChnl'
  3566. }
  3567. module.exports = function parse(data) {
  3568. data = data.toString()
  3569. var xmlRoot = parseFromString(data)
  3570. var output = {
  3571. pages: [],
  3572. chars: [],
  3573. kernings: []
  3574. }
  3575. //get config settings
  3576. ;['info', 'common'].forEach(function(key) {
  3577. var element = xmlRoot.getElementsByTagName(key)[0]
  3578. if (element)
  3579. output[key] = parseAttributes(getAttribs(element))
  3580. })
  3581. //get page info
  3582. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3583. if (!pageRoot)
  3584. throw new Error('malformed file -- no <pages> element')
  3585. var pages = pageRoot.getElementsByTagName('page')
  3586. for (var i=0; i<pages.length; i++) {
  3587. var p = pages[i]
  3588. var id = parseInt(p.getAttribute('id'), 10)
  3589. var file = p.getAttribute('file')
  3590. if (isNaN(id))
  3591. throw new Error('malformed file -- page "id" attribute is NaN')
  3592. if (!file)
  3593. throw new Error('malformed file -- needs page "file" attribute')
  3594. output.pages[parseInt(id, 10)] = file
  3595. }
  3596. //get kernings / chars
  3597. ;['chars', 'kernings'].forEach(function(key) {
  3598. var element = xmlRoot.getElementsByTagName(key)[0]
  3599. if (!element)
  3600. return
  3601. var childTag = key.substring(0, key.length-1)
  3602. var children = element.getElementsByTagName(childTag)
  3603. for (var i=0; i<children.length; i++) {
  3604. var child = children[i]
  3605. output[key].push(parseAttributes(getAttribs(child)))
  3606. }
  3607. })
  3608. return output
  3609. }
  3610. function getAttribs(element) {
  3611. var attribs = getAttribList(element)
  3612. return attribs.reduce(function(dict, attrib) {
  3613. var key = mapName(attrib.nodeName)
  3614. dict[key] = attrib.nodeValue
  3615. return dict
  3616. }, {})
  3617. }
  3618. function getAttribList(element) {
  3619. //IE8+ and modern browsers
  3620. var attribs = []
  3621. for (var i=0; i<element.attributes.length; i++)
  3622. attribs.push(element.attributes[i])
  3623. return attribs
  3624. }
  3625. function mapName(nodeName) {
  3626. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3627. }
  3628. },{"./parse-attribs":29,"xml-parse-from-string":49}],29:[function(_dereq_,module,exports){
  3629. //Some versions of GlyphDesigner have a typo
  3630. //that causes some bugs with parsing.
  3631. //Need to confirm with recent version of the software
  3632. //to see whether this is still an issue or not.
  3633. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3634. module.exports = function parseAttributes(obj) {
  3635. if (GLYPH_DESIGNER_ERROR in obj) {
  3636. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3637. delete obj[GLYPH_DESIGNER_ERROR]
  3638. }
  3639. for (var k in obj) {
  3640. if (k === 'face' || k === 'charset')
  3641. continue
  3642. else if (k === 'padding' || k === 'spacing')
  3643. obj[k] = parseIntList(obj[k])
  3644. else
  3645. obj[k] = parseInt(obj[k], 10)
  3646. }
  3647. return obj
  3648. }
  3649. function parseIntList(data) {
  3650. return data.split(',').map(function(val) {
  3651. return parseInt(val, 10)
  3652. })
  3653. }
  3654. },{}],30:[function(_dereq_,module,exports){
  3655. var trim = _dereq_('trim')
  3656. , forEach = _dereq_('for-each')
  3657. , isArray = function(arg) {
  3658. return Object.prototype.toString.call(arg) === '[object Array]';
  3659. }
  3660. module.exports = function (headers) {
  3661. if (!headers)
  3662. return {}
  3663. var result = {}
  3664. forEach(
  3665. trim(headers).split('\n')
  3666. , function (row) {
  3667. var index = row.indexOf(':')
  3668. , key = trim(row.slice(0, index)).toLowerCase()
  3669. , value = trim(row.slice(index + 1))
  3670. if (typeof(result[key]) === 'undefined') {
  3671. result[key] = value
  3672. } else if (isArray(result[key])) {
  3673. result[key].push(value)
  3674. } else {
  3675. result[key] = [ result[key], value ]
  3676. }
  3677. }
  3678. )
  3679. return result
  3680. }
  3681. },{"for-each":14,"trim":45}],31:[function(_dereq_,module,exports){
  3682. (function (global){
  3683. var performance = global.performance || {};
  3684. var present = (function () {
  3685. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3686. while (names.length) {
  3687. var name = names.shift();
  3688. if (name in performance) {
  3689. return performance[name].bind(performance);
  3690. }
  3691. }
  3692. var dateNow = Date.now || function () { return new Date().getTime(); };
  3693. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3694. return function () {
  3695. return dateNow() - navigationStart;
  3696. };
  3697. }());
  3698. present.performanceNow = performance.now;
  3699. present.noConflict = function () {
  3700. performance.now = present.performanceNow;
  3701. };
  3702. present.conflict = function () {
  3703. performance.now = present;
  3704. };
  3705. present.conflict();
  3706. module.exports = present;
  3707. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3708. },{}],32:[function(_dereq_,module,exports){
  3709. // shim for using process in browser
  3710. var process = module.exports = {};
  3711. // cached from whatever global is present so that test runners that stub it
  3712. // don't break things. But we need to wrap it in a try catch in case it is
  3713. // wrapped in strict mode code which doesn't define any globals. It's inside a
  3714. // function because try/catches deoptimize in certain engines.
  3715. var cachedSetTimeout;
  3716. var cachedClearTimeout;
  3717. function defaultSetTimout() {
  3718. throw new Error('setTimeout has not been defined');
  3719. }
  3720. function defaultClearTimeout () {
  3721. throw new Error('clearTimeout has not been defined');
  3722. }
  3723. (function () {
  3724. try {
  3725. if (typeof setTimeout === 'function') {
  3726. cachedSetTimeout = setTimeout;
  3727. } else {
  3728. cachedSetTimeout = defaultSetTimout;
  3729. }
  3730. } catch (e) {
  3731. cachedSetTimeout = defaultSetTimout;
  3732. }
  3733. try {
  3734. if (typeof clearTimeout === 'function') {
  3735. cachedClearTimeout = clearTimeout;
  3736. } else {
  3737. cachedClearTimeout = defaultClearTimeout;
  3738. }
  3739. } catch (e) {
  3740. cachedClearTimeout = defaultClearTimeout;
  3741. }
  3742. } ())
  3743. function runTimeout(fun) {
  3744. if (cachedSetTimeout === setTimeout) {
  3745. //normal enviroments in sane situations
  3746. return setTimeout(fun, 0);
  3747. }
  3748. // if setTimeout wasn't available but was latter defined
  3749. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  3750. cachedSetTimeout = setTimeout;
  3751. return setTimeout(fun, 0);
  3752. }
  3753. try {
  3754. // when when somebody has screwed with setTimeout but no I.E. maddness
  3755. return cachedSetTimeout(fun, 0);
  3756. } catch(e){
  3757. try {
  3758. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3759. return cachedSetTimeout.call(null, fun, 0);
  3760. } catch(e){
  3761. // 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
  3762. return cachedSetTimeout.call(this, fun, 0);
  3763. }
  3764. }
  3765. }
  3766. function runClearTimeout(marker) {
  3767. if (cachedClearTimeout === clearTimeout) {
  3768. //normal enviroments in sane situations
  3769. return clearTimeout(marker);
  3770. }
  3771. // if clearTimeout wasn't available but was latter defined
  3772. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3773. cachedClearTimeout = clearTimeout;
  3774. return clearTimeout(marker);
  3775. }
  3776. try {
  3777. // when when somebody has screwed with setTimeout but no I.E. maddness
  3778. return cachedClearTimeout(marker);
  3779. } catch (e){
  3780. try {
  3781. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3782. return cachedClearTimeout.call(null, marker);
  3783. } catch (e){
  3784. // 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.
  3785. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  3786. return cachedClearTimeout.call(this, marker);
  3787. }
  3788. }
  3789. }
  3790. var queue = [];
  3791. var draining = false;
  3792. var currentQueue;
  3793. var queueIndex = -1;
  3794. function cleanUpNextTick() {
  3795. if (!draining || !currentQueue) {
  3796. return;
  3797. }
  3798. draining = false;
  3799. if (currentQueue.length) {
  3800. queue = currentQueue.concat(queue);
  3801. } else {
  3802. queueIndex = -1;
  3803. }
  3804. if (queue.length) {
  3805. drainQueue();
  3806. }
  3807. }
  3808. function drainQueue() {
  3809. if (draining) {
  3810. return;
  3811. }
  3812. var timeout = runTimeout(cleanUpNextTick);
  3813. draining = true;
  3814. var len = queue.length;
  3815. while(len) {
  3816. currentQueue = queue;
  3817. queue = [];
  3818. while (++queueIndex < len) {
  3819. if (currentQueue) {
  3820. currentQueue[queueIndex].run();
  3821. }
  3822. }
  3823. queueIndex = -1;
  3824. len = queue.length;
  3825. }
  3826. currentQueue = null;
  3827. draining = false;
  3828. runClearTimeout(timeout);
  3829. }
  3830. process.nextTick = function (fun) {
  3831. var args = new Array(arguments.length - 1);
  3832. if (arguments.length > 1) {
  3833. for (var i = 1; i < arguments.length; i++) {
  3834. args[i - 1] = arguments[i];
  3835. }
  3836. }
  3837. queue.push(new Item(fun, args));
  3838. if (queue.length === 1 && !draining) {
  3839. runTimeout(drainQueue);
  3840. }
  3841. };
  3842. // v8 likes predictible objects
  3843. function Item(fun, array) {
  3844. this.fun = fun;
  3845. this.array = array;
  3846. }
  3847. Item.prototype.run = function () {
  3848. this.fun.apply(null, this.array);
  3849. };
  3850. process.title = 'browser';
  3851. process.browser = true;
  3852. process.env = {};
  3853. process.argv = [];
  3854. process.version = ''; // empty string to avoid regexp issues
  3855. process.versions = {};
  3856. function noop() {}
  3857. process.on = noop;
  3858. process.addListener = noop;
  3859. process.once = noop;
  3860. process.off = noop;
  3861. process.removeListener = noop;
  3862. process.removeAllListeners = noop;
  3863. process.emit = noop;
  3864. process.prependListener = noop;
  3865. process.prependOnceListener = noop;
  3866. process.listeners = function (name) { return [] }
  3867. process.binding = function (name) {
  3868. throw new Error('process.binding is not supported');
  3869. };
  3870. process.cwd = function () { return '/' };
  3871. process.chdir = function (dir) {
  3872. throw new Error('process.chdir is not supported');
  3873. };
  3874. process.umask = function() { return 0; };
  3875. },{}],33:[function(_dereq_,module,exports){
  3876. (function(root) {
  3877. // Store setTimeout reference so promise-polyfill will be unaffected by
  3878. // other code modifying setTimeout (like sinon.useFakeTimers())
  3879. var setTimeoutFunc = setTimeout;
  3880. // Use polyfill for setImmediate for performance gains
  3881. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  3882. function(fn) { setTimeoutFunc(fn, 1); };
  3883. // Polyfill for Function.prototype.bind
  3884. function bind(fn, thisArg) {
  3885. return function() {
  3886. fn.apply(thisArg, arguments);
  3887. }
  3888. }
  3889. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  3890. function Promise(fn) {
  3891. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  3892. if (typeof fn !== 'function') throw new TypeError('not a function');
  3893. this._state = null;
  3894. this._value = null;
  3895. this._deferreds = []
  3896. doResolve(fn, bind(resolve, this), bind(reject, this))
  3897. }
  3898. function handle(deferred) {
  3899. var me = this;
  3900. if (this._state === null) {
  3901. this._deferreds.push(deferred);
  3902. return
  3903. }
  3904. asap(function() {
  3905. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  3906. if (cb === null) {
  3907. (me._state ? deferred.resolve : deferred.reject)(me._value);
  3908. return;
  3909. }
  3910. var ret;
  3911. try {
  3912. ret = cb(me._value);
  3913. }
  3914. catch (e) {
  3915. deferred.reject(e);
  3916. return;
  3917. }
  3918. deferred.resolve(ret);
  3919. })
  3920. }
  3921. function resolve(newValue) {
  3922. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  3923. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  3924. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  3925. var then = newValue.then;
  3926. if (typeof then === 'function') {
  3927. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  3928. return;
  3929. }
  3930. }
  3931. this._state = true;
  3932. this._value = newValue;
  3933. finale.call(this);
  3934. } catch (e) { reject.call(this, e); }
  3935. }
  3936. function reject(newValue) {
  3937. this._state = false;
  3938. this._value = newValue;
  3939. finale.call(this);
  3940. }
  3941. function finale() {
  3942. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  3943. handle.call(this, this._deferreds[i]);
  3944. }
  3945. this._deferreds = null;
  3946. }
  3947. function Handler(onFulfilled, onRejected, resolve, reject){
  3948. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  3949. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  3950. this.resolve = resolve;
  3951. this.reject = reject;
  3952. }
  3953. /**
  3954. * Take a potentially misbehaving resolver function and make sure
  3955. * onFulfilled and onRejected are only called once.
  3956. *
  3957. * Makes no guarantees about asynchrony.
  3958. */
  3959. function doResolve(fn, onFulfilled, onRejected) {
  3960. var done = false;
  3961. try {
  3962. fn(function (value) {
  3963. if (done) return;
  3964. done = true;
  3965. onFulfilled(value);
  3966. }, function (reason) {
  3967. if (done) return;
  3968. done = true;
  3969. onRejected(reason);
  3970. })
  3971. } catch (ex) {
  3972. if (done) return;
  3973. done = true;
  3974. onRejected(ex);
  3975. }
  3976. }
  3977. Promise.prototype['catch'] = function (onRejected) {
  3978. return this.then(null, onRejected);
  3979. };
  3980. Promise.prototype.then = function(onFulfilled, onRejected) {
  3981. var me = this;
  3982. return new Promise(function(resolve, reject) {
  3983. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  3984. })
  3985. };
  3986. Promise.all = function () {
  3987. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  3988. return new Promise(function (resolve, reject) {
  3989. if (args.length === 0) return resolve([]);
  3990. var remaining = args.length;
  3991. function res(i, val) {
  3992. try {
  3993. if (val && (typeof val === 'object' || typeof val === 'function')) {
  3994. var then = val.then;
  3995. if (typeof then === 'function') {
  3996. then.call(val, function (val) { res(i, val) }, reject);
  3997. return;
  3998. }
  3999. }
  4000. args[i] = val;
  4001. if (--remaining === 0) {
  4002. resolve(args);
  4003. }
  4004. } catch (ex) {
  4005. reject(ex);
  4006. }
  4007. }
  4008. for (var i = 0; i < args.length; i++) {
  4009. res(i, args[i]);
  4010. }
  4011. });
  4012. };
  4013. Promise.resolve = function (value) {
  4014. if (value && typeof value === 'object' && value.constructor === Promise) {
  4015. return value;
  4016. }
  4017. return new Promise(function (resolve) {
  4018. resolve(value);
  4019. });
  4020. };
  4021. Promise.reject = function (value) {
  4022. return new Promise(function (resolve, reject) {
  4023. reject(value);
  4024. });
  4025. };
  4026. Promise.race = function (values) {
  4027. return new Promise(function (resolve, reject) {
  4028. for(var i = 0, len = values.length; i < len; i++) {
  4029. values[i].then(resolve, reject);
  4030. }
  4031. });
  4032. };
  4033. /**
  4034. * Set the immediate function to execute callbacks
  4035. * @param fn {function} Function to execute
  4036. * @private
  4037. */
  4038. Promise._setImmediateFn = function _setImmediateFn(fn) {
  4039. asap = fn;
  4040. };
  4041. if (typeof module !== 'undefined' && module.exports) {
  4042. module.exports = Promise;
  4043. } else if (!root.Promise) {
  4044. root.Promise = Promise;
  4045. }
  4046. })(this);
  4047. },{}],34:[function(_dereq_,module,exports){
  4048. var dtype = _dereq_('dtype')
  4049. var anArray = _dereq_('an-array')
  4050. var isBuffer = _dereq_('is-buffer')
  4051. var CW = [0, 2, 3]
  4052. var CCW = [2, 1, 3]
  4053. module.exports = function createQuadElements(array, opt) {
  4054. //if user didn't specify an output array
  4055. if (!array || !(anArray(array) || isBuffer(array))) {
  4056. opt = array || {}
  4057. array = null
  4058. }
  4059. if (typeof opt === 'number') //backwards-compatible
  4060. opt = { count: opt }
  4061. else
  4062. opt = opt || {}
  4063. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  4064. var count = typeof opt.count === 'number' ? opt.count : 1
  4065. var start = (opt.start || 0)
  4066. var dir = opt.clockwise !== false ? CW : CCW,
  4067. a = dir[0],
  4068. b = dir[1],
  4069. c = dir[2]
  4070. var numIndices = count * 6
  4071. var indices = array || new (dtype(type))(numIndices)
  4072. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  4073. var x = i + start
  4074. indices[x + 0] = j + 0
  4075. indices[x + 1] = j + 1
  4076. indices[x + 2] = j + 2
  4077. indices[x + 3] = j + a
  4078. indices[x + 4] = j + b
  4079. indices[x + 5] = j + c
  4080. }
  4081. return indices
  4082. }
  4083. },{"an-array":2,"dtype":12,"is-buffer":18}],35:[function(_dereq_,module,exports){
  4084. /*:: type Attr = { [key: string]: string | number } */
  4085. /*:: type Opts = { preserveNumbers: ?boolean } */
  4086. /*
  4087. style-attr
  4088. ====
  4089. Very simple parsing and stringifying of style attributes.
  4090. `parse`
  4091. ----
  4092. Convert a style attribute string to an object.
  4093. */
  4094. /*:: declare function parse (raw: string, opts: ?Opts): Attr */
  4095. function parse(raw, opts) {
  4096. opts = opts || {};
  4097. var preserveNumbers = opts.preserveNumbers;
  4098. var trim = function (s) {
  4099. return s.trim();
  4100. };
  4101. var obj = {};
  4102. getKeyValueChunks(raw).map(trim).filter(Boolean).forEach(function (item) {
  4103. // split with `.indexOf` rather than `.split` because the value may also contain colons.
  4104. var pos = item.indexOf(':');
  4105. var key = item.substr(0, pos).trim();
  4106. var val = item.substr(pos + 1).trim();
  4107. if (preserveNumbers && isNumeric(val)) {
  4108. val = Number(val);
  4109. }
  4110. obj[key] = val;
  4111. });
  4112. return obj;
  4113. }
  4114. /*
  4115. `isNumeric`
  4116. ----
  4117. Check if a value is numeric.
  4118. Via: https://stackoverflow.com/a/1830844/9324
  4119. */
  4120. /*:: declare function isNumeric (n: any): boolean */
  4121. function isNumeric(n) {
  4122. return !isNaN(parseFloat(n)) && isFinite(n);
  4123. }
  4124. /*
  4125. `getKeyValueChunks`
  4126. ----
  4127. Split a string into chunks matching `<key>: <value>`
  4128. */
  4129. /*:: declare function getKeyValueChunks (raw: string): Array<string> */
  4130. function getKeyValueChunks(raw) {
  4131. var chunks = [];
  4132. var offset = 0;
  4133. var sep = ';';
  4134. var hasUnclosedUrl = /url\([^\)]+$/;
  4135. var chunk = '';
  4136. var nextSplit;
  4137. while (offset < raw.length) {
  4138. nextSplit = raw.indexOf(sep, offset);
  4139. if (nextSplit === -1) {
  4140. nextSplit = raw.length;
  4141. }
  4142. chunk += raw.substring(offset, nextSplit);
  4143. // data URIs can contain semicolons, so make sure we get the whole thing
  4144. if (hasUnclosedUrl.test(chunk)) {
  4145. chunk += ';';
  4146. offset = nextSplit + 1;
  4147. continue;
  4148. }
  4149. chunks.push(chunk);
  4150. chunk = '';
  4151. offset = nextSplit + 1;
  4152. }
  4153. return chunks;
  4154. }
  4155. /*
  4156. `stringify`
  4157. ----
  4158. Convert an object into an attribute string
  4159. */
  4160. /*:: declare function stringify (obj: Attr): string */
  4161. function stringify(obj) {
  4162. return Object.keys(obj).map(function (key) {
  4163. return key + ':' + obj[key];
  4164. }).join(';');
  4165. }
  4166. /*
  4167. `normalize`
  4168. ----
  4169. Normalize an attribute string (eg. collapse duplicates)
  4170. */
  4171. /*:: declare function normalize (str: string, opts: ?Opts): string */
  4172. function normalize(str, opts) {
  4173. return stringify(parse(str, opts));
  4174. }
  4175. module.exports.parse = parse;
  4176. module.exports.stringify = stringify;
  4177. module.exports.normalize = normalize;
  4178. },{}],36:[function(_dereq_,module,exports){
  4179. var createLayout = _dereq_('layout-bmfont-text')
  4180. var inherits = _dereq_('inherits')
  4181. var createIndices = _dereq_('quad-indices')
  4182. var buffer = _dereq_('three-buffer-vertex-data')
  4183. var assign = _dereq_('object-assign')
  4184. var vertices = _dereq_('./lib/vertices')
  4185. var utils = _dereq_('./lib/utils')
  4186. var Base = THREE.BufferGeometry
  4187. module.exports = function createTextGeometry (opt) {
  4188. return new TextGeometry(opt)
  4189. }
  4190. function TextGeometry (opt) {
  4191. Base.call(this)
  4192. if (typeof opt === 'string') {
  4193. opt = { text: opt }
  4194. }
  4195. // use these as default values for any subsequent
  4196. // calls to update()
  4197. this._opt = assign({}, opt)
  4198. // also do an initial setup...
  4199. if (opt) this.update(opt)
  4200. }
  4201. inherits(TextGeometry, Base)
  4202. TextGeometry.prototype.update = function (opt) {
  4203. if (typeof opt === 'string') {
  4204. opt = { text: opt }
  4205. }
  4206. // use constructor defaults
  4207. opt = assign({}, this._opt, opt)
  4208. if (!opt.font) {
  4209. throw new TypeError('must specify a { font } in options')
  4210. }
  4211. this.layout = createLayout(opt)
  4212. // get vec2 texcoords
  4213. var flipY = opt.flipY !== false
  4214. // the desired BMFont data
  4215. var font = opt.font
  4216. // determine texture size from font file
  4217. var texWidth = font.common.scaleW
  4218. var texHeight = font.common.scaleH
  4219. // get visible glyphs
  4220. var glyphs = this.layout.glyphs.filter(function (glyph) {
  4221. var bitmap = glyph.data
  4222. return bitmap.width * bitmap.height > 0
  4223. })
  4224. // provide visible glyphs for convenience
  4225. this.visibleGlyphs = glyphs
  4226. // get common vertex data
  4227. var positions = vertices.positions(glyphs)
  4228. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  4229. var indices = createIndices({
  4230. clockwise: true,
  4231. type: 'uint16',
  4232. count: glyphs.length
  4233. })
  4234. // update vertex data
  4235. buffer.index(this, indices, 1, 'uint16')
  4236. buffer.attr(this, 'position', positions, 2)
  4237. buffer.attr(this, 'uv', uvs, 2)
  4238. // update multipage data
  4239. if (!opt.multipage && 'page' in this.attributes) {
  4240. // disable multipage rendering
  4241. this.removeAttribute('page')
  4242. } else if (opt.multipage) {
  4243. var pages = vertices.pages(glyphs)
  4244. // enable multipage rendering
  4245. buffer.attr(this, 'page', pages, 1)
  4246. }
  4247. }
  4248. TextGeometry.prototype.computeBoundingSphere = function () {
  4249. if (this.boundingSphere === null) {
  4250. this.boundingSphere = new THREE.Sphere()
  4251. }
  4252. var positions = this.attributes.position.array
  4253. var itemSize = this.attributes.position.itemSize
  4254. if (!positions || !itemSize || positions.length < 2) {
  4255. this.boundingSphere.radius = 0
  4256. this.boundingSphere.center.set(0, 0, 0)
  4257. return
  4258. }
  4259. utils.computeSphere(positions, this.boundingSphere)
  4260. if (isNaN(this.boundingSphere.radius)) {
  4261. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  4262. 'Computed radius is NaN. The ' +
  4263. '"position" attribute is likely to have NaN values.')
  4264. }
  4265. }
  4266. TextGeometry.prototype.computeBoundingBox = function () {
  4267. if (this.boundingBox === null) {
  4268. this.boundingBox = new THREE.Box3()
  4269. }
  4270. var bbox = this.boundingBox
  4271. var positions = this.attributes.position.array
  4272. var itemSize = this.attributes.position.itemSize
  4273. if (!positions || !itemSize || positions.length < 2) {
  4274. bbox.makeEmpty()
  4275. return
  4276. }
  4277. utils.computeBox(positions, bbox)
  4278. }
  4279. },{"./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){
  4280. var itemSize = 2
  4281. var box = { min: [0, 0], max: [0, 0] }
  4282. function bounds (positions) {
  4283. var count = positions.length / itemSize
  4284. box.min[0] = positions[0]
  4285. box.min[1] = positions[1]
  4286. box.max[0] = positions[0]
  4287. box.max[1] = positions[1]
  4288. for (var i = 0; i < count; i++) {
  4289. var x = positions[i * itemSize + 0]
  4290. var y = positions[i * itemSize + 1]
  4291. box.min[0] = Math.min(x, box.min[0])
  4292. box.min[1] = Math.min(y, box.min[1])
  4293. box.max[0] = Math.max(x, box.max[0])
  4294. box.max[1] = Math.max(y, box.max[1])
  4295. }
  4296. }
  4297. module.exports.computeBox = function (positions, output) {
  4298. bounds(positions)
  4299. output.min.set(box.min[0], box.min[1], 0)
  4300. output.max.set(box.max[0], box.max[1], 0)
  4301. }
  4302. module.exports.computeSphere = function (positions, output) {
  4303. bounds(positions)
  4304. var minX = box.min[0]
  4305. var minY = box.min[1]
  4306. var maxX = box.max[0]
  4307. var maxY = box.max[1]
  4308. var width = maxX - minX
  4309. var height = maxY - minY
  4310. var length = Math.sqrt(width * width + height * height)
  4311. output.center.set(minX + width / 2, minY + height / 2, 0)
  4312. output.radius = length / 2
  4313. }
  4314. },{}],38:[function(_dereq_,module,exports){
  4315. module.exports.pages = function pages (glyphs) {
  4316. var pages = new Float32Array(glyphs.length * 4 * 1)
  4317. var i = 0
  4318. glyphs.forEach(function (glyph) {
  4319. var id = glyph.data.page || 0
  4320. pages[i++] = id
  4321. pages[i++] = id
  4322. pages[i++] = id
  4323. pages[i++] = id
  4324. })
  4325. return pages
  4326. }
  4327. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  4328. var uvs = new Float32Array(glyphs.length * 4 * 2)
  4329. var i = 0
  4330. glyphs.forEach(function (glyph) {
  4331. var bitmap = glyph.data
  4332. var bw = (bitmap.x + bitmap.width)
  4333. var bh = (bitmap.y + bitmap.height)
  4334. // top left position
  4335. var u0 = bitmap.x / texWidth
  4336. var v1 = bitmap.y / texHeight
  4337. var u1 = bw / texWidth
  4338. var v0 = bh / texHeight
  4339. if (flipY) {
  4340. v1 = (texHeight - bitmap.y) / texHeight
  4341. v0 = (texHeight - bh) / texHeight
  4342. }
  4343. // BL
  4344. uvs[i++] = u0
  4345. uvs[i++] = v1
  4346. // TL
  4347. uvs[i++] = u0
  4348. uvs[i++] = v0
  4349. // TR
  4350. uvs[i++] = u1
  4351. uvs[i++] = v0
  4352. // BR
  4353. uvs[i++] = u1
  4354. uvs[i++] = v1
  4355. })
  4356. return uvs
  4357. }
  4358. module.exports.positions = function positions (glyphs) {
  4359. var positions = new Float32Array(glyphs.length * 4 * 2)
  4360. var i = 0
  4361. glyphs.forEach(function (glyph) {
  4362. var bitmap = glyph.data
  4363. // bottom left position
  4364. var x = glyph.position[0] + bitmap.xoffset
  4365. var y = glyph.position[1] + bitmap.yoffset
  4366. // quad size
  4367. var w = bitmap.width
  4368. var h = bitmap.height
  4369. // BL
  4370. positions[i++] = x
  4371. positions[i++] = y
  4372. // TL
  4373. positions[i++] = x
  4374. positions[i++] = y + h
  4375. // TR
  4376. positions[i++] = x + w
  4377. positions[i++] = y + h
  4378. // BR
  4379. positions[i++] = x + w
  4380. positions[i++] = y
  4381. })
  4382. return positions
  4383. }
  4384. },{}],39:[function(_dereq_,module,exports){
  4385. var flatten = _dereq_('flatten-vertex-data')
  4386. var warned = false;
  4387. module.exports.attr = setAttribute
  4388. module.exports.index = setIndex
  4389. function setIndex (geometry, data, itemSize, dtype) {
  4390. if (typeof itemSize !== 'number') itemSize = 1
  4391. if (typeof dtype !== 'string') dtype = 'uint16'
  4392. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  4393. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  4394. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  4395. if (newAttrib) {
  4396. if (isR69) geometry.addAttribute('index', newAttrib)
  4397. else geometry.index = newAttrib
  4398. }
  4399. }
  4400. function setAttribute (geometry, key, data, itemSize, dtype) {
  4401. if (typeof itemSize !== 'number') itemSize = 3
  4402. if (typeof dtype !== 'string') dtype = 'float32'
  4403. if (Array.isArray(data) &&
  4404. Array.isArray(data[0]) &&
  4405. data[0].length !== itemSize) {
  4406. throw new Error('Nested vertex array has unexpected size; expected ' +
  4407. itemSize + ' but found ' + data[0].length)
  4408. }
  4409. var attrib = geometry.getAttribute(key)
  4410. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  4411. if (newAttrib) {
  4412. geometry.addAttribute(key, newAttrib)
  4413. }
  4414. }
  4415. function updateAttribute (attrib, data, itemSize, dtype) {
  4416. data = data || []
  4417. if (!attrib || rebuildAttribute(attrib, data, itemSize)) {
  4418. // create a new array with desired type
  4419. data = flatten(data, dtype)
  4420. var needsNewBuffer = attrib && typeof attrib.setArray !== 'function'
  4421. if (!attrib || needsNewBuffer) {
  4422. // We are on an old version of ThreeJS which can't
  4423. // support growing / shrinking buffers, so we need
  4424. // to build a new buffer
  4425. if (needsNewBuffer && !warned) {
  4426. warned = true
  4427. console.warn([
  4428. 'A WebGL buffer is being updated with a new size or itemSize, ',
  4429. 'however this version of ThreeJS only supports fixed-size buffers.',
  4430. '\nThe old buffer may still be kept in memory.\n',
  4431. 'To avoid memory leaks, it is recommended that you dispose ',
  4432. 'your geometries and create new ones, or update to ThreeJS r82 or newer.\n',
  4433. 'See here for discussion:\n',
  4434. 'https://github.com/mrdoob/three.js/pull/9631'
  4435. ].join(''))
  4436. }
  4437. // Build a new attribute
  4438. attrib = new THREE.BufferAttribute(data, itemSize);
  4439. }
  4440. attrib.itemSize = itemSize
  4441. attrib.needsUpdate = true
  4442. // New versions of ThreeJS suggest using setArray
  4443. // to change the data. It will use bufferData internally,
  4444. // so you can change the array size without any issues
  4445. if (typeof attrib.setArray === 'function') {
  4446. attrib.setArray(data)
  4447. }
  4448. return attrib
  4449. } else {
  4450. // copy data into the existing array
  4451. flatten(data, attrib.array)
  4452. attrib.needsUpdate = true
  4453. return null
  4454. }
  4455. }
  4456. // Test whether the attribute needs to be re-created,
  4457. // returns false if we can re-use it as-is.
  4458. function rebuildAttribute (attrib, data, itemSize) {
  4459. if (attrib.itemSize !== itemSize) return true
  4460. if (!attrib.array) return true
  4461. var attribLength = attrib.array.length
  4462. if (Array.isArray(data) && Array.isArray(data[0])) {
  4463. // [ [ x, y, z ] ]
  4464. return attribLength !== data.length * itemSize
  4465. } else {
  4466. // [ x, y, z ]
  4467. return attribLength !== data.length
  4468. }
  4469. return false
  4470. }
  4471. },{"flatten-vertex-data":13}],40:[function(_dereq_,module,exports){
  4472. (function (global, factory) {
  4473. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4474. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4475. (factory((global.THREE = {})));
  4476. }(this, (function (exports) { 'use strict';
  4477. // Polyfills
  4478. if ( Number.EPSILON === undefined ) {
  4479. Number.EPSILON = Math.pow( 2, - 52 );
  4480. }
  4481. if ( Number.isInteger === undefined ) {
  4482. // Missing in IE
  4483. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  4484. Number.isInteger = function ( value ) {
  4485. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  4486. };
  4487. }
  4488. //
  4489. if ( Math.sign === undefined ) {
  4490. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  4491. Math.sign = function ( x ) {
  4492. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  4493. };
  4494. }
  4495. if ( 'name' in Function.prototype === false ) {
  4496. // Missing in IE
  4497. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  4498. Object.defineProperty( Function.prototype, 'name', {
  4499. get: function () {
  4500. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  4501. }
  4502. } );
  4503. }
  4504. if ( Object.assign === undefined ) {
  4505. // Missing in IE
  4506. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  4507. ( function () {
  4508. Object.assign = function ( target ) {
  4509. if ( target === undefined || target === null ) {
  4510. throw new TypeError( 'Cannot convert undefined or null to object' );
  4511. }
  4512. var output = Object( target );
  4513. for ( var index = 1; index < arguments.length; index ++ ) {
  4514. var source = arguments[ index ];
  4515. if ( source !== undefined && source !== null ) {
  4516. for ( var nextKey in source ) {
  4517. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  4518. output[ nextKey ] = source[ nextKey ];
  4519. }
  4520. }
  4521. }
  4522. }
  4523. return output;
  4524. };
  4525. } )();
  4526. }
  4527. /**
  4528. * https://github.com/mrdoob/eventdispatcher.js/
  4529. */
  4530. function EventDispatcher() {}
  4531. Object.assign( EventDispatcher.prototype, {
  4532. addEventListener: function ( type, listener ) {
  4533. if ( this._listeners === undefined ) this._listeners = {};
  4534. var listeners = this._listeners;
  4535. if ( listeners[ type ] === undefined ) {
  4536. listeners[ type ] = [];
  4537. }
  4538. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4539. listeners[ type ].push( listener );
  4540. }
  4541. },
  4542. hasEventListener: function ( type, listener ) {
  4543. if ( this._listeners === undefined ) return false;
  4544. var listeners = this._listeners;
  4545. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  4546. },
  4547. removeEventListener: function ( type, listener ) {
  4548. if ( this._listeners === undefined ) return;
  4549. var listeners = this._listeners;
  4550. var listenerArray = listeners[ type ];
  4551. if ( listenerArray !== undefined ) {
  4552. var index = listenerArray.indexOf( listener );
  4553. if ( index !== - 1 ) {
  4554. listenerArray.splice( index, 1 );
  4555. }
  4556. }
  4557. },
  4558. dispatchEvent: function ( event ) {
  4559. if ( this._listeners === undefined ) return;
  4560. var listeners = this._listeners;
  4561. var listenerArray = listeners[ event.type ];
  4562. if ( listenerArray !== undefined ) {
  4563. event.target = this;
  4564. var array = listenerArray.slice( 0 );
  4565. for ( var i = 0, l = array.length; i < l; i ++ ) {
  4566. array[ i ].call( this, event );
  4567. }
  4568. }
  4569. }
  4570. } );
  4571. var REVISION = '92';
  4572. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  4573. var CullFaceNone = 0;
  4574. var CullFaceBack = 1;
  4575. var CullFaceFront = 2;
  4576. var CullFaceFrontBack = 3;
  4577. var FrontFaceDirectionCW = 0;
  4578. var FrontFaceDirectionCCW = 1;
  4579. var BasicShadowMap = 0;
  4580. var PCFShadowMap = 1;
  4581. var PCFSoftShadowMap = 2;
  4582. var FrontSide = 0;
  4583. var BackSide = 1;
  4584. var DoubleSide = 2;
  4585. var FlatShading = 1;
  4586. var SmoothShading = 2;
  4587. var NoColors = 0;
  4588. var FaceColors = 1;
  4589. var VertexColors = 2;
  4590. var NoBlending = 0;
  4591. var NormalBlending = 1;
  4592. var AdditiveBlending = 2;
  4593. var SubtractiveBlending = 3;
  4594. var MultiplyBlending = 4;
  4595. var CustomBlending = 5;
  4596. var AddEquation = 100;
  4597. var SubtractEquation = 101;
  4598. var ReverseSubtractEquation = 102;
  4599. var MinEquation = 103;
  4600. var MaxEquation = 104;
  4601. var ZeroFactor = 200;
  4602. var OneFactor = 201;
  4603. var SrcColorFactor = 202;
  4604. var OneMinusSrcColorFactor = 203;
  4605. var SrcAlphaFactor = 204;
  4606. var OneMinusSrcAlphaFactor = 205;
  4607. var DstAlphaFactor = 206;
  4608. var OneMinusDstAlphaFactor = 207;
  4609. var DstColorFactor = 208;
  4610. var OneMinusDstColorFactor = 209;
  4611. var SrcAlphaSaturateFactor = 210;
  4612. var NeverDepth = 0;
  4613. var AlwaysDepth = 1;
  4614. var LessDepth = 2;
  4615. var LessEqualDepth = 3;
  4616. var EqualDepth = 4;
  4617. var GreaterEqualDepth = 5;
  4618. var GreaterDepth = 6;
  4619. var NotEqualDepth = 7;
  4620. var MultiplyOperation = 0;
  4621. var MixOperation = 1;
  4622. var AddOperation = 2;
  4623. var NoToneMapping = 0;
  4624. var LinearToneMapping = 1;
  4625. var ReinhardToneMapping = 2;
  4626. var Uncharted2ToneMapping = 3;
  4627. var CineonToneMapping = 4;
  4628. var UVMapping = 300;
  4629. var CubeReflectionMapping = 301;
  4630. var CubeRefractionMapping = 302;
  4631. var EquirectangularReflectionMapping = 303;
  4632. var EquirectangularRefractionMapping = 304;
  4633. var SphericalReflectionMapping = 305;
  4634. var CubeUVReflectionMapping = 306;
  4635. var CubeUVRefractionMapping = 307;
  4636. var RepeatWrapping = 1000;
  4637. var ClampToEdgeWrapping = 1001;
  4638. var MirroredRepeatWrapping = 1002;
  4639. var NearestFilter = 1003;
  4640. var NearestMipMapNearestFilter = 1004;
  4641. var NearestMipMapLinearFilter = 1005;
  4642. var LinearFilter = 1006;
  4643. var LinearMipMapNearestFilter = 1007;
  4644. var LinearMipMapLinearFilter = 1008;
  4645. var UnsignedByteType = 1009;
  4646. var ByteType = 1010;
  4647. var ShortType = 1011;
  4648. var UnsignedShortType = 1012;
  4649. var IntType = 1013;
  4650. var UnsignedIntType = 1014;
  4651. var FloatType = 1015;
  4652. var HalfFloatType = 1016;
  4653. var UnsignedShort4444Type = 1017;
  4654. var UnsignedShort5551Type = 1018;
  4655. var UnsignedShort565Type = 1019;
  4656. var UnsignedInt248Type = 1020;
  4657. var AlphaFormat = 1021;
  4658. var RGBFormat = 1022;
  4659. var RGBAFormat = 1023;
  4660. var LuminanceFormat = 1024;
  4661. var LuminanceAlphaFormat = 1025;
  4662. var RGBEFormat = RGBAFormat;
  4663. var DepthFormat = 1026;
  4664. var DepthStencilFormat = 1027;
  4665. var RGB_S3TC_DXT1_Format = 33776;
  4666. var RGBA_S3TC_DXT1_Format = 33777;
  4667. var RGBA_S3TC_DXT3_Format = 33778;
  4668. var RGBA_S3TC_DXT5_Format = 33779;
  4669. var RGB_PVRTC_4BPPV1_Format = 35840;
  4670. var RGB_PVRTC_2BPPV1_Format = 35841;
  4671. var RGBA_PVRTC_4BPPV1_Format = 35842;
  4672. var RGBA_PVRTC_2BPPV1_Format = 35843;
  4673. var RGB_ETC1_Format = 36196;
  4674. var RGBA_ASTC_4x4_Format = 37808;
  4675. var RGBA_ASTC_5x4_Format = 37809;
  4676. var RGBA_ASTC_5x5_Format = 37810;
  4677. var RGBA_ASTC_6x5_Format = 37811;
  4678. var RGBA_ASTC_6x6_Format = 37812;
  4679. var RGBA_ASTC_8x5_Format = 37813;
  4680. var RGBA_ASTC_8x6_Format = 37814;
  4681. var RGBA_ASTC_8x8_Format = 37815;
  4682. var RGBA_ASTC_10x5_Format = 37816;
  4683. var RGBA_ASTC_10x6_Format = 37817;
  4684. var RGBA_ASTC_10x8_Format = 37818;
  4685. var RGBA_ASTC_10x10_Format = 37819;
  4686. var RGBA_ASTC_12x10_Format = 37820;
  4687. var RGBA_ASTC_12x12_Format = 37821;
  4688. var LoopOnce = 2200;
  4689. var LoopRepeat = 2201;
  4690. var LoopPingPong = 2202;
  4691. var InterpolateDiscrete = 2300;
  4692. var InterpolateLinear = 2301;
  4693. var InterpolateSmooth = 2302;
  4694. var ZeroCurvatureEnding = 2400;
  4695. var ZeroSlopeEnding = 2401;
  4696. var WrapAroundEnding = 2402;
  4697. var TrianglesDrawMode = 0;
  4698. var TriangleStripDrawMode = 1;
  4699. var TriangleFanDrawMode = 2;
  4700. var LinearEncoding = 3000;
  4701. var sRGBEncoding = 3001;
  4702. var GammaEncoding = 3007;
  4703. var RGBEEncoding = 3002;
  4704. var LogLuvEncoding = 3003;
  4705. var RGBM7Encoding = 3004;
  4706. var RGBM16Encoding = 3005;
  4707. var RGBDEncoding = 3006;
  4708. var BasicDepthPacking = 3200;
  4709. var RGBADepthPacking = 3201;
  4710. /**
  4711. * @author alteredq / http://alteredqualia.com/
  4712. * @author mrdoob / http://mrdoob.com/
  4713. */
  4714. var _Math = {
  4715. DEG2RAD: Math.PI / 180,
  4716. RAD2DEG: 180 / Math.PI,
  4717. generateUUID: ( function () {
  4718. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  4719. var lut = [];
  4720. for ( var i = 0; i < 256; i ++ ) {
  4721. lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  4722. }
  4723. return function generateUUID() {
  4724. var d0 = Math.random() * 0xffffffff | 0;
  4725. var d1 = Math.random() * 0xffffffff | 0;
  4726. var d2 = Math.random() * 0xffffffff | 0;
  4727. var d3 = Math.random() * 0xffffffff | 0;
  4728. var uuid = lut[ d0 & 0xff ] + lut[ d0 >> 8 & 0xff ] + lut[ d0 >> 16 & 0xff ] + lut[ d0 >> 24 & 0xff ] + '-' +
  4729. lut[ d1 & 0xff ] + lut[ d1 >> 8 & 0xff ] + '-' + lut[ d1 >> 16 & 0x0f | 0x40 ] + lut[ d1 >> 24 & 0xff ] + '-' +
  4730. lut[ d2 & 0x3f | 0x80 ] + lut[ d2 >> 8 & 0xff ] + '-' + lut[ d2 >> 16 & 0xff ] + lut[ d2 >> 24 & 0xff ] +
  4731. lut[ d3 & 0xff ] + lut[ d3 >> 8 & 0xff ] + lut[ d3 >> 16 & 0xff ] + lut[ d3 >> 24 & 0xff ];
  4732. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  4733. return uuid.toUpperCase();
  4734. };
  4735. } )(),
  4736. clamp: function ( value, min, max ) {
  4737. return Math.max( min, Math.min( max, value ) );
  4738. },
  4739. // compute euclidian modulo of m % n
  4740. // https://en.wikipedia.org/wiki/Modulo_operation
  4741. euclideanModulo: function ( n, m ) {
  4742. return ( ( n % m ) + m ) % m;
  4743. },
  4744. // Linear mapping from range <a1, a2> to range <b1, b2>
  4745. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4746. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4747. },
  4748. // https://en.wikipedia.org/wiki/Linear_interpolation
  4749. lerp: function ( x, y, t ) {
  4750. return ( 1 - t ) * x + t * y;
  4751. },
  4752. // http://en.wikipedia.org/wiki/Smoothstep
  4753. smoothstep: function ( x, min, max ) {
  4754. if ( x <= min ) return 0;
  4755. if ( x >= max ) return 1;
  4756. x = ( x - min ) / ( max - min );
  4757. return x * x * ( 3 - 2 * x );
  4758. },
  4759. smootherstep: function ( x, min, max ) {
  4760. if ( x <= min ) return 0;
  4761. if ( x >= max ) return 1;
  4762. x = ( x - min ) / ( max - min );
  4763. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4764. },
  4765. // Random integer from <low, high> interval
  4766. randInt: function ( low, high ) {
  4767. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4768. },
  4769. // Random float from <low, high> interval
  4770. randFloat: function ( low, high ) {
  4771. return low + Math.random() * ( high - low );
  4772. },
  4773. // Random float from <-range/2, range/2> interval
  4774. randFloatSpread: function ( range ) {
  4775. return range * ( 0.5 - Math.random() );
  4776. },
  4777. degToRad: function ( degrees ) {
  4778. return degrees * _Math.DEG2RAD;
  4779. },
  4780. radToDeg: function ( radians ) {
  4781. return radians * _Math.RAD2DEG;
  4782. },
  4783. isPowerOfTwo: function ( value ) {
  4784. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4785. },
  4786. ceilPowerOfTwo: function ( value ) {
  4787. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  4788. },
  4789. floorPowerOfTwo: function ( value ) {
  4790. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  4791. }
  4792. };
  4793. /**
  4794. * @author mrdoob / http://mrdoob.com/
  4795. * @author philogb / http://blog.thejit.org/
  4796. * @author egraether / http://egraether.com/
  4797. * @author zz85 / http://www.lab4games.net/zz85/blog
  4798. */
  4799. function Vector2( x, y ) {
  4800. this.x = x || 0;
  4801. this.y = y || 0;
  4802. }
  4803. Object.defineProperties( Vector2.prototype, {
  4804. "width": {
  4805. get: function () {
  4806. return this.x;
  4807. },
  4808. set: function ( value ) {
  4809. this.x = value;
  4810. }
  4811. },
  4812. "height": {
  4813. get: function () {
  4814. return this.y;
  4815. },
  4816. set: function ( value ) {
  4817. this.y = value;
  4818. }
  4819. }
  4820. } );
  4821. Object.assign( Vector2.prototype, {
  4822. isVector2: true,
  4823. set: function ( x, y ) {
  4824. this.x = x;
  4825. this.y = y;
  4826. return this;
  4827. },
  4828. setScalar: function ( scalar ) {
  4829. this.x = scalar;
  4830. this.y = scalar;
  4831. return this;
  4832. },
  4833. setX: function ( x ) {
  4834. this.x = x;
  4835. return this;
  4836. },
  4837. setY: function ( y ) {
  4838. this.y = y;
  4839. return this;
  4840. },
  4841. setComponent: function ( index, value ) {
  4842. switch ( index ) {
  4843. case 0: this.x = value; break;
  4844. case 1: this.y = value; break;
  4845. default: throw new Error( 'index is out of range: ' + index );
  4846. }
  4847. return this;
  4848. },
  4849. getComponent: function ( index ) {
  4850. switch ( index ) {
  4851. case 0: return this.x;
  4852. case 1: return this.y;
  4853. default: throw new Error( 'index is out of range: ' + index );
  4854. }
  4855. },
  4856. clone: function () {
  4857. return new this.constructor( this.x, this.y );
  4858. },
  4859. copy: function ( v ) {
  4860. this.x = v.x;
  4861. this.y = v.y;
  4862. return this;
  4863. },
  4864. add: function ( v, w ) {
  4865. if ( w !== undefined ) {
  4866. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  4867. return this.addVectors( v, w );
  4868. }
  4869. this.x += v.x;
  4870. this.y += v.y;
  4871. return this;
  4872. },
  4873. addScalar: function ( s ) {
  4874. this.x += s;
  4875. this.y += s;
  4876. return this;
  4877. },
  4878. addVectors: function ( a, b ) {
  4879. this.x = a.x + b.x;
  4880. this.y = a.y + b.y;
  4881. return this;
  4882. },
  4883. addScaledVector: function ( v, s ) {
  4884. this.x += v.x * s;
  4885. this.y += v.y * s;
  4886. return this;
  4887. },
  4888. sub: function ( v, w ) {
  4889. if ( w !== undefined ) {
  4890. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  4891. return this.subVectors( v, w );
  4892. }
  4893. this.x -= v.x;
  4894. this.y -= v.y;
  4895. return this;
  4896. },
  4897. subScalar: function ( s ) {
  4898. this.x -= s;
  4899. this.y -= s;
  4900. return this;
  4901. },
  4902. subVectors: function ( a, b ) {
  4903. this.x = a.x - b.x;
  4904. this.y = a.y - b.y;
  4905. return this;
  4906. },
  4907. multiply: function ( v ) {
  4908. this.x *= v.x;
  4909. this.y *= v.y;
  4910. return this;
  4911. },
  4912. multiplyScalar: function ( scalar ) {
  4913. this.x *= scalar;
  4914. this.y *= scalar;
  4915. return this;
  4916. },
  4917. divide: function ( v ) {
  4918. this.x /= v.x;
  4919. this.y /= v.y;
  4920. return this;
  4921. },
  4922. divideScalar: function ( scalar ) {
  4923. return this.multiplyScalar( 1 / scalar );
  4924. },
  4925. applyMatrix3: function ( m ) {
  4926. var x = this.x, y = this.y;
  4927. var e = m.elements;
  4928. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  4929. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  4930. return this;
  4931. },
  4932. min: function ( v ) {
  4933. this.x = Math.min( this.x, v.x );
  4934. this.y = Math.min( this.y, v.y );
  4935. return this;
  4936. },
  4937. max: function ( v ) {
  4938. this.x = Math.max( this.x, v.x );
  4939. this.y = Math.max( this.y, v.y );
  4940. return this;
  4941. },
  4942. clamp: function ( min, max ) {
  4943. // assumes min < max, componentwise
  4944. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  4945. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  4946. return this;
  4947. },
  4948. clampScalar: function () {
  4949. var min = new Vector2();
  4950. var max = new Vector2();
  4951. return function clampScalar( minVal, maxVal ) {
  4952. min.set( minVal, minVal );
  4953. max.set( maxVal, maxVal );
  4954. return this.clamp( min, max );
  4955. };
  4956. }(),
  4957. clampLength: function ( min, max ) {
  4958. var length = this.length();
  4959. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  4960. },
  4961. floor: function () {
  4962. this.x = Math.floor( this.x );
  4963. this.y = Math.floor( this.y );
  4964. return this;
  4965. },
  4966. ceil: function () {
  4967. this.x = Math.ceil( this.x );
  4968. this.y = Math.ceil( this.y );
  4969. return this;
  4970. },
  4971. round: function () {
  4972. this.x = Math.round( this.x );
  4973. this.y = Math.round( this.y );
  4974. return this;
  4975. },
  4976. roundToZero: function () {
  4977. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  4978. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  4979. return this;
  4980. },
  4981. negate: function () {
  4982. this.x = - this.x;
  4983. this.y = - this.y;
  4984. return this;
  4985. },
  4986. dot: function ( v ) {
  4987. return this.x * v.x + this.y * v.y;
  4988. },
  4989. lengthSq: function () {
  4990. return this.x * this.x + this.y * this.y;
  4991. },
  4992. length: function () {
  4993. return Math.sqrt( this.x * this.x + this.y * this.y );
  4994. },
  4995. manhattanLength: function () {
  4996. return Math.abs( this.x ) + Math.abs( this.y );
  4997. },
  4998. normalize: function () {
  4999. return this.divideScalar( this.length() || 1 );
  5000. },
  5001. angle: function () {
  5002. // computes the angle in radians with respect to the positive x-axis
  5003. var angle = Math.atan2( this.y, this.x );
  5004. if ( angle < 0 ) angle += 2 * Math.PI;
  5005. return angle;
  5006. },
  5007. distanceTo: function ( v ) {
  5008. return Math.sqrt( this.distanceToSquared( v ) );
  5009. },
  5010. distanceToSquared: function ( v ) {
  5011. var dx = this.x - v.x, dy = this.y - v.y;
  5012. return dx * dx + dy * dy;
  5013. },
  5014. manhattanDistanceTo: function ( v ) {
  5015. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  5016. },
  5017. setLength: function ( length ) {
  5018. return this.normalize().multiplyScalar( length );
  5019. },
  5020. lerp: function ( v, alpha ) {
  5021. this.x += ( v.x - this.x ) * alpha;
  5022. this.y += ( v.y - this.y ) * alpha;
  5023. return this;
  5024. },
  5025. lerpVectors: function ( v1, v2, alpha ) {
  5026. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  5027. },
  5028. equals: function ( v ) {
  5029. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  5030. },
  5031. fromArray: function ( array, offset ) {
  5032. if ( offset === undefined ) offset = 0;
  5033. this.x = array[ offset ];
  5034. this.y = array[ offset + 1 ];
  5035. return this;
  5036. },
  5037. toArray: function ( array, offset ) {
  5038. if ( array === undefined ) array = [];
  5039. if ( offset === undefined ) offset = 0;
  5040. array[ offset ] = this.x;
  5041. array[ offset + 1 ] = this.y;
  5042. return array;
  5043. },
  5044. fromBufferAttribute: function ( attribute, index, offset ) {
  5045. if ( offset !== undefined ) {
  5046. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  5047. }
  5048. this.x = attribute.getX( index );
  5049. this.y = attribute.getY( index );
  5050. return this;
  5051. },
  5052. rotateAround: function ( center, angle ) {
  5053. var c = Math.cos( angle ), s = Math.sin( angle );
  5054. var x = this.x - center.x;
  5055. var y = this.y - center.y;
  5056. this.x = x * c - y * s + center.x;
  5057. this.y = x * s + y * c + center.y;
  5058. return this;
  5059. }
  5060. } );
  5061. /**
  5062. * @author mrdoob / http://mrdoob.com/
  5063. * @author supereggbert / http://www.paulbrunt.co.uk/
  5064. * @author philogb / http://blog.thejit.org/
  5065. * @author jordi_ros / http://plattsoft.com
  5066. * @author D1plo1d / http://github.com/D1plo1d
  5067. * @author alteredq / http://alteredqualia.com/
  5068. * @author mikael emtinger / http://gomo.se/
  5069. * @author timknip / http://www.floorplanner.com/
  5070. * @author bhouston / http://clara.io
  5071. * @author WestLangley / http://github.com/WestLangley
  5072. */
  5073. function Matrix4() {
  5074. this.elements = [
  5075. 1, 0, 0, 0,
  5076. 0, 1, 0, 0,
  5077. 0, 0, 1, 0,
  5078. 0, 0, 0, 1
  5079. ];
  5080. if ( arguments.length > 0 ) {
  5081. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  5082. }
  5083. }
  5084. Object.assign( Matrix4.prototype, {
  5085. isMatrix4: true,
  5086. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  5087. var te = this.elements;
  5088. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  5089. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  5090. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  5091. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  5092. return this;
  5093. },
  5094. identity: function () {
  5095. this.set(
  5096. 1, 0, 0, 0,
  5097. 0, 1, 0, 0,
  5098. 0, 0, 1, 0,
  5099. 0, 0, 0, 1
  5100. );
  5101. return this;
  5102. },
  5103. clone: function () {
  5104. return new Matrix4().fromArray( this.elements );
  5105. },
  5106. copy: function ( m ) {
  5107. var te = this.elements;
  5108. var me = m.elements;
  5109. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  5110. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  5111. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  5112. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  5113. return this;
  5114. },
  5115. copyPosition: function ( m ) {
  5116. var te = this.elements, me = m.elements;
  5117. te[ 12 ] = me[ 12 ];
  5118. te[ 13 ] = me[ 13 ];
  5119. te[ 14 ] = me[ 14 ];
  5120. return this;
  5121. },
  5122. extractBasis: function ( xAxis, yAxis, zAxis ) {
  5123. xAxis.setFromMatrixColumn( this, 0 );
  5124. yAxis.setFromMatrixColumn( this, 1 );
  5125. zAxis.setFromMatrixColumn( this, 2 );
  5126. return this;
  5127. },
  5128. makeBasis: function ( xAxis, yAxis, zAxis ) {
  5129. this.set(
  5130. xAxis.x, yAxis.x, zAxis.x, 0,
  5131. xAxis.y, yAxis.y, zAxis.y, 0,
  5132. xAxis.z, yAxis.z, zAxis.z, 0,
  5133. 0, 0, 0, 1
  5134. );
  5135. return this;
  5136. },
  5137. extractRotation: function () {
  5138. var v1 = new Vector3();
  5139. return function extractRotation( m ) {
  5140. var te = this.elements;
  5141. var me = m.elements;
  5142. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  5143. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  5144. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  5145. te[ 0 ] = me[ 0 ] * scaleX;
  5146. te[ 1 ] = me[ 1 ] * scaleX;
  5147. te[ 2 ] = me[ 2 ] * scaleX;
  5148. te[ 4 ] = me[ 4 ] * scaleY;
  5149. te[ 5 ] = me[ 5 ] * scaleY;
  5150. te[ 6 ] = me[ 6 ] * scaleY;
  5151. te[ 8 ] = me[ 8 ] * scaleZ;
  5152. te[ 9 ] = me[ 9 ] * scaleZ;
  5153. te[ 10 ] = me[ 10 ] * scaleZ;
  5154. return this;
  5155. };
  5156. }(),
  5157. makeRotationFromEuler: function ( euler ) {
  5158. if ( ! ( euler && euler.isEuler ) ) {
  5159. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  5160. }
  5161. var te = this.elements;
  5162. var x = euler.x, y = euler.y, z = euler.z;
  5163. var a = Math.cos( x ), b = Math.sin( x );
  5164. var c = Math.cos( y ), d = Math.sin( y );
  5165. var e = Math.cos( z ), f = Math.sin( z );
  5166. if ( euler.order === 'XYZ' ) {
  5167. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  5168. te[ 0 ] = c * e;
  5169. te[ 4 ] = - c * f;
  5170. te[ 8 ] = d;
  5171. te[ 1 ] = af + be * d;
  5172. te[ 5 ] = ae - bf * d;
  5173. te[ 9 ] = - b * c;
  5174. te[ 2 ] = bf - ae * d;
  5175. te[ 6 ] = be + af * d;
  5176. te[ 10 ] = a * c;
  5177. } else if ( euler.order === 'YXZ' ) {
  5178. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  5179. te[ 0 ] = ce + df * b;
  5180. te[ 4 ] = de * b - cf;
  5181. te[ 8 ] = a * d;
  5182. te[ 1 ] = a * f;
  5183. te[ 5 ] = a * e;
  5184. te[ 9 ] = - b;
  5185. te[ 2 ] = cf * b - de;
  5186. te[ 6 ] = df + ce * b;
  5187. te[ 10 ] = a * c;
  5188. } else if ( euler.order === 'ZXY' ) {
  5189. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  5190. te[ 0 ] = ce - df * b;
  5191. te[ 4 ] = - a * f;
  5192. te[ 8 ] = de + cf * b;
  5193. te[ 1 ] = cf + de * b;
  5194. te[ 5 ] = a * e;
  5195. te[ 9 ] = df - ce * b;
  5196. te[ 2 ] = - a * d;
  5197. te[ 6 ] = b;
  5198. te[ 10 ] = a * c;
  5199. } else if ( euler.order === 'ZYX' ) {
  5200. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  5201. te[ 0 ] = c * e;
  5202. te[ 4 ] = be * d - af;
  5203. te[ 8 ] = ae * d + bf;
  5204. te[ 1 ] = c * f;
  5205. te[ 5 ] = bf * d + ae;
  5206. te[ 9 ] = af * d - be;
  5207. te[ 2 ] = - d;
  5208. te[ 6 ] = b * c;
  5209. te[ 10 ] = a * c;
  5210. } else if ( euler.order === 'YZX' ) {
  5211. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  5212. te[ 0 ] = c * e;
  5213. te[ 4 ] = bd - ac * f;
  5214. te[ 8 ] = bc * f + ad;
  5215. te[ 1 ] = f;
  5216. te[ 5 ] = a * e;
  5217. te[ 9 ] = - b * e;
  5218. te[ 2 ] = - d * e;
  5219. te[ 6 ] = ad * f + bc;
  5220. te[ 10 ] = ac - bd * f;
  5221. } else if ( euler.order === 'XZY' ) {
  5222. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  5223. te[ 0 ] = c * e;
  5224. te[ 4 ] = - f;
  5225. te[ 8 ] = d * e;
  5226. te[ 1 ] = ac * f + bd;
  5227. te[ 5 ] = a * e;
  5228. te[ 9 ] = ad * f - bc;
  5229. te[ 2 ] = bc * f - ad;
  5230. te[ 6 ] = b * e;
  5231. te[ 10 ] = bd * f + ac;
  5232. }
  5233. // last column
  5234. te[ 3 ] = 0;
  5235. te[ 7 ] = 0;
  5236. te[ 11 ] = 0;
  5237. // bottom row
  5238. te[ 12 ] = 0;
  5239. te[ 13 ] = 0;
  5240. te[ 14 ] = 0;
  5241. te[ 15 ] = 1;
  5242. return this;
  5243. },
  5244. makeRotationFromQuaternion: function ( q ) {
  5245. var te = this.elements;
  5246. var x = q._x, y = q._y, z = q._z, w = q._w;
  5247. var x2 = x + x, y2 = y + y, z2 = z + z;
  5248. var xx = x * x2, xy = x * y2, xz = x * z2;
  5249. var yy = y * y2, yz = y * z2, zz = z * z2;
  5250. var wx = w * x2, wy = w * y2, wz = w * z2;
  5251. te[ 0 ] = 1 - ( yy + zz );
  5252. te[ 4 ] = xy - wz;
  5253. te[ 8 ] = xz + wy;
  5254. te[ 1 ] = xy + wz;
  5255. te[ 5 ] = 1 - ( xx + zz );
  5256. te[ 9 ] = yz - wx;
  5257. te[ 2 ] = xz - wy;
  5258. te[ 6 ] = yz + wx;
  5259. te[ 10 ] = 1 - ( xx + yy );
  5260. // last column
  5261. te[ 3 ] = 0;
  5262. te[ 7 ] = 0;
  5263. te[ 11 ] = 0;
  5264. // bottom row
  5265. te[ 12 ] = 0;
  5266. te[ 13 ] = 0;
  5267. te[ 14 ] = 0;
  5268. te[ 15 ] = 1;
  5269. return this;
  5270. },
  5271. lookAt: function () {
  5272. var x = new Vector3();
  5273. var y = new Vector3();
  5274. var z = new Vector3();
  5275. return function lookAt( eye, target, up ) {
  5276. var te = this.elements;
  5277. z.subVectors( eye, target );
  5278. if ( z.lengthSq() === 0 ) {
  5279. // eye and target are in the same position
  5280. z.z = 1;
  5281. }
  5282. z.normalize();
  5283. x.crossVectors( up, z );
  5284. if ( x.lengthSq() === 0 ) {
  5285. // up and z are parallel
  5286. if ( Math.abs( up.z ) === 1 ) {
  5287. z.x += 0.0001;
  5288. } else {
  5289. z.z += 0.0001;
  5290. }
  5291. z.normalize();
  5292. x.crossVectors( up, z );
  5293. }
  5294. x.normalize();
  5295. y.crossVectors( z, x );
  5296. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  5297. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  5298. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  5299. return this;
  5300. };
  5301. }(),
  5302. multiply: function ( m, n ) {
  5303. if ( n !== undefined ) {
  5304. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  5305. return this.multiplyMatrices( m, n );
  5306. }
  5307. return this.multiplyMatrices( this, m );
  5308. },
  5309. premultiply: function ( m ) {
  5310. return this.multiplyMatrices( m, this );
  5311. },
  5312. multiplyMatrices: function ( a, b ) {
  5313. var ae = a.elements;
  5314. var be = b.elements;
  5315. var te = this.elements;
  5316. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  5317. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  5318. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  5319. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  5320. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  5321. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  5322. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  5323. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  5324. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  5325. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  5326. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  5327. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  5328. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  5329. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  5330. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  5331. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  5332. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  5333. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  5334. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  5335. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  5336. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  5337. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  5338. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  5339. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  5340. return this;
  5341. },
  5342. multiplyScalar: function ( s ) {
  5343. var te = this.elements;
  5344. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  5345. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  5346. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  5347. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  5348. return this;
  5349. },
  5350. applyToBufferAttribute: function () {
  5351. var v1 = new Vector3();
  5352. return function applyToBufferAttribute( attribute ) {
  5353. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5354. v1.x = attribute.getX( i );
  5355. v1.y = attribute.getY( i );
  5356. v1.z = attribute.getZ( i );
  5357. v1.applyMatrix4( this );
  5358. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5359. }
  5360. return attribute;
  5361. };
  5362. }(),
  5363. determinant: function () {
  5364. var te = this.elements;
  5365. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  5366. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  5367. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  5368. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  5369. //TODO: make this more efficient
  5370. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  5371. return (
  5372. n41 * (
  5373. + n14 * n23 * n32
  5374. - n13 * n24 * n32
  5375. - n14 * n22 * n33
  5376. + n12 * n24 * n33
  5377. + n13 * n22 * n34
  5378. - n12 * n23 * n34
  5379. ) +
  5380. n42 * (
  5381. + n11 * n23 * n34
  5382. - n11 * n24 * n33
  5383. + n14 * n21 * n33
  5384. - n13 * n21 * n34
  5385. + n13 * n24 * n31
  5386. - n14 * n23 * n31
  5387. ) +
  5388. n43 * (
  5389. + n11 * n24 * n32
  5390. - n11 * n22 * n34
  5391. - n14 * n21 * n32
  5392. + n12 * n21 * n34
  5393. + n14 * n22 * n31
  5394. - n12 * n24 * n31
  5395. ) +
  5396. n44 * (
  5397. - n13 * n22 * n31
  5398. - n11 * n23 * n32
  5399. + n11 * n22 * n33
  5400. + n13 * n21 * n32
  5401. - n12 * n21 * n33
  5402. + n12 * n23 * n31
  5403. )
  5404. );
  5405. },
  5406. transpose: function () {
  5407. var te = this.elements;
  5408. var tmp;
  5409. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  5410. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  5411. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  5412. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  5413. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  5414. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  5415. return this;
  5416. },
  5417. setPosition: function ( v ) {
  5418. var te = this.elements;
  5419. te[ 12 ] = v.x;
  5420. te[ 13 ] = v.y;
  5421. te[ 14 ] = v.z;
  5422. return this;
  5423. },
  5424. getInverse: function ( m, throwOnDegenerate ) {
  5425. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  5426. var te = this.elements,
  5427. me = m.elements,
  5428. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  5429. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  5430. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  5431. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  5432. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  5433. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  5434. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  5435. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  5436. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  5437. if ( det === 0 ) {
  5438. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  5439. if ( throwOnDegenerate === true ) {
  5440. throw new Error( msg );
  5441. } else {
  5442. console.warn( msg );
  5443. }
  5444. return this.identity();
  5445. }
  5446. var detInv = 1 / det;
  5447. te[ 0 ] = t11 * detInv;
  5448. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  5449. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  5450. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  5451. te[ 4 ] = t12 * detInv;
  5452. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  5453. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  5454. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  5455. te[ 8 ] = t13 * detInv;
  5456. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  5457. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  5458. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  5459. te[ 12 ] = t14 * detInv;
  5460. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  5461. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  5462. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  5463. return this;
  5464. },
  5465. scale: function ( v ) {
  5466. var te = this.elements;
  5467. var x = v.x, y = v.y, z = v.z;
  5468. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  5469. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  5470. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  5471. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  5472. return this;
  5473. },
  5474. getMaxScaleOnAxis: function () {
  5475. var te = this.elements;
  5476. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  5477. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  5478. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  5479. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  5480. },
  5481. makeTranslation: function ( x, y, z ) {
  5482. this.set(
  5483. 1, 0, 0, x,
  5484. 0, 1, 0, y,
  5485. 0, 0, 1, z,
  5486. 0, 0, 0, 1
  5487. );
  5488. return this;
  5489. },
  5490. makeRotationX: function ( theta ) {
  5491. var c = Math.cos( theta ), s = Math.sin( theta );
  5492. this.set(
  5493. 1, 0, 0, 0,
  5494. 0, c, - s, 0,
  5495. 0, s, c, 0,
  5496. 0, 0, 0, 1
  5497. );
  5498. return this;
  5499. },
  5500. makeRotationY: function ( theta ) {
  5501. var c = Math.cos( theta ), s = Math.sin( theta );
  5502. this.set(
  5503. c, 0, s, 0,
  5504. 0, 1, 0, 0,
  5505. - s, 0, c, 0,
  5506. 0, 0, 0, 1
  5507. );
  5508. return this;
  5509. },
  5510. makeRotationZ: function ( theta ) {
  5511. var c = Math.cos( theta ), s = Math.sin( theta );
  5512. this.set(
  5513. c, - s, 0, 0,
  5514. s, c, 0, 0,
  5515. 0, 0, 1, 0,
  5516. 0, 0, 0, 1
  5517. );
  5518. return this;
  5519. },
  5520. makeRotationAxis: function ( axis, angle ) {
  5521. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  5522. var c = Math.cos( angle );
  5523. var s = Math.sin( angle );
  5524. var t = 1 - c;
  5525. var x = axis.x, y = axis.y, z = axis.z;
  5526. var tx = t * x, ty = t * y;
  5527. this.set(
  5528. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  5529. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  5530. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  5531. 0, 0, 0, 1
  5532. );
  5533. return this;
  5534. },
  5535. makeScale: function ( x, y, z ) {
  5536. this.set(
  5537. x, 0, 0, 0,
  5538. 0, y, 0, 0,
  5539. 0, 0, z, 0,
  5540. 0, 0, 0, 1
  5541. );
  5542. return this;
  5543. },
  5544. makeShear: function ( x, y, z ) {
  5545. this.set(
  5546. 1, y, z, 0,
  5547. x, 1, z, 0,
  5548. x, y, 1, 0,
  5549. 0, 0, 0, 1
  5550. );
  5551. return this;
  5552. },
  5553. compose: function ( position, quaternion, scale ) {
  5554. this.makeRotationFromQuaternion( quaternion );
  5555. this.scale( scale );
  5556. this.setPosition( position );
  5557. return this;
  5558. },
  5559. decompose: function () {
  5560. var vector = new Vector3();
  5561. var matrix = new Matrix4();
  5562. return function decompose( position, quaternion, scale ) {
  5563. var te = this.elements;
  5564. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  5565. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  5566. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  5567. // if determine is negative, we need to invert one scale
  5568. var det = this.determinant();
  5569. if ( det < 0 ) sx = - sx;
  5570. position.x = te[ 12 ];
  5571. position.y = te[ 13 ];
  5572. position.z = te[ 14 ];
  5573. // scale the rotation part
  5574. matrix.copy( this );
  5575. var invSX = 1 / sx;
  5576. var invSY = 1 / sy;
  5577. var invSZ = 1 / sz;
  5578. matrix.elements[ 0 ] *= invSX;
  5579. matrix.elements[ 1 ] *= invSX;
  5580. matrix.elements[ 2 ] *= invSX;
  5581. matrix.elements[ 4 ] *= invSY;
  5582. matrix.elements[ 5 ] *= invSY;
  5583. matrix.elements[ 6 ] *= invSY;
  5584. matrix.elements[ 8 ] *= invSZ;
  5585. matrix.elements[ 9 ] *= invSZ;
  5586. matrix.elements[ 10 ] *= invSZ;
  5587. quaternion.setFromRotationMatrix( matrix );
  5588. scale.x = sx;
  5589. scale.y = sy;
  5590. scale.z = sz;
  5591. return this;
  5592. };
  5593. }(),
  5594. makePerspective: function ( left, right, top, bottom, near, far ) {
  5595. if ( far === undefined ) {
  5596. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  5597. }
  5598. var te = this.elements;
  5599. var x = 2 * near / ( right - left );
  5600. var y = 2 * near / ( top - bottom );
  5601. var a = ( right + left ) / ( right - left );
  5602. var b = ( top + bottom ) / ( top - bottom );
  5603. var c = - ( far + near ) / ( far - near );
  5604. var d = - 2 * far * near / ( far - near );
  5605. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  5606. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  5607. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  5608. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  5609. return this;
  5610. },
  5611. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  5612. var te = this.elements;
  5613. var w = 1.0 / ( right - left );
  5614. var h = 1.0 / ( top - bottom );
  5615. var p = 1.0 / ( far - near );
  5616. var x = ( right + left ) * w;
  5617. var y = ( top + bottom ) * h;
  5618. var z = ( far + near ) * p;
  5619. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  5620. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  5621. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  5622. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  5623. return this;
  5624. },
  5625. equals: function ( matrix ) {
  5626. var te = this.elements;
  5627. var me = matrix.elements;
  5628. for ( var i = 0; i < 16; i ++ ) {
  5629. if ( te[ i ] !== me[ i ] ) return false;
  5630. }
  5631. return true;
  5632. },
  5633. fromArray: function ( array, offset ) {
  5634. if ( offset === undefined ) offset = 0;
  5635. for ( var i = 0; i < 16; i ++ ) {
  5636. this.elements[ i ] = array[ i + offset ];
  5637. }
  5638. return this;
  5639. },
  5640. toArray: function ( array, offset ) {
  5641. if ( array === undefined ) array = [];
  5642. if ( offset === undefined ) offset = 0;
  5643. var te = this.elements;
  5644. array[ offset ] = te[ 0 ];
  5645. array[ offset + 1 ] = te[ 1 ];
  5646. array[ offset + 2 ] = te[ 2 ];
  5647. array[ offset + 3 ] = te[ 3 ];
  5648. array[ offset + 4 ] = te[ 4 ];
  5649. array[ offset + 5 ] = te[ 5 ];
  5650. array[ offset + 6 ] = te[ 6 ];
  5651. array[ offset + 7 ] = te[ 7 ];
  5652. array[ offset + 8 ] = te[ 8 ];
  5653. array[ offset + 9 ] = te[ 9 ];
  5654. array[ offset + 10 ] = te[ 10 ];
  5655. array[ offset + 11 ] = te[ 11 ];
  5656. array[ offset + 12 ] = te[ 12 ];
  5657. array[ offset + 13 ] = te[ 13 ];
  5658. array[ offset + 14 ] = te[ 14 ];
  5659. array[ offset + 15 ] = te[ 15 ];
  5660. return array;
  5661. }
  5662. } );
  5663. /**
  5664. * @author mikael emtinger / http://gomo.se/
  5665. * @author alteredq / http://alteredqualia.com/
  5666. * @author WestLangley / http://github.com/WestLangley
  5667. * @author bhouston / http://clara.io
  5668. */
  5669. function Quaternion( x, y, z, w ) {
  5670. this._x = x || 0;
  5671. this._y = y || 0;
  5672. this._z = z || 0;
  5673. this._w = ( w !== undefined ) ? w : 1;
  5674. }
  5675. Object.assign( Quaternion, {
  5676. slerp: function ( qa, qb, qm, t ) {
  5677. return qm.copy( qa ).slerp( qb, t );
  5678. },
  5679. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5680. // fuzz-free, array-based Quaternion SLERP operation
  5681. var x0 = src0[ srcOffset0 + 0 ],
  5682. y0 = src0[ srcOffset0 + 1 ],
  5683. z0 = src0[ srcOffset0 + 2 ],
  5684. w0 = src0[ srcOffset0 + 3 ],
  5685. x1 = src1[ srcOffset1 + 0 ],
  5686. y1 = src1[ srcOffset1 + 1 ],
  5687. z1 = src1[ srcOffset1 + 2 ],
  5688. w1 = src1[ srcOffset1 + 3 ];
  5689. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5690. var s = 1 - t,
  5691. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5692. dir = ( cos >= 0 ? 1 : - 1 ),
  5693. sqrSin = 1 - cos * cos;
  5694. // Skip the Slerp for tiny steps to avoid numeric problems:
  5695. if ( sqrSin > Number.EPSILON ) {
  5696. var sin = Math.sqrt( sqrSin ),
  5697. len = Math.atan2( sin, cos * dir );
  5698. s = Math.sin( s * len ) / sin;
  5699. t = Math.sin( t * len ) / sin;
  5700. }
  5701. var tDir = t * dir;
  5702. x0 = x0 * s + x1 * tDir;
  5703. y0 = y0 * s + y1 * tDir;
  5704. z0 = z0 * s + z1 * tDir;
  5705. w0 = w0 * s + w1 * tDir;
  5706. // Normalize in case we just did a lerp:
  5707. if ( s === 1 - t ) {
  5708. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5709. x0 *= f;
  5710. y0 *= f;
  5711. z0 *= f;
  5712. w0 *= f;
  5713. }
  5714. }
  5715. dst[ dstOffset ] = x0;
  5716. dst[ dstOffset + 1 ] = y0;
  5717. dst[ dstOffset + 2 ] = z0;
  5718. dst[ dstOffset + 3 ] = w0;
  5719. }
  5720. } );
  5721. Object.defineProperties( Quaternion.prototype, {
  5722. x: {
  5723. get: function () {
  5724. return this._x;
  5725. },
  5726. set: function ( value ) {
  5727. this._x = value;
  5728. this.onChangeCallback();
  5729. }
  5730. },
  5731. y: {
  5732. get: function () {
  5733. return this._y;
  5734. },
  5735. set: function ( value ) {
  5736. this._y = value;
  5737. this.onChangeCallback();
  5738. }
  5739. },
  5740. z: {
  5741. get: function () {
  5742. return this._z;
  5743. },
  5744. set: function ( value ) {
  5745. this._z = value;
  5746. this.onChangeCallback();
  5747. }
  5748. },
  5749. w: {
  5750. get: function () {
  5751. return this._w;
  5752. },
  5753. set: function ( value ) {
  5754. this._w = value;
  5755. this.onChangeCallback();
  5756. }
  5757. }
  5758. } );
  5759. Object.assign( Quaternion.prototype, {
  5760. set: function ( x, y, z, w ) {
  5761. this._x = x;
  5762. this._y = y;
  5763. this._z = z;
  5764. this._w = w;
  5765. this.onChangeCallback();
  5766. return this;
  5767. },
  5768. clone: function () {
  5769. return new this.constructor( this._x, this._y, this._z, this._w );
  5770. },
  5771. copy: function ( quaternion ) {
  5772. this._x = quaternion.x;
  5773. this._y = quaternion.y;
  5774. this._z = quaternion.z;
  5775. this._w = quaternion.w;
  5776. this.onChangeCallback();
  5777. return this;
  5778. },
  5779. setFromEuler: function ( euler, update ) {
  5780. if ( ! ( euler && euler.isEuler ) ) {
  5781. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5782. }
  5783. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  5784. // http://www.mathworks.com/matlabcentral/fileexchange/
  5785. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  5786. // content/SpinCalc.m
  5787. var cos = Math.cos;
  5788. var sin = Math.sin;
  5789. var c1 = cos( x / 2 );
  5790. var c2 = cos( y / 2 );
  5791. var c3 = cos( z / 2 );
  5792. var s1 = sin( x / 2 );
  5793. var s2 = sin( y / 2 );
  5794. var s3 = sin( z / 2 );
  5795. if ( order === 'XYZ' ) {
  5796. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5797. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5798. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5799. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5800. } else if ( order === 'YXZ' ) {
  5801. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5802. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5803. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5804. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5805. } else if ( order === 'ZXY' ) {
  5806. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5807. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5808. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5809. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5810. } else if ( order === 'ZYX' ) {
  5811. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5812. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5813. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5814. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5815. } else if ( order === 'YZX' ) {
  5816. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5817. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5818. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5819. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5820. } else if ( order === 'XZY' ) {
  5821. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5822. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5823. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5824. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5825. }
  5826. if ( update !== false ) this.onChangeCallback();
  5827. return this;
  5828. },
  5829. setFromAxisAngle: function ( axis, angle ) {
  5830. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  5831. // assumes axis is normalized
  5832. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  5833. this._x = axis.x * s;
  5834. this._y = axis.y * s;
  5835. this._z = axis.z * s;
  5836. this._w = Math.cos( halfAngle );
  5837. this.onChangeCallback();
  5838. return this;
  5839. },
  5840. setFromRotationMatrix: function ( m ) {
  5841. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  5842. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5843. var te = m.elements,
  5844. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5845. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5846. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  5847. trace = m11 + m22 + m33,
  5848. s;
  5849. if ( trace > 0 ) {
  5850. s = 0.5 / Math.sqrt( trace + 1.0 );
  5851. this._w = 0.25 / s;
  5852. this._x = ( m32 - m23 ) * s;
  5853. this._y = ( m13 - m31 ) * s;
  5854. this._z = ( m21 - m12 ) * s;
  5855. } else if ( m11 > m22 && m11 > m33 ) {
  5856. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  5857. this._w = ( m32 - m23 ) / s;
  5858. this._x = 0.25 * s;
  5859. this._y = ( m12 + m21 ) / s;
  5860. this._z = ( m13 + m31 ) / s;
  5861. } else if ( m22 > m33 ) {
  5862. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  5863. this._w = ( m13 - m31 ) / s;
  5864. this._x = ( m12 + m21 ) / s;
  5865. this._y = 0.25 * s;
  5866. this._z = ( m23 + m32 ) / s;
  5867. } else {
  5868. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  5869. this._w = ( m21 - m12 ) / s;
  5870. this._x = ( m13 + m31 ) / s;
  5871. this._y = ( m23 + m32 ) / s;
  5872. this._z = 0.25 * s;
  5873. }
  5874. this.onChangeCallback();
  5875. return this;
  5876. },
  5877. setFromUnitVectors: function () {
  5878. // assumes direction vectors vFrom and vTo are normalized
  5879. var v1 = new Vector3();
  5880. var r;
  5881. var EPS = 0.000001;
  5882. return function setFromUnitVectors( vFrom, vTo ) {
  5883. if ( v1 === undefined ) v1 = new Vector3();
  5884. r = vFrom.dot( vTo ) + 1;
  5885. if ( r < EPS ) {
  5886. r = 0;
  5887. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  5888. v1.set( - vFrom.y, vFrom.x, 0 );
  5889. } else {
  5890. v1.set( 0, - vFrom.z, vFrom.y );
  5891. }
  5892. } else {
  5893. v1.crossVectors( vFrom, vTo );
  5894. }
  5895. this._x = v1.x;
  5896. this._y = v1.y;
  5897. this._z = v1.z;
  5898. this._w = r;
  5899. return this.normalize();
  5900. };
  5901. }(),
  5902. inverse: function () {
  5903. // quaternion is assumed to have unit length
  5904. return this.conjugate();
  5905. },
  5906. conjugate: function () {
  5907. this._x *= - 1;
  5908. this._y *= - 1;
  5909. this._z *= - 1;
  5910. this.onChangeCallback();
  5911. return this;
  5912. },
  5913. dot: function ( v ) {
  5914. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  5915. },
  5916. lengthSq: function () {
  5917. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  5918. },
  5919. length: function () {
  5920. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  5921. },
  5922. normalize: function () {
  5923. var l = this.length();
  5924. if ( l === 0 ) {
  5925. this._x = 0;
  5926. this._y = 0;
  5927. this._z = 0;
  5928. this._w = 1;
  5929. } else {
  5930. l = 1 / l;
  5931. this._x = this._x * l;
  5932. this._y = this._y * l;
  5933. this._z = this._z * l;
  5934. this._w = this._w * l;
  5935. }
  5936. this.onChangeCallback();
  5937. return this;
  5938. },
  5939. multiply: function ( q, p ) {
  5940. if ( p !== undefined ) {
  5941. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  5942. return this.multiplyQuaternions( q, p );
  5943. }
  5944. return this.multiplyQuaternions( this, q );
  5945. },
  5946. premultiply: function ( q ) {
  5947. return this.multiplyQuaternions( q, this );
  5948. },
  5949. multiplyQuaternions: function ( a, b ) {
  5950. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  5951. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  5952. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  5953. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  5954. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  5955. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  5956. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  5957. this.onChangeCallback();
  5958. return this;
  5959. },
  5960. slerp: function ( qb, t ) {
  5961. if ( t === 0 ) return this;
  5962. if ( t === 1 ) return this.copy( qb );
  5963. var x = this._x, y = this._y, z = this._z, w = this._w;
  5964. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  5965. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  5966. if ( cosHalfTheta < 0 ) {
  5967. this._w = - qb._w;
  5968. this._x = - qb._x;
  5969. this._y = - qb._y;
  5970. this._z = - qb._z;
  5971. cosHalfTheta = - cosHalfTheta;
  5972. } else {
  5973. this.copy( qb );
  5974. }
  5975. if ( cosHalfTheta >= 1.0 ) {
  5976. this._w = w;
  5977. this._x = x;
  5978. this._y = y;
  5979. this._z = z;
  5980. return this;
  5981. }
  5982. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  5983. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  5984. this._w = 0.5 * ( w + this._w );
  5985. this._x = 0.5 * ( x + this._x );
  5986. this._y = 0.5 * ( y + this._y );
  5987. this._z = 0.5 * ( z + this._z );
  5988. return this;
  5989. }
  5990. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  5991. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  5992. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  5993. this._w = ( w * ratioA + this._w * ratioB );
  5994. this._x = ( x * ratioA + this._x * ratioB );
  5995. this._y = ( y * ratioA + this._y * ratioB );
  5996. this._z = ( z * ratioA + this._z * ratioB );
  5997. this.onChangeCallback();
  5998. return this;
  5999. },
  6000. equals: function ( quaternion ) {
  6001. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  6002. },
  6003. fromArray: function ( array, offset ) {
  6004. if ( offset === undefined ) offset = 0;
  6005. this._x = array[ offset ];
  6006. this._y = array[ offset + 1 ];
  6007. this._z = array[ offset + 2 ];
  6008. this._w = array[ offset + 3 ];
  6009. this.onChangeCallback();
  6010. return this;
  6011. },
  6012. toArray: function ( array, offset ) {
  6013. if ( array === undefined ) array = [];
  6014. if ( offset === undefined ) offset = 0;
  6015. array[ offset ] = this._x;
  6016. array[ offset + 1 ] = this._y;
  6017. array[ offset + 2 ] = this._z;
  6018. array[ offset + 3 ] = this._w;
  6019. return array;
  6020. },
  6021. onChange: function ( callback ) {
  6022. this.onChangeCallback = callback;
  6023. return this;
  6024. },
  6025. onChangeCallback: function () {}
  6026. } );
  6027. /**
  6028. * @author mrdoob / http://mrdoob.com/
  6029. * @author kile / http://kile.stravaganza.org/
  6030. * @author philogb / http://blog.thejit.org/
  6031. * @author mikael emtinger / http://gomo.se/
  6032. * @author egraether / http://egraether.com/
  6033. * @author WestLangley / http://github.com/WestLangley
  6034. */
  6035. function Vector3( x, y, z ) {
  6036. this.x = x || 0;
  6037. this.y = y || 0;
  6038. this.z = z || 0;
  6039. }
  6040. Object.assign( Vector3.prototype, {
  6041. isVector3: true,
  6042. set: function ( x, y, z ) {
  6043. this.x = x;
  6044. this.y = y;
  6045. this.z = z;
  6046. return this;
  6047. },
  6048. setScalar: function ( scalar ) {
  6049. this.x = scalar;
  6050. this.y = scalar;
  6051. this.z = scalar;
  6052. return this;
  6053. },
  6054. setX: function ( x ) {
  6055. this.x = x;
  6056. return this;
  6057. },
  6058. setY: function ( y ) {
  6059. this.y = y;
  6060. return this;
  6061. },
  6062. setZ: function ( z ) {
  6063. this.z = z;
  6064. return this;
  6065. },
  6066. setComponent: function ( index, value ) {
  6067. switch ( index ) {
  6068. case 0: this.x = value; break;
  6069. case 1: this.y = value; break;
  6070. case 2: this.z = value; break;
  6071. default: throw new Error( 'index is out of range: ' + index );
  6072. }
  6073. return this;
  6074. },
  6075. getComponent: function ( index ) {
  6076. switch ( index ) {
  6077. case 0: return this.x;
  6078. case 1: return this.y;
  6079. case 2: return this.z;
  6080. default: throw new Error( 'index is out of range: ' + index );
  6081. }
  6082. },
  6083. clone: function () {
  6084. return new this.constructor( this.x, this.y, this.z );
  6085. },
  6086. copy: function ( v ) {
  6087. this.x = v.x;
  6088. this.y = v.y;
  6089. this.z = v.z;
  6090. return this;
  6091. },
  6092. add: function ( v, w ) {
  6093. if ( w !== undefined ) {
  6094. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6095. return this.addVectors( v, w );
  6096. }
  6097. this.x += v.x;
  6098. this.y += v.y;
  6099. this.z += v.z;
  6100. return this;
  6101. },
  6102. addScalar: function ( s ) {
  6103. this.x += s;
  6104. this.y += s;
  6105. this.z += s;
  6106. return this;
  6107. },
  6108. addVectors: function ( a, b ) {
  6109. this.x = a.x + b.x;
  6110. this.y = a.y + b.y;
  6111. this.z = a.z + b.z;
  6112. return this;
  6113. },
  6114. addScaledVector: function ( v, s ) {
  6115. this.x += v.x * s;
  6116. this.y += v.y * s;
  6117. this.z += v.z * s;
  6118. return this;
  6119. },
  6120. sub: function ( v, w ) {
  6121. if ( w !== undefined ) {
  6122. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6123. return this.subVectors( v, w );
  6124. }
  6125. this.x -= v.x;
  6126. this.y -= v.y;
  6127. this.z -= v.z;
  6128. return this;
  6129. },
  6130. subScalar: function ( s ) {
  6131. this.x -= s;
  6132. this.y -= s;
  6133. this.z -= s;
  6134. return this;
  6135. },
  6136. subVectors: function ( a, b ) {
  6137. this.x = a.x - b.x;
  6138. this.y = a.y - b.y;
  6139. this.z = a.z - b.z;
  6140. return this;
  6141. },
  6142. multiply: function ( v, w ) {
  6143. if ( w !== undefined ) {
  6144. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  6145. return this.multiplyVectors( v, w );
  6146. }
  6147. this.x *= v.x;
  6148. this.y *= v.y;
  6149. this.z *= v.z;
  6150. return this;
  6151. },
  6152. multiplyScalar: function ( scalar ) {
  6153. this.x *= scalar;
  6154. this.y *= scalar;
  6155. this.z *= scalar;
  6156. return this;
  6157. },
  6158. multiplyVectors: function ( a, b ) {
  6159. this.x = a.x * b.x;
  6160. this.y = a.y * b.y;
  6161. this.z = a.z * b.z;
  6162. return this;
  6163. },
  6164. applyEuler: function () {
  6165. var quaternion = new Quaternion();
  6166. return function applyEuler( euler ) {
  6167. if ( ! ( euler && euler.isEuler ) ) {
  6168. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  6169. }
  6170. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  6171. };
  6172. }(),
  6173. applyAxisAngle: function () {
  6174. var quaternion = new Quaternion();
  6175. return function applyAxisAngle( axis, angle ) {
  6176. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  6177. };
  6178. }(),
  6179. applyMatrix3: function ( m ) {
  6180. var x = this.x, y = this.y, z = this.z;
  6181. var e = m.elements;
  6182. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  6183. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  6184. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  6185. return this;
  6186. },
  6187. applyMatrix4: function ( m ) {
  6188. var x = this.x, y = this.y, z = this.z;
  6189. var e = m.elements;
  6190. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  6191. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  6192. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  6193. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  6194. return this;
  6195. },
  6196. applyQuaternion: function ( q ) {
  6197. var x = this.x, y = this.y, z = this.z;
  6198. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  6199. // calculate quat * vector
  6200. var ix = qw * x + qy * z - qz * y;
  6201. var iy = qw * y + qz * x - qx * z;
  6202. var iz = qw * z + qx * y - qy * x;
  6203. var iw = - qx * x - qy * y - qz * z;
  6204. // calculate result * inverse quat
  6205. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  6206. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  6207. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  6208. return this;
  6209. },
  6210. project: function () {
  6211. var matrix = new Matrix4();
  6212. return function project( camera ) {
  6213. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  6214. return this.applyMatrix4( matrix );
  6215. };
  6216. }(),
  6217. unproject: function () {
  6218. var matrix = new Matrix4();
  6219. return function unproject( camera ) {
  6220. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  6221. return this.applyMatrix4( matrix );
  6222. };
  6223. }(),
  6224. transformDirection: function ( m ) {
  6225. // input: THREE.Matrix4 affine matrix
  6226. // vector interpreted as a direction
  6227. var x = this.x, y = this.y, z = this.z;
  6228. var e = m.elements;
  6229. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  6230. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  6231. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  6232. return this.normalize();
  6233. },
  6234. divide: function ( v ) {
  6235. this.x /= v.x;
  6236. this.y /= v.y;
  6237. this.z /= v.z;
  6238. return this;
  6239. },
  6240. divideScalar: function ( scalar ) {
  6241. return this.multiplyScalar( 1 / scalar );
  6242. },
  6243. min: function ( v ) {
  6244. this.x = Math.min( this.x, v.x );
  6245. this.y = Math.min( this.y, v.y );
  6246. this.z = Math.min( this.z, v.z );
  6247. return this;
  6248. },
  6249. max: function ( v ) {
  6250. this.x = Math.max( this.x, v.x );
  6251. this.y = Math.max( this.y, v.y );
  6252. this.z = Math.max( this.z, v.z );
  6253. return this;
  6254. },
  6255. clamp: function ( min, max ) {
  6256. // assumes min < max, componentwise
  6257. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6258. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6259. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6260. return this;
  6261. },
  6262. clampScalar: function () {
  6263. var min = new Vector3();
  6264. var max = new Vector3();
  6265. return function clampScalar( minVal, maxVal ) {
  6266. min.set( minVal, minVal, minVal );
  6267. max.set( maxVal, maxVal, maxVal );
  6268. return this.clamp( min, max );
  6269. };
  6270. }(),
  6271. clampLength: function ( min, max ) {
  6272. var length = this.length();
  6273. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6274. },
  6275. floor: function () {
  6276. this.x = Math.floor( this.x );
  6277. this.y = Math.floor( this.y );
  6278. this.z = Math.floor( this.z );
  6279. return this;
  6280. },
  6281. ceil: function () {
  6282. this.x = Math.ceil( this.x );
  6283. this.y = Math.ceil( this.y );
  6284. this.z = Math.ceil( this.z );
  6285. return this;
  6286. },
  6287. round: function () {
  6288. this.x = Math.round( this.x );
  6289. this.y = Math.round( this.y );
  6290. this.z = Math.round( this.z );
  6291. return this;
  6292. },
  6293. roundToZero: function () {
  6294. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6295. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6296. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  6297. return this;
  6298. },
  6299. negate: function () {
  6300. this.x = - this.x;
  6301. this.y = - this.y;
  6302. this.z = - this.z;
  6303. return this;
  6304. },
  6305. dot: function ( v ) {
  6306. return this.x * v.x + this.y * v.y + this.z * v.z;
  6307. },
  6308. // TODO lengthSquared?
  6309. lengthSq: function () {
  6310. return this.x * this.x + this.y * this.y + this.z * this.z;
  6311. },
  6312. length: function () {
  6313. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  6314. },
  6315. manhattanLength: function () {
  6316. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  6317. },
  6318. normalize: function () {
  6319. return this.divideScalar( this.length() || 1 );
  6320. },
  6321. setLength: function ( length ) {
  6322. return this.normalize().multiplyScalar( length );
  6323. },
  6324. lerp: function ( v, alpha ) {
  6325. this.x += ( v.x - this.x ) * alpha;
  6326. this.y += ( v.y - this.y ) * alpha;
  6327. this.z += ( v.z - this.z ) * alpha;
  6328. return this;
  6329. },
  6330. lerpVectors: function ( v1, v2, alpha ) {
  6331. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6332. },
  6333. cross: function ( v, w ) {
  6334. if ( w !== undefined ) {
  6335. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  6336. return this.crossVectors( v, w );
  6337. }
  6338. return this.crossVectors( this, v );
  6339. },
  6340. crossVectors: function ( a, b ) {
  6341. var ax = a.x, ay = a.y, az = a.z;
  6342. var bx = b.x, by = b.y, bz = b.z;
  6343. this.x = ay * bz - az * by;
  6344. this.y = az * bx - ax * bz;
  6345. this.z = ax * by - ay * bx;
  6346. return this;
  6347. },
  6348. projectOnVector: function ( vector ) {
  6349. var scalar = vector.dot( this ) / vector.lengthSq();
  6350. return this.copy( vector ).multiplyScalar( scalar );
  6351. },
  6352. projectOnPlane: function () {
  6353. var v1 = new Vector3();
  6354. return function projectOnPlane( planeNormal ) {
  6355. v1.copy( this ).projectOnVector( planeNormal );
  6356. return this.sub( v1 );
  6357. };
  6358. }(),
  6359. reflect: function () {
  6360. // reflect incident vector off plane orthogonal to normal
  6361. // normal is assumed to have unit length
  6362. var v1 = new Vector3();
  6363. return function reflect( normal ) {
  6364. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  6365. };
  6366. }(),
  6367. angleTo: function ( v ) {
  6368. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  6369. // clamp, to handle numerical problems
  6370. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  6371. },
  6372. distanceTo: function ( v ) {
  6373. return Math.sqrt( this.distanceToSquared( v ) );
  6374. },
  6375. distanceToSquared: function ( v ) {
  6376. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  6377. return dx * dx + dy * dy + dz * dz;
  6378. },
  6379. manhattanDistanceTo: function ( v ) {
  6380. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  6381. },
  6382. setFromSpherical: function ( s ) {
  6383. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  6384. this.x = sinPhiRadius * Math.sin( s.theta );
  6385. this.y = Math.cos( s.phi ) * s.radius;
  6386. this.z = sinPhiRadius * Math.cos( s.theta );
  6387. return this;
  6388. },
  6389. setFromCylindrical: function ( c ) {
  6390. this.x = c.radius * Math.sin( c.theta );
  6391. this.y = c.y;
  6392. this.z = c.radius * Math.cos( c.theta );
  6393. return this;
  6394. },
  6395. setFromMatrixPosition: function ( m ) {
  6396. var e = m.elements;
  6397. this.x = e[ 12 ];
  6398. this.y = e[ 13 ];
  6399. this.z = e[ 14 ];
  6400. return this;
  6401. },
  6402. setFromMatrixScale: function ( m ) {
  6403. var sx = this.setFromMatrixColumn( m, 0 ).length();
  6404. var sy = this.setFromMatrixColumn( m, 1 ).length();
  6405. var sz = this.setFromMatrixColumn( m, 2 ).length();
  6406. this.x = sx;
  6407. this.y = sy;
  6408. this.z = sz;
  6409. return this;
  6410. },
  6411. setFromMatrixColumn: function ( m, index ) {
  6412. return this.fromArray( m.elements, index * 4 );
  6413. },
  6414. equals: function ( v ) {
  6415. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  6416. },
  6417. fromArray: function ( array, offset ) {
  6418. if ( offset === undefined ) offset = 0;
  6419. this.x = array[ offset ];
  6420. this.y = array[ offset + 1 ];
  6421. this.z = array[ offset + 2 ];
  6422. return this;
  6423. },
  6424. toArray: function ( array, offset ) {
  6425. if ( array === undefined ) array = [];
  6426. if ( offset === undefined ) offset = 0;
  6427. array[ offset ] = this.x;
  6428. array[ offset + 1 ] = this.y;
  6429. array[ offset + 2 ] = this.z;
  6430. return array;
  6431. },
  6432. fromBufferAttribute: function ( attribute, index, offset ) {
  6433. if ( offset !== undefined ) {
  6434. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  6435. }
  6436. this.x = attribute.getX( index );
  6437. this.y = attribute.getY( index );
  6438. this.z = attribute.getZ( index );
  6439. return this;
  6440. }
  6441. } );
  6442. /**
  6443. * @author alteredq / http://alteredqualia.com/
  6444. * @author WestLangley / http://github.com/WestLangley
  6445. * @author bhouston / http://clara.io
  6446. * @author tschw
  6447. */
  6448. function Matrix3() {
  6449. this.elements = [
  6450. 1, 0, 0,
  6451. 0, 1, 0,
  6452. 0, 0, 1
  6453. ];
  6454. if ( arguments.length > 0 ) {
  6455. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  6456. }
  6457. }
  6458. Object.assign( Matrix3.prototype, {
  6459. isMatrix3: true,
  6460. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  6461. var te = this.elements;
  6462. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  6463. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  6464. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  6465. return this;
  6466. },
  6467. identity: function () {
  6468. this.set(
  6469. 1, 0, 0,
  6470. 0, 1, 0,
  6471. 0, 0, 1
  6472. );
  6473. return this;
  6474. },
  6475. clone: function () {
  6476. return new this.constructor().fromArray( this.elements );
  6477. },
  6478. copy: function ( m ) {
  6479. var te = this.elements;
  6480. var me = m.elements;
  6481. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  6482. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  6483. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  6484. return this;
  6485. },
  6486. setFromMatrix4: function ( m ) {
  6487. var me = m.elements;
  6488. this.set(
  6489. me[ 0 ], me[ 4 ], me[ 8 ],
  6490. me[ 1 ], me[ 5 ], me[ 9 ],
  6491. me[ 2 ], me[ 6 ], me[ 10 ]
  6492. );
  6493. return this;
  6494. },
  6495. applyToBufferAttribute: function () {
  6496. var v1 = new Vector3();
  6497. return function applyToBufferAttribute( attribute ) {
  6498. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  6499. v1.x = attribute.getX( i );
  6500. v1.y = attribute.getY( i );
  6501. v1.z = attribute.getZ( i );
  6502. v1.applyMatrix3( this );
  6503. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  6504. }
  6505. return attribute;
  6506. };
  6507. }(),
  6508. multiply: function ( m ) {
  6509. return this.multiplyMatrices( this, m );
  6510. },
  6511. premultiply: function ( m ) {
  6512. return this.multiplyMatrices( m, this );
  6513. },
  6514. multiplyMatrices: function ( a, b ) {
  6515. var ae = a.elements;
  6516. var be = b.elements;
  6517. var te = this.elements;
  6518. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  6519. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  6520. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  6521. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  6522. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  6523. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  6524. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  6525. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  6526. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  6527. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  6528. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  6529. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  6530. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  6531. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  6532. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  6533. return this;
  6534. },
  6535. multiplyScalar: function ( s ) {
  6536. var te = this.elements;
  6537. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  6538. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  6539. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  6540. return this;
  6541. },
  6542. determinant: function () {
  6543. var te = this.elements;
  6544. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  6545. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  6546. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  6547. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  6548. },
  6549. getInverse: function ( matrix, throwOnDegenerate ) {
  6550. if ( matrix && matrix.isMatrix4 ) {
  6551. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  6552. }
  6553. var me = matrix.elements,
  6554. te = this.elements,
  6555. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  6556. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  6557. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  6558. t11 = n33 * n22 - n32 * n23,
  6559. t12 = n32 * n13 - n33 * n12,
  6560. t13 = n23 * n12 - n22 * n13,
  6561. det = n11 * t11 + n21 * t12 + n31 * t13;
  6562. if ( det === 0 ) {
  6563. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  6564. if ( throwOnDegenerate === true ) {
  6565. throw new Error( msg );
  6566. } else {
  6567. console.warn( msg );
  6568. }
  6569. return this.identity();
  6570. }
  6571. var detInv = 1 / det;
  6572. te[ 0 ] = t11 * detInv;
  6573. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  6574. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  6575. te[ 3 ] = t12 * detInv;
  6576. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  6577. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  6578. te[ 6 ] = t13 * detInv;
  6579. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  6580. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  6581. return this;
  6582. },
  6583. transpose: function () {
  6584. var tmp, m = this.elements;
  6585. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  6586. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  6587. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  6588. return this;
  6589. },
  6590. getNormalMatrix: function ( matrix4 ) {
  6591. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  6592. },
  6593. transposeIntoArray: function ( r ) {
  6594. var m = this.elements;
  6595. r[ 0 ] = m[ 0 ];
  6596. r[ 1 ] = m[ 3 ];
  6597. r[ 2 ] = m[ 6 ];
  6598. r[ 3 ] = m[ 1 ];
  6599. r[ 4 ] = m[ 4 ];
  6600. r[ 5 ] = m[ 7 ];
  6601. r[ 6 ] = m[ 2 ];
  6602. r[ 7 ] = m[ 5 ];
  6603. r[ 8 ] = m[ 8 ];
  6604. return this;
  6605. },
  6606. setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {
  6607. var c = Math.cos( rotation );
  6608. var s = Math.sin( rotation );
  6609. this.set(
  6610. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  6611. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  6612. 0, 0, 1
  6613. );
  6614. },
  6615. scale: function ( sx, sy ) {
  6616. var te = this.elements;
  6617. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  6618. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  6619. return this;
  6620. },
  6621. rotate: function ( theta ) {
  6622. var c = Math.cos( theta );
  6623. var s = Math.sin( theta );
  6624. var te = this.elements;
  6625. var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  6626. var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  6627. te[ 0 ] = c * a11 + s * a21;
  6628. te[ 3 ] = c * a12 + s * a22;
  6629. te[ 6 ] = c * a13 + s * a23;
  6630. te[ 1 ] = - s * a11 + c * a21;
  6631. te[ 4 ] = - s * a12 + c * a22;
  6632. te[ 7 ] = - s * a13 + c * a23;
  6633. return this;
  6634. },
  6635. translate: function ( tx, ty ) {
  6636. var te = this.elements;
  6637. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  6638. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  6639. return this;
  6640. },
  6641. equals: function ( matrix ) {
  6642. var te = this.elements;
  6643. var me = matrix.elements;
  6644. for ( var i = 0; i < 9; i ++ ) {
  6645. if ( te[ i ] !== me[ i ] ) return false;
  6646. }
  6647. return true;
  6648. },
  6649. fromArray: function ( array, offset ) {
  6650. if ( offset === undefined ) offset = 0;
  6651. for ( var i = 0; i < 9; i ++ ) {
  6652. this.elements[ i ] = array[ i + offset ];
  6653. }
  6654. return this;
  6655. },
  6656. toArray: function ( array, offset ) {
  6657. if ( array === undefined ) array = [];
  6658. if ( offset === undefined ) offset = 0;
  6659. var te = this.elements;
  6660. array[ offset ] = te[ 0 ];
  6661. array[ offset + 1 ] = te[ 1 ];
  6662. array[ offset + 2 ] = te[ 2 ];
  6663. array[ offset + 3 ] = te[ 3 ];
  6664. array[ offset + 4 ] = te[ 4 ];
  6665. array[ offset + 5 ] = te[ 5 ];
  6666. array[ offset + 6 ] = te[ 6 ];
  6667. array[ offset + 7 ] = te[ 7 ];
  6668. array[ offset + 8 ] = te[ 8 ];
  6669. return array;
  6670. }
  6671. } );
  6672. /**
  6673. * @author mrdoob / http://mrdoob.com/
  6674. * @author alteredq / http://alteredqualia.com/
  6675. * @author szimek / https://github.com/szimek/
  6676. */
  6677. var textureId = 0;
  6678. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  6679. Object.defineProperty( this, 'id', { value: textureId ++ } );
  6680. this.uuid = _Math.generateUUID();
  6681. this.name = '';
  6682. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  6683. this.mipmaps = [];
  6684. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  6685. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  6686. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  6687. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  6688. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  6689. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6690. this.format = format !== undefined ? format : RGBAFormat;
  6691. this.type = type !== undefined ? type : UnsignedByteType;
  6692. this.offset = new Vector2( 0, 0 );
  6693. this.repeat = new Vector2( 1, 1 );
  6694. this.center = new Vector2( 0, 0 );
  6695. this.rotation = 0;
  6696. this.matrixAutoUpdate = true;
  6697. this.matrix = new Matrix3();
  6698. this.generateMipmaps = true;
  6699. this.premultiplyAlpha = false;
  6700. this.flipY = true;
  6701. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  6702. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  6703. //
  6704. // Also changing the encoding after already used by a Material will not automatically make the Material
  6705. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  6706. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  6707. this.version = 0;
  6708. this.onUpdate = null;
  6709. }
  6710. Texture.DEFAULT_IMAGE = undefined;
  6711. Texture.DEFAULT_MAPPING = UVMapping;
  6712. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6713. constructor: Texture,
  6714. isTexture: true,
  6715. updateMatrix: function () {
  6716. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  6717. },
  6718. clone: function () {
  6719. return new this.constructor().copy( this );
  6720. },
  6721. copy: function ( source ) {
  6722. this.name = source.name;
  6723. this.image = source.image;
  6724. this.mipmaps = source.mipmaps.slice( 0 );
  6725. this.mapping = source.mapping;
  6726. this.wrapS = source.wrapS;
  6727. this.wrapT = source.wrapT;
  6728. this.magFilter = source.magFilter;
  6729. this.minFilter = source.minFilter;
  6730. this.anisotropy = source.anisotropy;
  6731. this.format = source.format;
  6732. this.type = source.type;
  6733. this.offset.copy( source.offset );
  6734. this.repeat.copy( source.repeat );
  6735. this.center.copy( source.center );
  6736. this.rotation = source.rotation;
  6737. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6738. this.matrix.copy( source.matrix );
  6739. this.generateMipmaps = source.generateMipmaps;
  6740. this.premultiplyAlpha = source.premultiplyAlpha;
  6741. this.flipY = source.flipY;
  6742. this.unpackAlignment = source.unpackAlignment;
  6743. this.encoding = source.encoding;
  6744. return this;
  6745. },
  6746. toJSON: function ( meta ) {
  6747. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  6748. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6749. return meta.textures[ this.uuid ];
  6750. }
  6751. function getDataURL( image ) {
  6752. var canvas;
  6753. if ( image instanceof HTMLCanvasElement ) {
  6754. canvas = image;
  6755. } else {
  6756. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  6757. canvas.width = image.width;
  6758. canvas.height = image.height;
  6759. var context = canvas.getContext( '2d' );
  6760. if ( image instanceof ImageData ) {
  6761. context.putImageData( image, 0, 0 );
  6762. } else {
  6763. context.drawImage( image, 0, 0, image.width, image.height );
  6764. }
  6765. }
  6766. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  6767. return canvas.toDataURL( 'image/jpeg', 0.6 );
  6768. } else {
  6769. return canvas.toDataURL( 'image/png' );
  6770. }
  6771. }
  6772. var output = {
  6773. metadata: {
  6774. version: 4.5,
  6775. type: 'Texture',
  6776. generator: 'Texture.toJSON'
  6777. },
  6778. uuid: this.uuid,
  6779. name: this.name,
  6780. mapping: this.mapping,
  6781. repeat: [ this.repeat.x, this.repeat.y ],
  6782. offset: [ this.offset.x, this.offset.y ],
  6783. center: [ this.center.x, this.center.y ],
  6784. rotation: this.rotation,
  6785. wrap: [ this.wrapS, this.wrapT ],
  6786. format: this.format,
  6787. minFilter: this.minFilter,
  6788. magFilter: this.magFilter,
  6789. anisotropy: this.anisotropy,
  6790. flipY: this.flipY
  6791. };
  6792. if ( this.image !== undefined ) {
  6793. // TODO: Move to THREE.Image
  6794. var image = this.image;
  6795. if ( image.uuid === undefined ) {
  6796. image.uuid = _Math.generateUUID(); // UGH
  6797. }
  6798. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  6799. meta.images[ image.uuid ] = {
  6800. uuid: image.uuid,
  6801. url: getDataURL( image )
  6802. };
  6803. }
  6804. output.image = image.uuid;
  6805. }
  6806. if ( ! isRootObject ) {
  6807. meta.textures[ this.uuid ] = output;
  6808. }
  6809. return output;
  6810. },
  6811. dispose: function () {
  6812. this.dispatchEvent( { type: 'dispose' } );
  6813. },
  6814. transformUv: function ( uv ) {
  6815. if ( this.mapping !== UVMapping ) return;
  6816. uv.applyMatrix3( this.matrix );
  6817. if ( uv.x < 0 || uv.x > 1 ) {
  6818. switch ( this.wrapS ) {
  6819. case RepeatWrapping:
  6820. uv.x = uv.x - Math.floor( uv.x );
  6821. break;
  6822. case ClampToEdgeWrapping:
  6823. uv.x = uv.x < 0 ? 0 : 1;
  6824. break;
  6825. case MirroredRepeatWrapping:
  6826. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6827. uv.x = Math.ceil( uv.x ) - uv.x;
  6828. } else {
  6829. uv.x = uv.x - Math.floor( uv.x );
  6830. }
  6831. break;
  6832. }
  6833. }
  6834. if ( uv.y < 0 || uv.y > 1 ) {
  6835. switch ( this.wrapT ) {
  6836. case RepeatWrapping:
  6837. uv.y = uv.y - Math.floor( uv.y );
  6838. break;
  6839. case ClampToEdgeWrapping:
  6840. uv.y = uv.y < 0 ? 0 : 1;
  6841. break;
  6842. case MirroredRepeatWrapping:
  6843. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6844. uv.y = Math.ceil( uv.y ) - uv.y;
  6845. } else {
  6846. uv.y = uv.y - Math.floor( uv.y );
  6847. }
  6848. break;
  6849. }
  6850. }
  6851. if ( this.flipY ) {
  6852. uv.y = 1 - uv.y;
  6853. }
  6854. }
  6855. } );
  6856. Object.defineProperty( Texture.prototype, "needsUpdate", {
  6857. set: function ( value ) {
  6858. if ( value === true ) this.version ++;
  6859. }
  6860. } );
  6861. /**
  6862. * @author supereggbert / http://www.paulbrunt.co.uk/
  6863. * @author philogb / http://blog.thejit.org/
  6864. * @author mikael emtinger / http://gomo.se/
  6865. * @author egraether / http://egraether.com/
  6866. * @author WestLangley / http://github.com/WestLangley
  6867. */
  6868. function Vector4( x, y, z, w ) {
  6869. this.x = x || 0;
  6870. this.y = y || 0;
  6871. this.z = z || 0;
  6872. this.w = ( w !== undefined ) ? w : 1;
  6873. }
  6874. Object.assign( Vector4.prototype, {
  6875. isVector4: true,
  6876. set: function ( x, y, z, w ) {
  6877. this.x = x;
  6878. this.y = y;
  6879. this.z = z;
  6880. this.w = w;
  6881. return this;
  6882. },
  6883. setScalar: function ( scalar ) {
  6884. this.x = scalar;
  6885. this.y = scalar;
  6886. this.z = scalar;
  6887. this.w = scalar;
  6888. return this;
  6889. },
  6890. setX: function ( x ) {
  6891. this.x = x;
  6892. return this;
  6893. },
  6894. setY: function ( y ) {
  6895. this.y = y;
  6896. return this;
  6897. },
  6898. setZ: function ( z ) {
  6899. this.z = z;
  6900. return this;
  6901. },
  6902. setW: function ( w ) {
  6903. this.w = w;
  6904. return this;
  6905. },
  6906. setComponent: function ( index, value ) {
  6907. switch ( index ) {
  6908. case 0: this.x = value; break;
  6909. case 1: this.y = value; break;
  6910. case 2: this.z = value; break;
  6911. case 3: this.w = value; break;
  6912. default: throw new Error( 'index is out of range: ' + index );
  6913. }
  6914. return this;
  6915. },
  6916. getComponent: function ( index ) {
  6917. switch ( index ) {
  6918. case 0: return this.x;
  6919. case 1: return this.y;
  6920. case 2: return this.z;
  6921. case 3: return this.w;
  6922. default: throw new Error( 'index is out of range: ' + index );
  6923. }
  6924. },
  6925. clone: function () {
  6926. return new this.constructor( this.x, this.y, this.z, this.w );
  6927. },
  6928. copy: function ( v ) {
  6929. this.x = v.x;
  6930. this.y = v.y;
  6931. this.z = v.z;
  6932. this.w = ( v.w !== undefined ) ? v.w : 1;
  6933. return this;
  6934. },
  6935. add: function ( v, w ) {
  6936. if ( w !== undefined ) {
  6937. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6938. return this.addVectors( v, w );
  6939. }
  6940. this.x += v.x;
  6941. this.y += v.y;
  6942. this.z += v.z;
  6943. this.w += v.w;
  6944. return this;
  6945. },
  6946. addScalar: function ( s ) {
  6947. this.x += s;
  6948. this.y += s;
  6949. this.z += s;
  6950. this.w += s;
  6951. return this;
  6952. },
  6953. addVectors: function ( a, b ) {
  6954. this.x = a.x + b.x;
  6955. this.y = a.y + b.y;
  6956. this.z = a.z + b.z;
  6957. this.w = a.w + b.w;
  6958. return this;
  6959. },
  6960. addScaledVector: function ( v, s ) {
  6961. this.x += v.x * s;
  6962. this.y += v.y * s;
  6963. this.z += v.z * s;
  6964. this.w += v.w * s;
  6965. return this;
  6966. },
  6967. sub: function ( v, w ) {
  6968. if ( w !== undefined ) {
  6969. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6970. return this.subVectors( v, w );
  6971. }
  6972. this.x -= v.x;
  6973. this.y -= v.y;
  6974. this.z -= v.z;
  6975. this.w -= v.w;
  6976. return this;
  6977. },
  6978. subScalar: function ( s ) {
  6979. this.x -= s;
  6980. this.y -= s;
  6981. this.z -= s;
  6982. this.w -= s;
  6983. return this;
  6984. },
  6985. subVectors: function ( a, b ) {
  6986. this.x = a.x - b.x;
  6987. this.y = a.y - b.y;
  6988. this.z = a.z - b.z;
  6989. this.w = a.w - b.w;
  6990. return this;
  6991. },
  6992. multiplyScalar: function ( scalar ) {
  6993. this.x *= scalar;
  6994. this.y *= scalar;
  6995. this.z *= scalar;
  6996. this.w *= scalar;
  6997. return this;
  6998. },
  6999. applyMatrix4: function ( m ) {
  7000. var x = this.x, y = this.y, z = this.z, w = this.w;
  7001. var e = m.elements;
  7002. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  7003. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  7004. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  7005. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  7006. return this;
  7007. },
  7008. divideScalar: function ( scalar ) {
  7009. return this.multiplyScalar( 1 / scalar );
  7010. },
  7011. setAxisAngleFromQuaternion: function ( q ) {
  7012. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  7013. // q is assumed to be normalized
  7014. this.w = 2 * Math.acos( q.w );
  7015. var s = Math.sqrt( 1 - q.w * q.w );
  7016. if ( s < 0.0001 ) {
  7017. this.x = 1;
  7018. this.y = 0;
  7019. this.z = 0;
  7020. } else {
  7021. this.x = q.x / s;
  7022. this.y = q.y / s;
  7023. this.z = q.z / s;
  7024. }
  7025. return this;
  7026. },
  7027. setAxisAngleFromRotationMatrix: function ( m ) {
  7028. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  7029. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7030. var angle, x, y, z, // variables for result
  7031. epsilon = 0.01, // margin to allow for rounding errors
  7032. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  7033. te = m.elements,
  7034. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  7035. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  7036. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  7037. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  7038. ( Math.abs( m13 - m31 ) < epsilon ) &&
  7039. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  7040. // singularity found
  7041. // first check for identity matrix which must have +1 for all terms
  7042. // in leading diagonal and zero in other terms
  7043. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  7044. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  7045. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  7046. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  7047. // this singularity is identity matrix so angle = 0
  7048. this.set( 1, 0, 0, 0 );
  7049. return this; // zero angle, arbitrary axis
  7050. }
  7051. // otherwise this singularity is angle = 180
  7052. angle = Math.PI;
  7053. var xx = ( m11 + 1 ) / 2;
  7054. var yy = ( m22 + 1 ) / 2;
  7055. var zz = ( m33 + 1 ) / 2;
  7056. var xy = ( m12 + m21 ) / 4;
  7057. var xz = ( m13 + m31 ) / 4;
  7058. var yz = ( m23 + m32 ) / 4;
  7059. if ( ( xx > yy ) && ( xx > zz ) ) {
  7060. // m11 is the largest diagonal term
  7061. if ( xx < epsilon ) {
  7062. x = 0;
  7063. y = 0.707106781;
  7064. z = 0.707106781;
  7065. } else {
  7066. x = Math.sqrt( xx );
  7067. y = xy / x;
  7068. z = xz / x;
  7069. }
  7070. } else if ( yy > zz ) {
  7071. // m22 is the largest diagonal term
  7072. if ( yy < epsilon ) {
  7073. x = 0.707106781;
  7074. y = 0;
  7075. z = 0.707106781;
  7076. } else {
  7077. y = Math.sqrt( yy );
  7078. x = xy / y;
  7079. z = yz / y;
  7080. }
  7081. } else {
  7082. // m33 is the largest diagonal term so base result on this
  7083. if ( zz < epsilon ) {
  7084. x = 0.707106781;
  7085. y = 0.707106781;
  7086. z = 0;
  7087. } else {
  7088. z = Math.sqrt( zz );
  7089. x = xz / z;
  7090. y = yz / z;
  7091. }
  7092. }
  7093. this.set( x, y, z, angle );
  7094. return this; // return 180 deg rotation
  7095. }
  7096. // as we have reached here there are no singularities so we can handle normally
  7097. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  7098. ( m13 - m31 ) * ( m13 - m31 ) +
  7099. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  7100. if ( Math.abs( s ) < 0.001 ) s = 1;
  7101. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  7102. // caught by singularity test above, but I've left it in just in case
  7103. this.x = ( m32 - m23 ) / s;
  7104. this.y = ( m13 - m31 ) / s;
  7105. this.z = ( m21 - m12 ) / s;
  7106. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  7107. return this;
  7108. },
  7109. min: function ( v ) {
  7110. this.x = Math.min( this.x, v.x );
  7111. this.y = Math.min( this.y, v.y );
  7112. this.z = Math.min( this.z, v.z );
  7113. this.w = Math.min( this.w, v.w );
  7114. return this;
  7115. },
  7116. max: function ( v ) {
  7117. this.x = Math.max( this.x, v.x );
  7118. this.y = Math.max( this.y, v.y );
  7119. this.z = Math.max( this.z, v.z );
  7120. this.w = Math.max( this.w, v.w );
  7121. return this;
  7122. },
  7123. clamp: function ( min, max ) {
  7124. // assumes min < max, componentwise
  7125. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  7126. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  7127. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  7128. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  7129. return this;
  7130. },
  7131. clampScalar: function () {
  7132. var min, max;
  7133. return function clampScalar( minVal, maxVal ) {
  7134. if ( min === undefined ) {
  7135. min = new Vector4();
  7136. max = new Vector4();
  7137. }
  7138. min.set( minVal, minVal, minVal, minVal );
  7139. max.set( maxVal, maxVal, maxVal, maxVal );
  7140. return this.clamp( min, max );
  7141. };
  7142. }(),
  7143. clampLength: function ( min, max ) {
  7144. var length = this.length();
  7145. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  7146. },
  7147. floor: function () {
  7148. this.x = Math.floor( this.x );
  7149. this.y = Math.floor( this.y );
  7150. this.z = Math.floor( this.z );
  7151. this.w = Math.floor( this.w );
  7152. return this;
  7153. },
  7154. ceil: function () {
  7155. this.x = Math.ceil( this.x );
  7156. this.y = Math.ceil( this.y );
  7157. this.z = Math.ceil( this.z );
  7158. this.w = Math.ceil( this.w );
  7159. return this;
  7160. },
  7161. round: function () {
  7162. this.x = Math.round( this.x );
  7163. this.y = Math.round( this.y );
  7164. this.z = Math.round( this.z );
  7165. this.w = Math.round( this.w );
  7166. return this;
  7167. },
  7168. roundToZero: function () {
  7169. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  7170. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  7171. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  7172. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  7173. return this;
  7174. },
  7175. negate: function () {
  7176. this.x = - this.x;
  7177. this.y = - this.y;
  7178. this.z = - this.z;
  7179. this.w = - this.w;
  7180. return this;
  7181. },
  7182. dot: function ( v ) {
  7183. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  7184. },
  7185. lengthSq: function () {
  7186. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  7187. },
  7188. length: function () {
  7189. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  7190. },
  7191. manhattanLength: function () {
  7192. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  7193. },
  7194. normalize: function () {
  7195. return this.divideScalar( this.length() || 1 );
  7196. },
  7197. setLength: function ( length ) {
  7198. return this.normalize().multiplyScalar( length );
  7199. },
  7200. lerp: function ( v, alpha ) {
  7201. this.x += ( v.x - this.x ) * alpha;
  7202. this.y += ( v.y - this.y ) * alpha;
  7203. this.z += ( v.z - this.z ) * alpha;
  7204. this.w += ( v.w - this.w ) * alpha;
  7205. return this;
  7206. },
  7207. lerpVectors: function ( v1, v2, alpha ) {
  7208. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  7209. },
  7210. equals: function ( v ) {
  7211. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  7212. },
  7213. fromArray: function ( array, offset ) {
  7214. if ( offset === undefined ) offset = 0;
  7215. this.x = array[ offset ];
  7216. this.y = array[ offset + 1 ];
  7217. this.z = array[ offset + 2 ];
  7218. this.w = array[ offset + 3 ];
  7219. return this;
  7220. },
  7221. toArray: function ( array, offset ) {
  7222. if ( array === undefined ) array = [];
  7223. if ( offset === undefined ) offset = 0;
  7224. array[ offset ] = this.x;
  7225. array[ offset + 1 ] = this.y;
  7226. array[ offset + 2 ] = this.z;
  7227. array[ offset + 3 ] = this.w;
  7228. return array;
  7229. },
  7230. fromBufferAttribute: function ( attribute, index, offset ) {
  7231. if ( offset !== undefined ) {
  7232. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  7233. }
  7234. this.x = attribute.getX( index );
  7235. this.y = attribute.getY( index );
  7236. this.z = attribute.getZ( index );
  7237. this.w = attribute.getW( index );
  7238. return this;
  7239. }
  7240. } );
  7241. /**
  7242. * @author szimek / https://github.com/szimek/
  7243. * @author alteredq / http://alteredqualia.com/
  7244. * @author Marius Kintel / https://github.com/kintel
  7245. */
  7246. /*
  7247. In options, we can specify:
  7248. * Texture parameters for an auto-generated target texture
  7249. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  7250. */
  7251. function WebGLRenderTarget( width, height, options ) {
  7252. this.width = width;
  7253. this.height = height;
  7254. this.scissor = new Vector4( 0, 0, width, height );
  7255. this.scissorTest = false;
  7256. this.viewport = new Vector4( 0, 0, width, height );
  7257. options = options || {};
  7258. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  7259. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7260. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  7261. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  7262. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  7263. }
  7264. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  7265. constructor: WebGLRenderTarget,
  7266. isWebGLRenderTarget: true,
  7267. setSize: function ( width, height ) {
  7268. if ( this.width !== width || this.height !== height ) {
  7269. this.width = width;
  7270. this.height = height;
  7271. this.dispose();
  7272. }
  7273. this.viewport.set( 0, 0, width, height );
  7274. this.scissor.set( 0, 0, width, height );
  7275. },
  7276. clone: function () {
  7277. return new this.constructor().copy( this );
  7278. },
  7279. copy: function ( source ) {
  7280. this.width = source.width;
  7281. this.height = source.height;
  7282. this.viewport.copy( source.viewport );
  7283. this.texture = source.texture.clone();
  7284. this.depthBuffer = source.depthBuffer;
  7285. this.stencilBuffer = source.stencilBuffer;
  7286. this.depthTexture = source.depthTexture;
  7287. return this;
  7288. },
  7289. dispose: function () {
  7290. this.dispatchEvent( { type: 'dispose' } );
  7291. }
  7292. } );
  7293. /**
  7294. * @author alteredq / http://alteredqualia.com
  7295. */
  7296. function WebGLRenderTargetCube( width, height, options ) {
  7297. WebGLRenderTarget.call( this, width, height, options );
  7298. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  7299. this.activeMipMapLevel = 0;
  7300. }
  7301. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  7302. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  7303. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  7304. /**
  7305. * @author alteredq / http://alteredqualia.com/
  7306. */
  7307. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  7308. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7309. this.image = { data: data, width: width, height: height };
  7310. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7311. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7312. this.generateMipmaps = false;
  7313. this.flipY = false;
  7314. this.unpackAlignment = 1;
  7315. }
  7316. DataTexture.prototype = Object.create( Texture.prototype );
  7317. DataTexture.prototype.constructor = DataTexture;
  7318. DataTexture.prototype.isDataTexture = true;
  7319. /**
  7320. * @author bhouston / http://clara.io
  7321. * @author WestLangley / http://github.com/WestLangley
  7322. */
  7323. function Box3( min, max ) {
  7324. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  7325. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  7326. }
  7327. Object.assign( Box3.prototype, {
  7328. isBox3: true,
  7329. set: function ( min, max ) {
  7330. this.min.copy( min );
  7331. this.max.copy( max );
  7332. return this;
  7333. },
  7334. setFromArray: function ( array ) {
  7335. var minX = + Infinity;
  7336. var minY = + Infinity;
  7337. var minZ = + Infinity;
  7338. var maxX = - Infinity;
  7339. var maxY = - Infinity;
  7340. var maxZ = - Infinity;
  7341. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  7342. var x = array[ i ];
  7343. var y = array[ i + 1 ];
  7344. var z = array[ i + 2 ];
  7345. if ( x < minX ) minX = x;
  7346. if ( y < minY ) minY = y;
  7347. if ( z < minZ ) minZ = z;
  7348. if ( x > maxX ) maxX = x;
  7349. if ( y > maxY ) maxY = y;
  7350. if ( z > maxZ ) maxZ = z;
  7351. }
  7352. this.min.set( minX, minY, minZ );
  7353. this.max.set( maxX, maxY, maxZ );
  7354. return this;
  7355. },
  7356. setFromBufferAttribute: function ( attribute ) {
  7357. var minX = + Infinity;
  7358. var minY = + Infinity;
  7359. var minZ = + Infinity;
  7360. var maxX = - Infinity;
  7361. var maxY = - Infinity;
  7362. var maxZ = - Infinity;
  7363. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  7364. var x = attribute.getX( i );
  7365. var y = attribute.getY( i );
  7366. var z = attribute.getZ( i );
  7367. if ( x < minX ) minX = x;
  7368. if ( y < minY ) minY = y;
  7369. if ( z < minZ ) minZ = z;
  7370. if ( x > maxX ) maxX = x;
  7371. if ( y > maxY ) maxY = y;
  7372. if ( z > maxZ ) maxZ = z;
  7373. }
  7374. this.min.set( minX, minY, minZ );
  7375. this.max.set( maxX, maxY, maxZ );
  7376. return this;
  7377. },
  7378. setFromPoints: function ( points ) {
  7379. this.makeEmpty();
  7380. for ( var i = 0, il = points.length; i < il; i ++ ) {
  7381. this.expandByPoint( points[ i ] );
  7382. }
  7383. return this;
  7384. },
  7385. setFromCenterAndSize: function () {
  7386. var v1 = new Vector3();
  7387. return function setFromCenterAndSize( center, size ) {
  7388. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  7389. this.min.copy( center ).sub( halfSize );
  7390. this.max.copy( center ).add( halfSize );
  7391. return this;
  7392. };
  7393. }(),
  7394. setFromObject: function ( object ) {
  7395. this.makeEmpty();
  7396. return this.expandByObject( object );
  7397. },
  7398. clone: function () {
  7399. return new this.constructor().copy( this );
  7400. },
  7401. copy: function ( box ) {
  7402. this.min.copy( box.min );
  7403. this.max.copy( box.max );
  7404. return this;
  7405. },
  7406. makeEmpty: function () {
  7407. this.min.x = this.min.y = this.min.z = + Infinity;
  7408. this.max.x = this.max.y = this.max.z = - Infinity;
  7409. return this;
  7410. },
  7411. isEmpty: function () {
  7412. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7413. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7414. },
  7415. getCenter: function ( target ) {
  7416. if ( target === undefined ) {
  7417. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  7418. target = new Vector3();
  7419. }
  7420. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7421. },
  7422. getSize: function ( target ) {
  7423. if ( target === undefined ) {
  7424. console.warn( 'THREE.Box3: .getSize() target is now required' );
  7425. target = new Vector3();
  7426. }
  7427. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7428. },
  7429. expandByPoint: function ( point ) {
  7430. this.min.min( point );
  7431. this.max.max( point );
  7432. return this;
  7433. },
  7434. expandByVector: function ( vector ) {
  7435. this.min.sub( vector );
  7436. this.max.add( vector );
  7437. return this;
  7438. },
  7439. expandByScalar: function ( scalar ) {
  7440. this.min.addScalar( - scalar );
  7441. this.max.addScalar( scalar );
  7442. return this;
  7443. },
  7444. expandByObject: function () {
  7445. // Computes the world-axis-aligned bounding box of an object (including its children),
  7446. // accounting for both the object's, and children's, world transforms
  7447. var scope, i, l;
  7448. var v1 = new Vector3();
  7449. function traverse( node ) {
  7450. var geometry = node.geometry;
  7451. if ( geometry !== undefined ) {
  7452. if ( geometry.isGeometry ) {
  7453. var vertices = geometry.vertices;
  7454. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  7455. v1.copy( vertices[ i ] );
  7456. v1.applyMatrix4( node.matrixWorld );
  7457. scope.expandByPoint( v1 );
  7458. }
  7459. } else if ( geometry.isBufferGeometry ) {
  7460. var attribute = geometry.attributes.position;
  7461. if ( attribute !== undefined ) {
  7462. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  7463. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  7464. scope.expandByPoint( v1 );
  7465. }
  7466. }
  7467. }
  7468. }
  7469. }
  7470. return function expandByObject( object ) {
  7471. scope = this;
  7472. object.updateMatrixWorld( true );
  7473. object.traverse( traverse );
  7474. return this;
  7475. };
  7476. }(),
  7477. containsPoint: function ( point ) {
  7478. return point.x < this.min.x || point.x > this.max.x ||
  7479. point.y < this.min.y || point.y > this.max.y ||
  7480. point.z < this.min.z || point.z > this.max.z ? false : true;
  7481. },
  7482. containsBox: function ( box ) {
  7483. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7484. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7485. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7486. },
  7487. getParameter: function ( point, target ) {
  7488. // This can potentially have a divide by zero if the box
  7489. // has a size dimension of 0.
  7490. if ( target === undefined ) {
  7491. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  7492. target = new Vector3();
  7493. }
  7494. return target.set(
  7495. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7496. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7497. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7498. );
  7499. },
  7500. intersectsBox: function ( box ) {
  7501. // using 6 splitting planes to rule out intersections.
  7502. return box.max.x < this.min.x || box.min.x > this.max.x ||
  7503. box.max.y < this.min.y || box.min.y > this.max.y ||
  7504. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  7505. },
  7506. intersectsSphere: ( function () {
  7507. var closestPoint = new Vector3();
  7508. return function intersectsSphere( sphere ) {
  7509. // Find the point on the AABB closest to the sphere center.
  7510. this.clampPoint( sphere.center, closestPoint );
  7511. // If that point is inside the sphere, the AABB and sphere intersect.
  7512. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7513. };
  7514. } )(),
  7515. intersectsPlane: function ( plane ) {
  7516. // We compute the minimum and maximum dot product values. If those values
  7517. // are on the same side (back or front) of the plane, then there is no intersection.
  7518. var min, max;
  7519. if ( plane.normal.x > 0 ) {
  7520. min = plane.normal.x * this.min.x;
  7521. max = plane.normal.x * this.max.x;
  7522. } else {
  7523. min = plane.normal.x * this.max.x;
  7524. max = plane.normal.x * this.min.x;
  7525. }
  7526. if ( plane.normal.y > 0 ) {
  7527. min += plane.normal.y * this.min.y;
  7528. max += plane.normal.y * this.max.y;
  7529. } else {
  7530. min += plane.normal.y * this.max.y;
  7531. max += plane.normal.y * this.min.y;
  7532. }
  7533. if ( plane.normal.z > 0 ) {
  7534. min += plane.normal.z * this.min.z;
  7535. max += plane.normal.z * this.max.z;
  7536. } else {
  7537. min += plane.normal.z * this.max.z;
  7538. max += plane.normal.z * this.min.z;
  7539. }
  7540. return ( min <= plane.constant && max >= plane.constant );
  7541. },
  7542. intersectsTriangle: ( function () {
  7543. // triangle centered vertices
  7544. var v0 = new Vector3();
  7545. var v1 = new Vector3();
  7546. var v2 = new Vector3();
  7547. // triangle edge vectors
  7548. var f0 = new Vector3();
  7549. var f1 = new Vector3();
  7550. var f2 = new Vector3();
  7551. var testAxis = new Vector3();
  7552. var center = new Vector3();
  7553. var extents = new Vector3();
  7554. var triangleNormal = new Vector3();
  7555. function satForAxes( axes ) {
  7556. var i, j;
  7557. for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7558. testAxis.fromArray( axes, i );
  7559. // project the aabb onto the seperating axis
  7560. var r = extents.x * Math.abs( testAxis.x ) + extents.y * Math.abs( testAxis.y ) + extents.z * Math.abs( testAxis.z );
  7561. // project all 3 vertices of the triangle onto the seperating axis
  7562. var p0 = v0.dot( testAxis );
  7563. var p1 = v1.dot( testAxis );
  7564. var p2 = v2.dot( testAxis );
  7565. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7566. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7567. // points of the projected triangle are outside the projected half-length of the aabb
  7568. // the axis is seperating and we can exit
  7569. return false;
  7570. }
  7571. }
  7572. return true;
  7573. }
  7574. return function intersectsTriangle( triangle ) {
  7575. if ( this.isEmpty() ) {
  7576. return false;
  7577. }
  7578. // compute box center and extents
  7579. this.getCenter( center );
  7580. extents.subVectors( this.max, center );
  7581. // translate triangle to aabb origin
  7582. v0.subVectors( triangle.a, center );
  7583. v1.subVectors( triangle.b, center );
  7584. v2.subVectors( triangle.c, center );
  7585. // compute edge vectors for triangle
  7586. f0.subVectors( v1, v0 );
  7587. f1.subVectors( v2, v1 );
  7588. f2.subVectors( v0, v2 );
  7589. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7590. // 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
  7591. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7592. var axes = [
  7593. 0, - f0.z, f0.y, 0, - f1.z, f1.y, 0, - f2.z, f2.y,
  7594. f0.z, 0, - f0.x, f1.z, 0, - f1.x, f2.z, 0, - f2.x,
  7595. - f0.y, f0.x, 0, - f1.y, f1.x, 0, - f2.y, f2.x, 0
  7596. ];
  7597. if ( ! satForAxes( axes ) ) {
  7598. return false;
  7599. }
  7600. // test 3 face normals from the aabb
  7601. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7602. if ( ! satForAxes( axes ) ) {
  7603. return false;
  7604. }
  7605. // finally testing the face normal of the triangle
  7606. // use already existing triangle edge vectors here
  7607. triangleNormal.crossVectors( f0, f1 );
  7608. axes = [ triangleNormal.x, triangleNormal.y, triangleNormal.z ];
  7609. return satForAxes( axes );
  7610. };
  7611. } )(),
  7612. clampPoint: function ( point, target ) {
  7613. if ( target === undefined ) {
  7614. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  7615. target = new Vector3();
  7616. }
  7617. return target.copy( point ).clamp( this.min, this.max );
  7618. },
  7619. distanceToPoint: function () {
  7620. var v1 = new Vector3();
  7621. return function distanceToPoint( point ) {
  7622. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  7623. return clampedPoint.sub( point ).length();
  7624. };
  7625. }(),
  7626. getBoundingSphere: function () {
  7627. var v1 = new Vector3();
  7628. return function getBoundingSphere( target ) {
  7629. if ( target === undefined ) {
  7630. console.warn( 'THREE.Box3: .getBoundingSphere() target is now required' );
  7631. target = new Sphere();
  7632. }
  7633. this.getCenter( target.center );
  7634. target.radius = this.getSize( v1 ).length() * 0.5;
  7635. return target;
  7636. };
  7637. }(),
  7638. intersect: function ( box ) {
  7639. this.min.max( box.min );
  7640. this.max.min( box.max );
  7641. // 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.
  7642. if ( this.isEmpty() ) this.makeEmpty();
  7643. return this;
  7644. },
  7645. union: function ( box ) {
  7646. this.min.min( box.min );
  7647. this.max.max( box.max );
  7648. return this;
  7649. },
  7650. applyMatrix4: function () {
  7651. var points = [
  7652. new Vector3(),
  7653. new Vector3(),
  7654. new Vector3(),
  7655. new Vector3(),
  7656. new Vector3(),
  7657. new Vector3(),
  7658. new Vector3(),
  7659. new Vector3()
  7660. ];
  7661. return function applyMatrix4( matrix ) {
  7662. // transform of empty box is an empty box.
  7663. if ( this.isEmpty() ) return this;
  7664. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7665. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7666. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7667. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7668. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7669. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7670. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7671. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7672. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7673. this.setFromPoints( points );
  7674. return this;
  7675. };
  7676. }(),
  7677. translate: function ( offset ) {
  7678. this.min.add( offset );
  7679. this.max.add( offset );
  7680. return this;
  7681. },
  7682. equals: function ( box ) {
  7683. return box.min.equals( this.min ) && box.max.equals( this.max );
  7684. }
  7685. } );
  7686. /**
  7687. * @author bhouston / http://clara.io
  7688. * @author mrdoob / http://mrdoob.com/
  7689. */
  7690. function Sphere( center, radius ) {
  7691. this.center = ( center !== undefined ) ? center : new Vector3();
  7692. this.radius = ( radius !== undefined ) ? radius : 0;
  7693. }
  7694. Object.assign( Sphere.prototype, {
  7695. set: function ( center, radius ) {
  7696. this.center.copy( center );
  7697. this.radius = radius;
  7698. return this;
  7699. },
  7700. setFromPoints: function () {
  7701. var box = new Box3();
  7702. return function setFromPoints( points, optionalCenter ) {
  7703. var center = this.center;
  7704. if ( optionalCenter !== undefined ) {
  7705. center.copy( optionalCenter );
  7706. } else {
  7707. box.setFromPoints( points ).getCenter( center );
  7708. }
  7709. var maxRadiusSq = 0;
  7710. for ( var i = 0, il = points.length; i < il; i ++ ) {
  7711. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7712. }
  7713. this.radius = Math.sqrt( maxRadiusSq );
  7714. return this;
  7715. };
  7716. }(),
  7717. clone: function () {
  7718. return new this.constructor().copy( this );
  7719. },
  7720. copy: function ( sphere ) {
  7721. this.center.copy( sphere.center );
  7722. this.radius = sphere.radius;
  7723. return this;
  7724. },
  7725. empty: function () {
  7726. return ( this.radius <= 0 );
  7727. },
  7728. containsPoint: function ( point ) {
  7729. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7730. },
  7731. distanceToPoint: function ( point ) {
  7732. return ( point.distanceTo( this.center ) - this.radius );
  7733. },
  7734. intersectsSphere: function ( sphere ) {
  7735. var radiusSum = this.radius + sphere.radius;
  7736. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  7737. },
  7738. intersectsBox: function ( box ) {
  7739. return box.intersectsSphere( this );
  7740. },
  7741. intersectsPlane: function ( plane ) {
  7742. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  7743. },
  7744. clampPoint: function ( point, target ) {
  7745. var deltaLengthSq = this.center.distanceToSquared( point );
  7746. if ( target === undefined ) {
  7747. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  7748. target = new Vector3();
  7749. }
  7750. target.copy( point );
  7751. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  7752. target.sub( this.center ).normalize();
  7753. target.multiplyScalar( this.radius ).add( this.center );
  7754. }
  7755. return target;
  7756. },
  7757. getBoundingBox: function ( target ) {
  7758. if ( target === undefined ) {
  7759. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  7760. target = new Box3();
  7761. }
  7762. target.set( this.center, this.center );
  7763. target.expandByScalar( this.radius );
  7764. return target;
  7765. },
  7766. applyMatrix4: function ( matrix ) {
  7767. this.center.applyMatrix4( matrix );
  7768. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  7769. return this;
  7770. },
  7771. translate: function ( offset ) {
  7772. this.center.add( offset );
  7773. return this;
  7774. },
  7775. equals: function ( sphere ) {
  7776. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  7777. }
  7778. } );
  7779. /**
  7780. * @author bhouston / http://clara.io
  7781. */
  7782. function Plane( normal, constant ) {
  7783. // normal is assumed to be normalized
  7784. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  7785. this.constant = ( constant !== undefined ) ? constant : 0;
  7786. }
  7787. Object.assign( Plane.prototype, {
  7788. set: function ( normal, constant ) {
  7789. this.normal.copy( normal );
  7790. this.constant = constant;
  7791. return this;
  7792. },
  7793. setComponents: function ( x, y, z, w ) {
  7794. this.normal.set( x, y, z );
  7795. this.constant = w;
  7796. return this;
  7797. },
  7798. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  7799. this.normal.copy( normal );
  7800. this.constant = - point.dot( this.normal );
  7801. return this;
  7802. },
  7803. setFromCoplanarPoints: function () {
  7804. var v1 = new Vector3();
  7805. var v2 = new Vector3();
  7806. return function setFromCoplanarPoints( a, b, c ) {
  7807. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  7808. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7809. this.setFromNormalAndCoplanarPoint( normal, a );
  7810. return this;
  7811. };
  7812. }(),
  7813. clone: function () {
  7814. return new this.constructor().copy( this );
  7815. },
  7816. copy: function ( plane ) {
  7817. this.normal.copy( plane.normal );
  7818. this.constant = plane.constant;
  7819. return this;
  7820. },
  7821. normalize: function () {
  7822. // Note: will lead to a divide by zero if the plane is invalid.
  7823. var inverseNormalLength = 1.0 / this.normal.length();
  7824. this.normal.multiplyScalar( inverseNormalLength );
  7825. this.constant *= inverseNormalLength;
  7826. return this;
  7827. },
  7828. negate: function () {
  7829. this.constant *= - 1;
  7830. this.normal.negate();
  7831. return this;
  7832. },
  7833. distanceToPoint: function ( point ) {
  7834. return this.normal.dot( point ) + this.constant;
  7835. },
  7836. distanceToSphere: function ( sphere ) {
  7837. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7838. },
  7839. projectPoint: function ( point, target ) {
  7840. if ( target === undefined ) {
  7841. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  7842. target = new Vector3();
  7843. }
  7844. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7845. },
  7846. intersectLine: function () {
  7847. var v1 = new Vector3();
  7848. return function intersectLine( line, target ) {
  7849. if ( target === undefined ) {
  7850. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  7851. target = new Vector3();
  7852. }
  7853. var direction = line.delta( v1 );
  7854. var denominator = this.normal.dot( direction );
  7855. if ( denominator === 0 ) {
  7856. // line is coplanar, return origin
  7857. if ( this.distanceToPoint( line.start ) === 0 ) {
  7858. return target.copy( line.start );
  7859. }
  7860. // Unsure if this is the correct method to handle this case.
  7861. return undefined;
  7862. }
  7863. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7864. if ( t < 0 || t > 1 ) {
  7865. return undefined;
  7866. }
  7867. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7868. };
  7869. }(),
  7870. intersectsLine: function ( line ) {
  7871. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7872. var startSign = this.distanceToPoint( line.start );
  7873. var endSign = this.distanceToPoint( line.end );
  7874. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7875. },
  7876. intersectsBox: function ( box ) {
  7877. return box.intersectsPlane( this );
  7878. },
  7879. intersectsSphere: function ( sphere ) {
  7880. return sphere.intersectsPlane( this );
  7881. },
  7882. coplanarPoint: function ( target ) {
  7883. if ( target === undefined ) {
  7884. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  7885. target = new Vector3();
  7886. }
  7887. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7888. },
  7889. applyMatrix4: function () {
  7890. var v1 = new Vector3();
  7891. var m1 = new Matrix3();
  7892. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  7893. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  7894. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  7895. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7896. this.constant = - referencePoint.dot( normal );
  7897. return this;
  7898. };
  7899. }(),
  7900. translate: function ( offset ) {
  7901. this.constant -= offset.dot( this.normal );
  7902. return this;
  7903. },
  7904. equals: function ( plane ) {
  7905. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7906. }
  7907. } );
  7908. /**
  7909. * @author mrdoob / http://mrdoob.com/
  7910. * @author alteredq / http://alteredqualia.com/
  7911. * @author bhouston / http://clara.io
  7912. */
  7913. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  7914. this.planes = [
  7915. ( p0 !== undefined ) ? p0 : new Plane(),
  7916. ( p1 !== undefined ) ? p1 : new Plane(),
  7917. ( p2 !== undefined ) ? p2 : new Plane(),
  7918. ( p3 !== undefined ) ? p3 : new Plane(),
  7919. ( p4 !== undefined ) ? p4 : new Plane(),
  7920. ( p5 !== undefined ) ? p5 : new Plane()
  7921. ];
  7922. }
  7923. Object.assign( Frustum.prototype, {
  7924. set: function ( p0, p1, p2, p3, p4, p5 ) {
  7925. var planes = this.planes;
  7926. planes[ 0 ].copy( p0 );
  7927. planes[ 1 ].copy( p1 );
  7928. planes[ 2 ].copy( p2 );
  7929. planes[ 3 ].copy( p3 );
  7930. planes[ 4 ].copy( p4 );
  7931. planes[ 5 ].copy( p5 );
  7932. return this;
  7933. },
  7934. clone: function () {
  7935. return new this.constructor().copy( this );
  7936. },
  7937. copy: function ( frustum ) {
  7938. var planes = this.planes;
  7939. for ( var i = 0; i < 6; i ++ ) {
  7940. planes[ i ].copy( frustum.planes[ i ] );
  7941. }
  7942. return this;
  7943. },
  7944. setFromMatrix: function ( m ) {
  7945. var planes = this.planes;
  7946. var me = m.elements;
  7947. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7948. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7949. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7950. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7951. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7952. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7953. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7954. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7955. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7956. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7957. return this;
  7958. },
  7959. intersectsObject: function () {
  7960. var sphere = new Sphere();
  7961. return function intersectsObject( object ) {
  7962. var geometry = object.geometry;
  7963. if ( geometry.boundingSphere === null )
  7964. geometry.computeBoundingSphere();
  7965. sphere.copy( geometry.boundingSphere )
  7966. .applyMatrix4( object.matrixWorld );
  7967. return this.intersectsSphere( sphere );
  7968. };
  7969. }(),
  7970. intersectsSprite: function () {
  7971. var sphere = new Sphere();
  7972. return function intersectsSprite( sprite ) {
  7973. sphere.center.set( 0, 0, 0 );
  7974. sphere.radius = 0.7071067811865476;
  7975. sphere.applyMatrix4( sprite.matrixWorld );
  7976. return this.intersectsSphere( sphere );
  7977. };
  7978. }(),
  7979. intersectsSphere: function ( sphere ) {
  7980. var planes = this.planes;
  7981. var center = sphere.center;
  7982. var negRadius = - sphere.radius;
  7983. for ( var i = 0; i < 6; i ++ ) {
  7984. var distance = planes[ i ].distanceToPoint( center );
  7985. if ( distance < negRadius ) {
  7986. return false;
  7987. }
  7988. }
  7989. return true;
  7990. },
  7991. intersectsBox: function () {
  7992. var p1 = new Vector3(),
  7993. p2 = new Vector3();
  7994. return function intersectsBox( box ) {
  7995. var planes = this.planes;
  7996. for ( var i = 0; i < 6; i ++ ) {
  7997. var plane = planes[ i ];
  7998. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  7999. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8000. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  8001. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8002. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  8003. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8004. var d1 = plane.distanceToPoint( p1 );
  8005. var d2 = plane.distanceToPoint( p2 );
  8006. // if both outside plane, no intersection
  8007. if ( d1 < 0 && d2 < 0 ) {
  8008. return false;
  8009. }
  8010. }
  8011. return true;
  8012. };
  8013. }(),
  8014. containsPoint: function ( point ) {
  8015. var planes = this.planes;
  8016. for ( var i = 0; i < 6; i ++ ) {
  8017. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  8018. return false;
  8019. }
  8020. }
  8021. return true;
  8022. }
  8023. } );
  8024. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  8025. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  8026. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  8027. 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";
  8028. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8029. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  8030. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  8031. 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";
  8032. 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\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  8033. 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";
  8034. 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";
  8035. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  8036. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  8037. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8038. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  8039. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8040. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  8041. 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";
  8042. 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(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";
  8043. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n";
  8044. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  8045. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  8046. 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";
  8047. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  8048. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  8049. 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";
  8050. 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";
  8051. 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";
  8052. 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";
  8053. 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";
  8054. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  8055. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  8056. 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";
  8057. 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";
  8058. 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";
  8059. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  8060. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8061. 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";
  8062. 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";
  8063. var lights_pars_maps = "#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( 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(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";
  8064. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  8065. 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";
  8066. 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";
  8067. 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";
  8068. 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";
  8069. 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";
  8070. 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";
  8071. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8072. 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";
  8073. 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";
  8074. 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";
  8075. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  8076. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  8077. 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";
  8078. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif\n";
  8079. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";
  8080. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8081. 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";
  8082. 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";
  8083. 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";
  8084. 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";
  8085. var normal_fragment_maps = "#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  8086. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\t\tscale *= float( gl_FrontFacing ) * 2.0 - 1.0;\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  8087. 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";
  8088. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  8089. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n";
  8090. var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";
  8091. 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";
  8092. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";
  8093. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8094. 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";
  8095. 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";
  8096. 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";
  8097. 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";
  8098. 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";
  8099. 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";
  8100. 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";
  8101. 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";
  8102. 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";
  8103. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8104. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  8105. 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";
  8106. 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";
  8107. 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";
  8108. 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";
  8109. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8110. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  8111. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  8112. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n";
  8113. 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";
  8114. 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";
  8115. 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";
  8116. 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";
  8117. 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";
  8118. 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";
  8119. 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";
  8120. 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";
  8121. 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";
  8122. 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";
  8123. 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";
  8124. 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";
  8125. 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 <lights_pars_maps>\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";
  8126. 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 <lights_pars_maps>\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";
  8127. 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_pars_maps>\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";
  8128. 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";
  8129. 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 <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars_begin>\n#include <lights_pars_maps>\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";
  8130. 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";
  8131. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_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";
  8132. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_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 )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n";
  8133. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_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";
  8134. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <shadowmap_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 <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 <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  8135. 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";
  8136. 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";
  8137. var ShaderChunk = {
  8138. alphamap_fragment: alphamap_fragment,
  8139. alphamap_pars_fragment: alphamap_pars_fragment,
  8140. alphatest_fragment: alphatest_fragment,
  8141. aomap_fragment: aomap_fragment,
  8142. aomap_pars_fragment: aomap_pars_fragment,
  8143. begin_vertex: begin_vertex,
  8144. beginnormal_vertex: beginnormal_vertex,
  8145. bsdfs: bsdfs,
  8146. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8147. clipping_planes_fragment: clipping_planes_fragment,
  8148. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8149. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8150. clipping_planes_vertex: clipping_planes_vertex,
  8151. color_fragment: color_fragment,
  8152. color_pars_fragment: color_pars_fragment,
  8153. color_pars_vertex: color_pars_vertex,
  8154. color_vertex: color_vertex,
  8155. common: common,
  8156. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8157. defaultnormal_vertex: defaultnormal_vertex,
  8158. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8159. displacementmap_vertex: displacementmap_vertex,
  8160. emissivemap_fragment: emissivemap_fragment,
  8161. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8162. encodings_fragment: encodings_fragment,
  8163. encodings_pars_fragment: encodings_pars_fragment,
  8164. envmap_fragment: envmap_fragment,
  8165. envmap_pars_fragment: envmap_pars_fragment,
  8166. envmap_pars_vertex: envmap_pars_vertex,
  8167. envmap_vertex: envmap_vertex,
  8168. fog_vertex: fog_vertex,
  8169. fog_pars_vertex: fog_pars_vertex,
  8170. fog_fragment: fog_fragment,
  8171. fog_pars_fragment: fog_pars_fragment,
  8172. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8173. lightmap_fragment: lightmap_fragment,
  8174. lightmap_pars_fragment: lightmap_pars_fragment,
  8175. lights_lambert_vertex: lights_lambert_vertex,
  8176. lights_pars_begin: lights_pars_begin,
  8177. lights_pars_maps: lights_pars_maps,
  8178. lights_phong_fragment: lights_phong_fragment,
  8179. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8180. lights_physical_fragment: lights_physical_fragment,
  8181. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8182. lights_fragment_begin: lights_fragment_begin,
  8183. lights_fragment_maps: lights_fragment_maps,
  8184. lights_fragment_end: lights_fragment_end,
  8185. logdepthbuf_fragment: logdepthbuf_fragment,
  8186. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8187. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8188. logdepthbuf_vertex: logdepthbuf_vertex,
  8189. map_fragment: map_fragment,
  8190. map_pars_fragment: map_pars_fragment,
  8191. map_particle_fragment: map_particle_fragment,
  8192. map_particle_pars_fragment: map_particle_pars_fragment,
  8193. metalnessmap_fragment: metalnessmap_fragment,
  8194. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8195. morphnormal_vertex: morphnormal_vertex,
  8196. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8197. morphtarget_vertex: morphtarget_vertex,
  8198. normal_fragment_begin: normal_fragment_begin,
  8199. normal_fragment_maps: normal_fragment_maps,
  8200. normalmap_pars_fragment: normalmap_pars_fragment,
  8201. packing: packing,
  8202. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8203. project_vertex: project_vertex,
  8204. dithering_fragment: dithering_fragment,
  8205. dithering_pars_fragment: dithering_pars_fragment,
  8206. roughnessmap_fragment: roughnessmap_fragment,
  8207. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8208. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8209. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8210. shadowmap_vertex: shadowmap_vertex,
  8211. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8212. skinbase_vertex: skinbase_vertex,
  8213. skinning_pars_vertex: skinning_pars_vertex,
  8214. skinning_vertex: skinning_vertex,
  8215. skinnormal_vertex: skinnormal_vertex,
  8216. specularmap_fragment: specularmap_fragment,
  8217. specularmap_pars_fragment: specularmap_pars_fragment,
  8218. tonemapping_fragment: tonemapping_fragment,
  8219. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8220. uv_pars_fragment: uv_pars_fragment,
  8221. uv_pars_vertex: uv_pars_vertex,
  8222. uv_vertex: uv_vertex,
  8223. uv2_pars_fragment: uv2_pars_fragment,
  8224. uv2_pars_vertex: uv2_pars_vertex,
  8225. uv2_vertex: uv2_vertex,
  8226. worldpos_vertex: worldpos_vertex,
  8227. cube_frag: cube_frag,
  8228. cube_vert: cube_vert,
  8229. depth_frag: depth_frag,
  8230. depth_vert: depth_vert,
  8231. distanceRGBA_frag: distanceRGBA_frag,
  8232. distanceRGBA_vert: distanceRGBA_vert,
  8233. equirect_frag: equirect_frag,
  8234. equirect_vert: equirect_vert,
  8235. linedashed_frag: linedashed_frag,
  8236. linedashed_vert: linedashed_vert,
  8237. meshbasic_frag: meshbasic_frag,
  8238. meshbasic_vert: meshbasic_vert,
  8239. meshlambert_frag: meshlambert_frag,
  8240. meshlambert_vert: meshlambert_vert,
  8241. meshphong_frag: meshphong_frag,
  8242. meshphong_vert: meshphong_vert,
  8243. meshphysical_frag: meshphysical_frag,
  8244. meshphysical_vert: meshphysical_vert,
  8245. normal_frag: normal_frag,
  8246. normal_vert: normal_vert,
  8247. points_frag: points_frag,
  8248. points_vert: points_vert,
  8249. shadow_frag: shadow_frag,
  8250. shadow_vert: shadow_vert
  8251. };
  8252. /**
  8253. * Uniform Utilities
  8254. */
  8255. var UniformsUtils = {
  8256. merge: function ( uniforms ) {
  8257. var merged = {};
  8258. for ( var u = 0; u < uniforms.length; u ++ ) {
  8259. var tmp = this.clone( uniforms[ u ] );
  8260. for ( var p in tmp ) {
  8261. merged[ p ] = tmp[ p ];
  8262. }
  8263. }
  8264. return merged;
  8265. },
  8266. clone: function ( uniforms_src ) {
  8267. var uniforms_dst = {};
  8268. for ( var u in uniforms_src ) {
  8269. uniforms_dst[ u ] = {};
  8270. for ( var p in uniforms_src[ u ] ) {
  8271. var parameter_src = uniforms_src[ u ][ p ];
  8272. if ( parameter_src && ( parameter_src.isColor ||
  8273. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  8274. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  8275. parameter_src.isTexture ) ) {
  8276. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8277. } else if ( Array.isArray( parameter_src ) ) {
  8278. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8279. } else {
  8280. uniforms_dst[ u ][ p ] = parameter_src;
  8281. }
  8282. }
  8283. }
  8284. return uniforms_dst;
  8285. }
  8286. };
  8287. /**
  8288. * @author mrdoob / http://mrdoob.com/
  8289. */
  8290. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  8291. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  8292. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  8293. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  8294. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  8295. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  8296. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  8297. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  8298. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  8299. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  8300. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  8301. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  8302. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  8303. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  8304. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  8305. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  8306. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  8307. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  8308. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  8309. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  8310. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  8311. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  8312. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  8313. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  8314. function Color( r, g, b ) {
  8315. if ( g === undefined && b === undefined ) {
  8316. // r is THREE.Color, hex or string
  8317. return this.set( r );
  8318. }
  8319. return this.setRGB( r, g, b );
  8320. }
  8321. Object.assign( Color.prototype, {
  8322. isColor: true,
  8323. r: 1, g: 1, b: 1,
  8324. set: function ( value ) {
  8325. if ( value && value.isColor ) {
  8326. this.copy( value );
  8327. } else if ( typeof value === 'number' ) {
  8328. this.setHex( value );
  8329. } else if ( typeof value === 'string' ) {
  8330. this.setStyle( value );
  8331. }
  8332. return this;
  8333. },
  8334. setScalar: function ( scalar ) {
  8335. this.r = scalar;
  8336. this.g = scalar;
  8337. this.b = scalar;
  8338. return this;
  8339. },
  8340. setHex: function ( hex ) {
  8341. hex = Math.floor( hex );
  8342. this.r = ( hex >> 16 & 255 ) / 255;
  8343. this.g = ( hex >> 8 & 255 ) / 255;
  8344. this.b = ( hex & 255 ) / 255;
  8345. return this;
  8346. },
  8347. setRGB: function ( r, g, b ) {
  8348. this.r = r;
  8349. this.g = g;
  8350. this.b = b;
  8351. return this;
  8352. },
  8353. setHSL: function () {
  8354. function hue2rgb( p, q, t ) {
  8355. if ( t < 0 ) t += 1;
  8356. if ( t > 1 ) t -= 1;
  8357. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  8358. if ( t < 1 / 2 ) return q;
  8359. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  8360. return p;
  8361. }
  8362. return function setHSL( h, s, l ) {
  8363. // h,s,l ranges are in 0.0 - 1.0
  8364. h = _Math.euclideanModulo( h, 1 );
  8365. s = _Math.clamp( s, 0, 1 );
  8366. l = _Math.clamp( l, 0, 1 );
  8367. if ( s === 0 ) {
  8368. this.r = this.g = this.b = l;
  8369. } else {
  8370. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  8371. var q = ( 2 * l ) - p;
  8372. this.r = hue2rgb( q, p, h + 1 / 3 );
  8373. this.g = hue2rgb( q, p, h );
  8374. this.b = hue2rgb( q, p, h - 1 / 3 );
  8375. }
  8376. return this;
  8377. };
  8378. }(),
  8379. setStyle: function ( style ) {
  8380. function handleAlpha( string ) {
  8381. if ( string === undefined ) return;
  8382. if ( parseFloat( string ) < 1 ) {
  8383. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  8384. }
  8385. }
  8386. var m;
  8387. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  8388. // rgb / hsl
  8389. var color;
  8390. var name = m[ 1 ];
  8391. var components = m[ 2 ];
  8392. switch ( name ) {
  8393. case 'rgb':
  8394. case 'rgba':
  8395. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  8396. // rgb(255,0,0) rgba(255,0,0,0.5)
  8397. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  8398. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  8399. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  8400. handleAlpha( color[ 5 ] );
  8401. return this;
  8402. }
  8403. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  8404. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  8405. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  8406. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  8407. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  8408. handleAlpha( color[ 5 ] );
  8409. return this;
  8410. }
  8411. break;
  8412. case 'hsl':
  8413. case 'hsla':
  8414. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  8415. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  8416. var h = parseFloat( color[ 1 ] ) / 360;
  8417. var s = parseInt( color[ 2 ], 10 ) / 100;
  8418. var l = parseInt( color[ 3 ], 10 ) / 100;
  8419. handleAlpha( color[ 5 ] );
  8420. return this.setHSL( h, s, l );
  8421. }
  8422. break;
  8423. }
  8424. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  8425. // hex color
  8426. var hex = m[ 1 ];
  8427. var size = hex.length;
  8428. if ( size === 3 ) {
  8429. // #ff0
  8430. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  8431. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  8432. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  8433. return this;
  8434. } else if ( size === 6 ) {
  8435. // #ff0000
  8436. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  8437. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  8438. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  8439. return this;
  8440. }
  8441. }
  8442. if ( style && style.length > 0 ) {
  8443. // color keywords
  8444. var hex = ColorKeywords[ style ];
  8445. if ( hex !== undefined ) {
  8446. // red
  8447. this.setHex( hex );
  8448. } else {
  8449. // unknown color
  8450. console.warn( 'THREE.Color: Unknown color ' + style );
  8451. }
  8452. }
  8453. return this;
  8454. },
  8455. clone: function () {
  8456. return new this.constructor( this.r, this.g, this.b );
  8457. },
  8458. copy: function ( color ) {
  8459. this.r = color.r;
  8460. this.g = color.g;
  8461. this.b = color.b;
  8462. return this;
  8463. },
  8464. copyGammaToLinear: function ( color, gammaFactor ) {
  8465. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  8466. this.r = Math.pow( color.r, gammaFactor );
  8467. this.g = Math.pow( color.g, gammaFactor );
  8468. this.b = Math.pow( color.b, gammaFactor );
  8469. return this;
  8470. },
  8471. copyLinearToGamma: function ( color, gammaFactor ) {
  8472. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  8473. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  8474. this.r = Math.pow( color.r, safeInverse );
  8475. this.g = Math.pow( color.g, safeInverse );
  8476. this.b = Math.pow( color.b, safeInverse );
  8477. return this;
  8478. },
  8479. convertGammaToLinear: function () {
  8480. var r = this.r, g = this.g, b = this.b;
  8481. this.r = r * r;
  8482. this.g = g * g;
  8483. this.b = b * b;
  8484. return this;
  8485. },
  8486. convertLinearToGamma: function () {
  8487. this.r = Math.sqrt( this.r );
  8488. this.g = Math.sqrt( this.g );
  8489. this.b = Math.sqrt( this.b );
  8490. return this;
  8491. },
  8492. getHex: function () {
  8493. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  8494. },
  8495. getHexString: function () {
  8496. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  8497. },
  8498. getHSL: function ( target ) {
  8499. // h,s,l ranges are in 0.0 - 1.0
  8500. if ( target === undefined ) {
  8501. console.warn( 'THREE.Color: .getHSL() target is now required' );
  8502. target = { h: 0, s: 0, l: 0 };
  8503. }
  8504. var r = this.r, g = this.g, b = this.b;
  8505. var max = Math.max( r, g, b );
  8506. var min = Math.min( r, g, b );
  8507. var hue, saturation;
  8508. var lightness = ( min + max ) / 2.0;
  8509. if ( min === max ) {
  8510. hue = 0;
  8511. saturation = 0;
  8512. } else {
  8513. var delta = max - min;
  8514. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  8515. switch ( max ) {
  8516. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  8517. case g: hue = ( b - r ) / delta + 2; break;
  8518. case b: hue = ( r - g ) / delta + 4; break;
  8519. }
  8520. hue /= 6;
  8521. }
  8522. target.h = hue;
  8523. target.s = saturation;
  8524. target.l = lightness;
  8525. return target;
  8526. },
  8527. getStyle: function () {
  8528. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  8529. },
  8530. offsetHSL: function () {
  8531. var hsl = {};
  8532. return function ( h, s, l ) {
  8533. this.getHSL( hsl );
  8534. hsl.h += h; hsl.s += s; hsl.l += l;
  8535. this.setHSL( hsl.h, hsl.s, hsl.l );
  8536. return this;
  8537. };
  8538. }(),
  8539. add: function ( color ) {
  8540. this.r += color.r;
  8541. this.g += color.g;
  8542. this.b += color.b;
  8543. return this;
  8544. },
  8545. addColors: function ( color1, color2 ) {
  8546. this.r = color1.r + color2.r;
  8547. this.g = color1.g + color2.g;
  8548. this.b = color1.b + color2.b;
  8549. return this;
  8550. },
  8551. addScalar: function ( s ) {
  8552. this.r += s;
  8553. this.g += s;
  8554. this.b += s;
  8555. return this;
  8556. },
  8557. sub: function ( color ) {
  8558. this.r = Math.max( 0, this.r - color.r );
  8559. this.g = Math.max( 0, this.g - color.g );
  8560. this.b = Math.max( 0, this.b - color.b );
  8561. return this;
  8562. },
  8563. multiply: function ( color ) {
  8564. this.r *= color.r;
  8565. this.g *= color.g;
  8566. this.b *= color.b;
  8567. return this;
  8568. },
  8569. multiplyScalar: function ( s ) {
  8570. this.r *= s;
  8571. this.g *= s;
  8572. this.b *= s;
  8573. return this;
  8574. },
  8575. lerp: function ( color, alpha ) {
  8576. this.r += ( color.r - this.r ) * alpha;
  8577. this.g += ( color.g - this.g ) * alpha;
  8578. this.b += ( color.b - this.b ) * alpha;
  8579. return this;
  8580. },
  8581. equals: function ( c ) {
  8582. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  8583. },
  8584. fromArray: function ( array, offset ) {
  8585. if ( offset === undefined ) offset = 0;
  8586. this.r = array[ offset ];
  8587. this.g = array[ offset + 1 ];
  8588. this.b = array[ offset + 2 ];
  8589. return this;
  8590. },
  8591. toArray: function ( array, offset ) {
  8592. if ( array === undefined ) array = [];
  8593. if ( offset === undefined ) offset = 0;
  8594. array[ offset ] = this.r;
  8595. array[ offset + 1 ] = this.g;
  8596. array[ offset + 2 ] = this.b;
  8597. return array;
  8598. },
  8599. toJSON: function () {
  8600. return this.getHex();
  8601. }
  8602. } );
  8603. /**
  8604. * Uniforms library for shared webgl shaders
  8605. */
  8606. var UniformsLib = {
  8607. common: {
  8608. diffuse: { value: new Color( 0xeeeeee ) },
  8609. opacity: { value: 1.0 },
  8610. map: { value: null },
  8611. uvTransform: { value: new Matrix3() },
  8612. alphaMap: { value: null },
  8613. },
  8614. specularmap: {
  8615. specularMap: { value: null },
  8616. },
  8617. envmap: {
  8618. envMap: { value: null },
  8619. flipEnvMap: { value: - 1 },
  8620. reflectivity: { value: 1.0 },
  8621. refractionRatio: { value: 0.98 },
  8622. maxMipLevel: { value: 0 }
  8623. },
  8624. aomap: {
  8625. aoMap: { value: null },
  8626. aoMapIntensity: { value: 1 }
  8627. },
  8628. lightmap: {
  8629. lightMap: { value: null },
  8630. lightMapIntensity: { value: 1 }
  8631. },
  8632. emissivemap: {
  8633. emissiveMap: { value: null }
  8634. },
  8635. bumpmap: {
  8636. bumpMap: { value: null },
  8637. bumpScale: { value: 1 }
  8638. },
  8639. normalmap: {
  8640. normalMap: { value: null },
  8641. normalScale: { value: new Vector2( 1, 1 ) }
  8642. },
  8643. displacementmap: {
  8644. displacementMap: { value: null },
  8645. displacementScale: { value: 1 },
  8646. displacementBias: { value: 0 }
  8647. },
  8648. roughnessmap: {
  8649. roughnessMap: { value: null }
  8650. },
  8651. metalnessmap: {
  8652. metalnessMap: { value: null }
  8653. },
  8654. gradientmap: {
  8655. gradientMap: { value: null }
  8656. },
  8657. fog: {
  8658. fogDensity: { value: 0.00025 },
  8659. fogNear: { value: 1 },
  8660. fogFar: { value: 2000 },
  8661. fogColor: { value: new Color( 0xffffff ) }
  8662. },
  8663. lights: {
  8664. ambientLightColor: { value: [] },
  8665. directionalLights: { value: [], properties: {
  8666. direction: {},
  8667. color: {},
  8668. shadow: {},
  8669. shadowBias: {},
  8670. shadowRadius: {},
  8671. shadowMapSize: {}
  8672. } },
  8673. directionalShadowMap: { value: [] },
  8674. directionalShadowMatrix: { value: [] },
  8675. spotLights: { value: [], properties: {
  8676. color: {},
  8677. position: {},
  8678. direction: {},
  8679. distance: {},
  8680. coneCos: {},
  8681. penumbraCos: {},
  8682. decay: {},
  8683. shadow: {},
  8684. shadowBias: {},
  8685. shadowRadius: {},
  8686. shadowMapSize: {}
  8687. } },
  8688. spotShadowMap: { value: [] },
  8689. spotShadowMatrix: { value: [] },
  8690. pointLights: { value: [], properties: {
  8691. color: {},
  8692. position: {},
  8693. decay: {},
  8694. distance: {},
  8695. shadow: {},
  8696. shadowBias: {},
  8697. shadowRadius: {},
  8698. shadowMapSize: {},
  8699. shadowCameraNear: {},
  8700. shadowCameraFar: {}
  8701. } },
  8702. pointShadowMap: { value: [] },
  8703. pointShadowMatrix: { value: [] },
  8704. hemisphereLights: { value: [], properties: {
  8705. direction: {},
  8706. skyColor: {},
  8707. groundColor: {}
  8708. } },
  8709. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8710. rectAreaLights: { value: [], properties: {
  8711. color: {},
  8712. position: {},
  8713. width: {},
  8714. height: {}
  8715. } }
  8716. },
  8717. points: {
  8718. diffuse: { value: new Color( 0xeeeeee ) },
  8719. opacity: { value: 1.0 },
  8720. size: { value: 1.0 },
  8721. scale: { value: 1.0 },
  8722. map: { value: null },
  8723. uvTransform: { value: new Matrix3() }
  8724. }
  8725. };
  8726. /**
  8727. * @author alteredq / http://alteredqualia.com/
  8728. * @author mrdoob / http://mrdoob.com/
  8729. * @author mikael emtinger / http://gomo.se/
  8730. */
  8731. var ShaderLib = {
  8732. basic: {
  8733. uniforms: UniformsUtils.merge( [
  8734. UniformsLib.common,
  8735. UniformsLib.specularmap,
  8736. UniformsLib.envmap,
  8737. UniformsLib.aomap,
  8738. UniformsLib.lightmap,
  8739. UniformsLib.fog
  8740. ] ),
  8741. vertexShader: ShaderChunk.meshbasic_vert,
  8742. fragmentShader: ShaderChunk.meshbasic_frag
  8743. },
  8744. lambert: {
  8745. uniforms: UniformsUtils.merge( [
  8746. UniformsLib.common,
  8747. UniformsLib.specularmap,
  8748. UniformsLib.envmap,
  8749. UniformsLib.aomap,
  8750. UniformsLib.lightmap,
  8751. UniformsLib.emissivemap,
  8752. UniformsLib.fog,
  8753. UniformsLib.lights,
  8754. {
  8755. emissive: { value: new Color( 0x000000 ) }
  8756. }
  8757. ] ),
  8758. vertexShader: ShaderChunk.meshlambert_vert,
  8759. fragmentShader: ShaderChunk.meshlambert_frag
  8760. },
  8761. phong: {
  8762. uniforms: UniformsUtils.merge( [
  8763. UniformsLib.common,
  8764. UniformsLib.specularmap,
  8765. UniformsLib.envmap,
  8766. UniformsLib.aomap,
  8767. UniformsLib.lightmap,
  8768. UniformsLib.emissivemap,
  8769. UniformsLib.bumpmap,
  8770. UniformsLib.normalmap,
  8771. UniformsLib.displacementmap,
  8772. UniformsLib.gradientmap,
  8773. UniformsLib.fog,
  8774. UniformsLib.lights,
  8775. {
  8776. emissive: { value: new Color( 0x000000 ) },
  8777. specular: { value: new Color( 0x111111 ) },
  8778. shininess: { value: 30 }
  8779. }
  8780. ] ),
  8781. vertexShader: ShaderChunk.meshphong_vert,
  8782. fragmentShader: ShaderChunk.meshphong_frag
  8783. },
  8784. standard: {
  8785. uniforms: UniformsUtils.merge( [
  8786. UniformsLib.common,
  8787. UniformsLib.envmap,
  8788. UniformsLib.aomap,
  8789. UniformsLib.lightmap,
  8790. UniformsLib.emissivemap,
  8791. UniformsLib.bumpmap,
  8792. UniformsLib.normalmap,
  8793. UniformsLib.displacementmap,
  8794. UniformsLib.roughnessmap,
  8795. UniformsLib.metalnessmap,
  8796. UniformsLib.fog,
  8797. UniformsLib.lights,
  8798. {
  8799. emissive: { value: new Color( 0x000000 ) },
  8800. roughness: { value: 0.5 },
  8801. metalness: { value: 0.5 },
  8802. envMapIntensity: { value: 1 } // temporary
  8803. }
  8804. ] ),
  8805. vertexShader: ShaderChunk.meshphysical_vert,
  8806. fragmentShader: ShaderChunk.meshphysical_frag
  8807. },
  8808. points: {
  8809. uniforms: UniformsUtils.merge( [
  8810. UniformsLib.points,
  8811. UniformsLib.fog
  8812. ] ),
  8813. vertexShader: ShaderChunk.points_vert,
  8814. fragmentShader: ShaderChunk.points_frag
  8815. },
  8816. dashed: {
  8817. uniforms: UniformsUtils.merge( [
  8818. UniformsLib.common,
  8819. UniformsLib.fog,
  8820. {
  8821. scale: { value: 1 },
  8822. dashSize: { value: 1 },
  8823. totalSize: { value: 2 }
  8824. }
  8825. ] ),
  8826. vertexShader: ShaderChunk.linedashed_vert,
  8827. fragmentShader: ShaderChunk.linedashed_frag
  8828. },
  8829. depth: {
  8830. uniforms: UniformsUtils.merge( [
  8831. UniformsLib.common,
  8832. UniformsLib.displacementmap
  8833. ] ),
  8834. vertexShader: ShaderChunk.depth_vert,
  8835. fragmentShader: ShaderChunk.depth_frag
  8836. },
  8837. normal: {
  8838. uniforms: UniformsUtils.merge( [
  8839. UniformsLib.common,
  8840. UniformsLib.bumpmap,
  8841. UniformsLib.normalmap,
  8842. UniformsLib.displacementmap,
  8843. {
  8844. opacity: { value: 1.0 }
  8845. }
  8846. ] ),
  8847. vertexShader: ShaderChunk.normal_vert,
  8848. fragmentShader: ShaderChunk.normal_frag
  8849. },
  8850. /* -------------------------------------------------------------------------
  8851. // Cube map shader
  8852. ------------------------------------------------------------------------- */
  8853. cube: {
  8854. uniforms: {
  8855. tCube: { value: null },
  8856. tFlip: { value: - 1 },
  8857. opacity: { value: 1.0 }
  8858. },
  8859. vertexShader: ShaderChunk.cube_vert,
  8860. fragmentShader: ShaderChunk.cube_frag
  8861. },
  8862. equirect: {
  8863. uniforms: {
  8864. tEquirect: { value: null },
  8865. },
  8866. vertexShader: ShaderChunk.equirect_vert,
  8867. fragmentShader: ShaderChunk.equirect_frag
  8868. },
  8869. distanceRGBA: {
  8870. uniforms: UniformsUtils.merge( [
  8871. UniformsLib.common,
  8872. UniformsLib.displacementmap,
  8873. {
  8874. referencePosition: { value: new Vector3() },
  8875. nearDistance: { value: 1 },
  8876. farDistance: { value: 1000 }
  8877. }
  8878. ] ),
  8879. vertexShader: ShaderChunk.distanceRGBA_vert,
  8880. fragmentShader: ShaderChunk.distanceRGBA_frag
  8881. },
  8882. shadow: {
  8883. uniforms: UniformsUtils.merge( [
  8884. UniformsLib.lights,
  8885. UniformsLib.fog,
  8886. {
  8887. color: { value: new Color( 0x00000 ) },
  8888. opacity: { value: 1.0 }
  8889. },
  8890. ] ),
  8891. vertexShader: ShaderChunk.shadow_vert,
  8892. fragmentShader: ShaderChunk.shadow_frag
  8893. }
  8894. };
  8895. ShaderLib.physical = {
  8896. uniforms: UniformsUtils.merge( [
  8897. ShaderLib.standard.uniforms,
  8898. {
  8899. clearCoat: { value: 0 },
  8900. clearCoatRoughness: { value: 0 }
  8901. }
  8902. ] ),
  8903. vertexShader: ShaderChunk.meshphysical_vert,
  8904. fragmentShader: ShaderChunk.meshphysical_frag
  8905. };
  8906. /**
  8907. * @author mrdoob / http://mrdoob.com/
  8908. */
  8909. function WebGLAttributes( gl ) {
  8910. var buffers = new WeakMap();
  8911. function createBuffer( attribute, bufferType ) {
  8912. var array = attribute.array;
  8913. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  8914. var buffer = gl.createBuffer();
  8915. gl.bindBuffer( bufferType, buffer );
  8916. gl.bufferData( bufferType, array, usage );
  8917. attribute.onUploadCallback();
  8918. var type = gl.FLOAT;
  8919. if ( array instanceof Float32Array ) {
  8920. type = gl.FLOAT;
  8921. } else if ( array instanceof Float64Array ) {
  8922. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  8923. } else if ( array instanceof Uint16Array ) {
  8924. type = gl.UNSIGNED_SHORT;
  8925. } else if ( array instanceof Int16Array ) {
  8926. type = gl.SHORT;
  8927. } else if ( array instanceof Uint32Array ) {
  8928. type = gl.UNSIGNED_INT;
  8929. } else if ( array instanceof Int32Array ) {
  8930. type = gl.INT;
  8931. } else if ( array instanceof Int8Array ) {
  8932. type = gl.BYTE;
  8933. } else if ( array instanceof Uint8Array ) {
  8934. type = gl.UNSIGNED_BYTE;
  8935. }
  8936. return {
  8937. buffer: buffer,
  8938. type: type,
  8939. bytesPerElement: array.BYTES_PER_ELEMENT,
  8940. version: attribute.version
  8941. };
  8942. }
  8943. function updateBuffer( buffer, attribute, bufferType ) {
  8944. var array = attribute.array;
  8945. var updateRange = attribute.updateRange;
  8946. gl.bindBuffer( bufferType, buffer );
  8947. if ( attribute.dynamic === false ) {
  8948. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  8949. } else if ( updateRange.count === - 1 ) {
  8950. // Not using update ranges
  8951. gl.bufferSubData( bufferType, 0, array );
  8952. } else if ( updateRange.count === 0 ) {
  8953. 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.' );
  8954. } else {
  8955. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8956. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8957. updateRange.count = - 1; // reset range
  8958. }
  8959. }
  8960. //
  8961. function get( attribute ) {
  8962. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8963. return buffers.get( attribute );
  8964. }
  8965. function remove( attribute ) {
  8966. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8967. var data = buffers.get( attribute );
  8968. if ( data ) {
  8969. gl.deleteBuffer( data.buffer );
  8970. buffers.delete( attribute );
  8971. }
  8972. }
  8973. function update( attribute, bufferType ) {
  8974. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8975. var data = buffers.get( attribute );
  8976. if ( data === undefined ) {
  8977. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8978. } else if ( data.version < attribute.version ) {
  8979. updateBuffer( data.buffer, attribute, bufferType );
  8980. data.version = attribute.version;
  8981. }
  8982. }
  8983. return {
  8984. get: get,
  8985. remove: remove,
  8986. update: update
  8987. };
  8988. }
  8989. /**
  8990. * @author mrdoob / http://mrdoob.com/
  8991. * @author WestLangley / http://github.com/WestLangley
  8992. * @author bhouston / http://clara.io
  8993. */
  8994. function Euler( x, y, z, order ) {
  8995. this._x = x || 0;
  8996. this._y = y || 0;
  8997. this._z = z || 0;
  8998. this._order = order || Euler.DefaultOrder;
  8999. }
  9000. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  9001. Euler.DefaultOrder = 'XYZ';
  9002. Object.defineProperties( Euler.prototype, {
  9003. x: {
  9004. get: function () {
  9005. return this._x;
  9006. },
  9007. set: function ( value ) {
  9008. this._x = value;
  9009. this.onChangeCallback();
  9010. }
  9011. },
  9012. y: {
  9013. get: function () {
  9014. return this._y;
  9015. },
  9016. set: function ( value ) {
  9017. this._y = value;
  9018. this.onChangeCallback();
  9019. }
  9020. },
  9021. z: {
  9022. get: function () {
  9023. return this._z;
  9024. },
  9025. set: function ( value ) {
  9026. this._z = value;
  9027. this.onChangeCallback();
  9028. }
  9029. },
  9030. order: {
  9031. get: function () {
  9032. return this._order;
  9033. },
  9034. set: function ( value ) {
  9035. this._order = value;
  9036. this.onChangeCallback();
  9037. }
  9038. }
  9039. } );
  9040. Object.assign( Euler.prototype, {
  9041. isEuler: true,
  9042. set: function ( x, y, z, order ) {
  9043. this._x = x;
  9044. this._y = y;
  9045. this._z = z;
  9046. this._order = order || this._order;
  9047. this.onChangeCallback();
  9048. return this;
  9049. },
  9050. clone: function () {
  9051. return new this.constructor( this._x, this._y, this._z, this._order );
  9052. },
  9053. copy: function ( euler ) {
  9054. this._x = euler._x;
  9055. this._y = euler._y;
  9056. this._z = euler._z;
  9057. this._order = euler._order;
  9058. this.onChangeCallback();
  9059. return this;
  9060. },
  9061. setFromRotationMatrix: function ( m, order, update ) {
  9062. var clamp = _Math.clamp;
  9063. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9064. var te = m.elements;
  9065. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9066. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9067. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9068. order = order || this._order;
  9069. if ( order === 'XYZ' ) {
  9070. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  9071. if ( Math.abs( m13 ) < 0.99999 ) {
  9072. this._x = Math.atan2( - m23, m33 );
  9073. this._z = Math.atan2( - m12, m11 );
  9074. } else {
  9075. this._x = Math.atan2( m32, m22 );
  9076. this._z = 0;
  9077. }
  9078. } else if ( order === 'YXZ' ) {
  9079. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  9080. if ( Math.abs( m23 ) < 0.99999 ) {
  9081. this._y = Math.atan2( m13, m33 );
  9082. this._z = Math.atan2( m21, m22 );
  9083. } else {
  9084. this._y = Math.atan2( - m31, m11 );
  9085. this._z = 0;
  9086. }
  9087. } else if ( order === 'ZXY' ) {
  9088. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  9089. if ( Math.abs( m32 ) < 0.99999 ) {
  9090. this._y = Math.atan2( - m31, m33 );
  9091. this._z = Math.atan2( - m12, m22 );
  9092. } else {
  9093. this._y = 0;
  9094. this._z = Math.atan2( m21, m11 );
  9095. }
  9096. } else if ( order === 'ZYX' ) {
  9097. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  9098. if ( Math.abs( m31 ) < 0.99999 ) {
  9099. this._x = Math.atan2( m32, m33 );
  9100. this._z = Math.atan2( m21, m11 );
  9101. } else {
  9102. this._x = 0;
  9103. this._z = Math.atan2( - m12, m22 );
  9104. }
  9105. } else if ( order === 'YZX' ) {
  9106. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  9107. if ( Math.abs( m21 ) < 0.99999 ) {
  9108. this._x = Math.atan2( - m23, m22 );
  9109. this._y = Math.atan2( - m31, m11 );
  9110. } else {
  9111. this._x = 0;
  9112. this._y = Math.atan2( m13, m33 );
  9113. }
  9114. } else if ( order === 'XZY' ) {
  9115. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  9116. if ( Math.abs( m12 ) < 0.99999 ) {
  9117. this._x = Math.atan2( m32, m22 );
  9118. this._y = Math.atan2( m13, m11 );
  9119. } else {
  9120. this._x = Math.atan2( - m23, m33 );
  9121. this._y = 0;
  9122. }
  9123. } else {
  9124. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  9125. }
  9126. this._order = order;
  9127. if ( update !== false ) this.onChangeCallback();
  9128. return this;
  9129. },
  9130. setFromQuaternion: function () {
  9131. var matrix = new Matrix4();
  9132. return function setFromQuaternion( q, order, update ) {
  9133. matrix.makeRotationFromQuaternion( q );
  9134. return this.setFromRotationMatrix( matrix, order, update );
  9135. };
  9136. }(),
  9137. setFromVector3: function ( v, order ) {
  9138. return this.set( v.x, v.y, v.z, order || this._order );
  9139. },
  9140. reorder: function () {
  9141. // WARNING: this discards revolution information -bhouston
  9142. var q = new Quaternion();
  9143. return function reorder( newOrder ) {
  9144. q.setFromEuler( this );
  9145. return this.setFromQuaternion( q, newOrder );
  9146. };
  9147. }(),
  9148. equals: function ( euler ) {
  9149. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9150. },
  9151. fromArray: function ( array ) {
  9152. this._x = array[ 0 ];
  9153. this._y = array[ 1 ];
  9154. this._z = array[ 2 ];
  9155. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9156. this.onChangeCallback();
  9157. return this;
  9158. },
  9159. toArray: function ( array, offset ) {
  9160. if ( array === undefined ) array = [];
  9161. if ( offset === undefined ) offset = 0;
  9162. array[ offset ] = this._x;
  9163. array[ offset + 1 ] = this._y;
  9164. array[ offset + 2 ] = this._z;
  9165. array[ offset + 3 ] = this._order;
  9166. return array;
  9167. },
  9168. toVector3: function ( optionalResult ) {
  9169. if ( optionalResult ) {
  9170. return optionalResult.set( this._x, this._y, this._z );
  9171. } else {
  9172. return new Vector3( this._x, this._y, this._z );
  9173. }
  9174. },
  9175. onChange: function ( callback ) {
  9176. this.onChangeCallback = callback;
  9177. return this;
  9178. },
  9179. onChangeCallback: function () {}
  9180. } );
  9181. /**
  9182. * @author mrdoob / http://mrdoob.com/
  9183. */
  9184. function Layers() {
  9185. this.mask = 1 | 0;
  9186. }
  9187. Object.assign( Layers.prototype, {
  9188. set: function ( channel ) {
  9189. this.mask = 1 << channel | 0;
  9190. },
  9191. enable: function ( channel ) {
  9192. this.mask |= 1 << channel | 0;
  9193. },
  9194. toggle: function ( channel ) {
  9195. this.mask ^= 1 << channel | 0;
  9196. },
  9197. disable: function ( channel ) {
  9198. this.mask &= ~ ( 1 << channel | 0 );
  9199. },
  9200. test: function ( layers ) {
  9201. return ( this.mask & layers.mask ) !== 0;
  9202. }
  9203. } );
  9204. /**
  9205. * @author mrdoob / http://mrdoob.com/
  9206. * @author mikael emtinger / http://gomo.se/
  9207. * @author alteredq / http://alteredqualia.com/
  9208. * @author WestLangley / http://github.com/WestLangley
  9209. * @author elephantatwork / www.elephantatwork.ch
  9210. */
  9211. var object3DId = 0;
  9212. function Object3D() {
  9213. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  9214. this.uuid = _Math.generateUUID();
  9215. this.name = '';
  9216. this.type = 'Object3D';
  9217. this.parent = null;
  9218. this.children = [];
  9219. this.up = Object3D.DefaultUp.clone();
  9220. var position = new Vector3();
  9221. var rotation = new Euler();
  9222. var quaternion = new Quaternion();
  9223. var scale = new Vector3( 1, 1, 1 );
  9224. function onRotationChange() {
  9225. quaternion.setFromEuler( rotation, false );
  9226. }
  9227. function onQuaternionChange() {
  9228. rotation.setFromQuaternion( quaternion, undefined, false );
  9229. }
  9230. rotation.onChange( onRotationChange );
  9231. quaternion.onChange( onQuaternionChange );
  9232. Object.defineProperties( this, {
  9233. position: {
  9234. enumerable: true,
  9235. value: position
  9236. },
  9237. rotation: {
  9238. enumerable: true,
  9239. value: rotation
  9240. },
  9241. quaternion: {
  9242. enumerable: true,
  9243. value: quaternion
  9244. },
  9245. scale: {
  9246. enumerable: true,
  9247. value: scale
  9248. },
  9249. modelViewMatrix: {
  9250. value: new Matrix4()
  9251. },
  9252. normalMatrix: {
  9253. value: new Matrix3()
  9254. }
  9255. } );
  9256. this.matrix = new Matrix4();
  9257. this.matrixWorld = new Matrix4();
  9258. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  9259. this.matrixWorldNeedsUpdate = false;
  9260. this.layers = new Layers();
  9261. this.visible = true;
  9262. this.castShadow = false;
  9263. this.receiveShadow = false;
  9264. this.frustumCulled = true;
  9265. this.renderOrder = 0;
  9266. this.userData = {};
  9267. }
  9268. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  9269. Object3D.DefaultMatrixAutoUpdate = true;
  9270. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  9271. constructor: Object3D,
  9272. isObject3D: true,
  9273. onBeforeRender: function () {},
  9274. onAfterRender: function () {},
  9275. applyMatrix: function ( matrix ) {
  9276. this.matrix.multiplyMatrices( matrix, this.matrix );
  9277. this.matrix.decompose( this.position, this.quaternion, this.scale );
  9278. },
  9279. applyQuaternion: function ( q ) {
  9280. this.quaternion.premultiply( q );
  9281. return this;
  9282. },
  9283. setRotationFromAxisAngle: function ( axis, angle ) {
  9284. // assumes axis is normalized
  9285. this.quaternion.setFromAxisAngle( axis, angle );
  9286. },
  9287. setRotationFromEuler: function ( euler ) {
  9288. this.quaternion.setFromEuler( euler, true );
  9289. },
  9290. setRotationFromMatrix: function ( m ) {
  9291. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9292. this.quaternion.setFromRotationMatrix( m );
  9293. },
  9294. setRotationFromQuaternion: function ( q ) {
  9295. // assumes q is normalized
  9296. this.quaternion.copy( q );
  9297. },
  9298. rotateOnAxis: function () {
  9299. // rotate object on axis in object space
  9300. // axis is assumed to be normalized
  9301. var q1 = new Quaternion();
  9302. return function rotateOnAxis( axis, angle ) {
  9303. q1.setFromAxisAngle( axis, angle );
  9304. this.quaternion.multiply( q1 );
  9305. return this;
  9306. };
  9307. }(),
  9308. rotateOnWorldAxis: function () {
  9309. // rotate object on axis in world space
  9310. // axis is assumed to be normalized
  9311. // method assumes no rotated parent
  9312. var q1 = new Quaternion();
  9313. return function rotateOnWorldAxis( axis, angle ) {
  9314. q1.setFromAxisAngle( axis, angle );
  9315. this.quaternion.premultiply( q1 );
  9316. return this;
  9317. };
  9318. }(),
  9319. rotateX: function () {
  9320. var v1 = new Vector3( 1, 0, 0 );
  9321. return function rotateX( angle ) {
  9322. return this.rotateOnAxis( v1, angle );
  9323. };
  9324. }(),
  9325. rotateY: function () {
  9326. var v1 = new Vector3( 0, 1, 0 );
  9327. return function rotateY( angle ) {
  9328. return this.rotateOnAxis( v1, angle );
  9329. };
  9330. }(),
  9331. rotateZ: function () {
  9332. var v1 = new Vector3( 0, 0, 1 );
  9333. return function rotateZ( angle ) {
  9334. return this.rotateOnAxis( v1, angle );
  9335. };
  9336. }(),
  9337. translateOnAxis: function () {
  9338. // translate object by distance along axis in object space
  9339. // axis is assumed to be normalized
  9340. var v1 = new Vector3();
  9341. return function translateOnAxis( axis, distance ) {
  9342. v1.copy( axis ).applyQuaternion( this.quaternion );
  9343. this.position.add( v1.multiplyScalar( distance ) );
  9344. return this;
  9345. };
  9346. }(),
  9347. translateX: function () {
  9348. var v1 = new Vector3( 1, 0, 0 );
  9349. return function translateX( distance ) {
  9350. return this.translateOnAxis( v1, distance );
  9351. };
  9352. }(),
  9353. translateY: function () {
  9354. var v1 = new Vector3( 0, 1, 0 );
  9355. return function translateY( distance ) {
  9356. return this.translateOnAxis( v1, distance );
  9357. };
  9358. }(),
  9359. translateZ: function () {
  9360. var v1 = new Vector3( 0, 0, 1 );
  9361. return function translateZ( distance ) {
  9362. return this.translateOnAxis( v1, distance );
  9363. };
  9364. }(),
  9365. localToWorld: function ( vector ) {
  9366. return vector.applyMatrix4( this.matrixWorld );
  9367. },
  9368. worldToLocal: function () {
  9369. var m1 = new Matrix4();
  9370. return function worldToLocal( vector ) {
  9371. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  9372. };
  9373. }(),
  9374. lookAt: function () {
  9375. // This method does not support objects with rotated and/or translated parent(s)
  9376. var m1 = new Matrix4();
  9377. var vector = new Vector3();
  9378. return function lookAt( x, y, z ) {
  9379. if ( x.isVector3 ) {
  9380. vector.copy( x );
  9381. } else {
  9382. vector.set( x, y, z );
  9383. }
  9384. if ( this.isCamera ) {
  9385. m1.lookAt( this.position, vector, this.up );
  9386. } else {
  9387. m1.lookAt( vector, this.position, this.up );
  9388. }
  9389. this.quaternion.setFromRotationMatrix( m1 );
  9390. };
  9391. }(),
  9392. add: function ( object ) {
  9393. if ( arguments.length > 1 ) {
  9394. for ( var i = 0; i < arguments.length; i ++ ) {
  9395. this.add( arguments[ i ] );
  9396. }
  9397. return this;
  9398. }
  9399. if ( object === this ) {
  9400. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  9401. return this;
  9402. }
  9403. if ( ( object && object.isObject3D ) ) {
  9404. if ( object.parent !== null ) {
  9405. object.parent.remove( object );
  9406. }
  9407. object.parent = this;
  9408. object.dispatchEvent( { type: 'added' } );
  9409. this.children.push( object );
  9410. } else {
  9411. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  9412. }
  9413. return this;
  9414. },
  9415. remove: function ( object ) {
  9416. if ( arguments.length > 1 ) {
  9417. for ( var i = 0; i < arguments.length; i ++ ) {
  9418. this.remove( arguments[ i ] );
  9419. }
  9420. return this;
  9421. }
  9422. var index = this.children.indexOf( object );
  9423. if ( index !== - 1 ) {
  9424. object.parent = null;
  9425. object.dispatchEvent( { type: 'removed' } );
  9426. this.children.splice( index, 1 );
  9427. }
  9428. return this;
  9429. },
  9430. getObjectById: function ( id ) {
  9431. return this.getObjectByProperty( 'id', id );
  9432. },
  9433. getObjectByName: function ( name ) {
  9434. return this.getObjectByProperty( 'name', name );
  9435. },
  9436. getObjectByProperty: function ( name, value ) {
  9437. if ( this[ name ] === value ) return this;
  9438. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9439. var child = this.children[ i ];
  9440. var object = child.getObjectByProperty( name, value );
  9441. if ( object !== undefined ) {
  9442. return object;
  9443. }
  9444. }
  9445. return undefined;
  9446. },
  9447. getWorldPosition: function ( target ) {
  9448. if ( target === undefined ) {
  9449. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  9450. target = new Vector3();
  9451. }
  9452. this.updateMatrixWorld( true );
  9453. return target.setFromMatrixPosition( this.matrixWorld );
  9454. },
  9455. getWorldQuaternion: function () {
  9456. var position = new Vector3();
  9457. var scale = new Vector3();
  9458. return function getWorldQuaternion( target ) {
  9459. if ( target === undefined ) {
  9460. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  9461. target = new Quaternion();
  9462. }
  9463. this.updateMatrixWorld( true );
  9464. this.matrixWorld.decompose( position, target, scale );
  9465. return target;
  9466. };
  9467. }(),
  9468. getWorldScale: function () {
  9469. var position = new Vector3();
  9470. var quaternion = new Quaternion();
  9471. return function getWorldScale( target ) {
  9472. if ( target === undefined ) {
  9473. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  9474. target = new Vector3();
  9475. }
  9476. this.updateMatrixWorld( true );
  9477. this.matrixWorld.decompose( position, quaternion, target );
  9478. return target;
  9479. };
  9480. }(),
  9481. getWorldDirection: function () {
  9482. var quaternion = new Quaternion();
  9483. return function getWorldDirection( target ) {
  9484. if ( target === undefined ) {
  9485. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  9486. target = new Vector3();
  9487. }
  9488. this.getWorldQuaternion( quaternion );
  9489. return target.set( 0, 0, 1 ).applyQuaternion( quaternion );
  9490. };
  9491. }(),
  9492. raycast: function () {},
  9493. traverse: function ( callback ) {
  9494. callback( this );
  9495. var children = this.children;
  9496. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9497. children[ i ].traverse( callback );
  9498. }
  9499. },
  9500. traverseVisible: function ( callback ) {
  9501. if ( this.visible === false ) return;
  9502. callback( this );
  9503. var children = this.children;
  9504. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9505. children[ i ].traverseVisible( callback );
  9506. }
  9507. },
  9508. traverseAncestors: function ( callback ) {
  9509. var parent = this.parent;
  9510. if ( parent !== null ) {
  9511. callback( parent );
  9512. parent.traverseAncestors( callback );
  9513. }
  9514. },
  9515. updateMatrix: function () {
  9516. this.matrix.compose( this.position, this.quaternion, this.scale );
  9517. this.matrixWorldNeedsUpdate = true;
  9518. },
  9519. updateMatrixWorld: function ( force ) {
  9520. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9521. if ( this.matrixWorldNeedsUpdate || force ) {
  9522. if ( this.parent === null ) {
  9523. this.matrixWorld.copy( this.matrix );
  9524. } else {
  9525. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9526. }
  9527. this.matrixWorldNeedsUpdate = false;
  9528. force = true;
  9529. }
  9530. // update children
  9531. var children = this.children;
  9532. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9533. children[ i ].updateMatrixWorld( force );
  9534. }
  9535. },
  9536. toJSON: function ( meta ) {
  9537. // meta is a string when called from JSON.stringify
  9538. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  9539. var output = {};
  9540. // meta is a hash used to collect geometries, materials.
  9541. // not providing it implies that this is the root object
  9542. // being serialized.
  9543. if ( isRootObject ) {
  9544. // initialize meta obj
  9545. meta = {
  9546. geometries: {},
  9547. materials: {},
  9548. textures: {},
  9549. images: {},
  9550. shapes: {}
  9551. };
  9552. output.metadata = {
  9553. version: 4.5,
  9554. type: 'Object',
  9555. generator: 'Object3D.toJSON'
  9556. };
  9557. }
  9558. // standard Object3D serialization
  9559. var object = {};
  9560. object.uuid = this.uuid;
  9561. object.type = this.type;
  9562. if ( this.name !== '' ) object.name = this.name;
  9563. if ( this.castShadow === true ) object.castShadow = true;
  9564. if ( this.receiveShadow === true ) object.receiveShadow = true;
  9565. if ( this.visible === false ) object.visible = false;
  9566. if ( this.frustumCulled === false ) object.frustumCulled = false;
  9567. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  9568. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  9569. object.matrix = this.matrix.toArray();
  9570. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  9571. //
  9572. function serialize( library, element ) {
  9573. if ( library[ element.uuid ] === undefined ) {
  9574. library[ element.uuid ] = element.toJSON( meta );
  9575. }
  9576. return element.uuid;
  9577. }
  9578. if ( this.geometry !== undefined ) {
  9579. object.geometry = serialize( meta.geometries, this.geometry );
  9580. var parameters = this.geometry.parameters;
  9581. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  9582. var shapes = parameters.shapes;
  9583. if ( Array.isArray( shapes ) ) {
  9584. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  9585. var shape = shapes[ i ];
  9586. serialize( meta.shapes, shape );
  9587. }
  9588. } else {
  9589. serialize( meta.shapes, shapes );
  9590. }
  9591. }
  9592. }
  9593. if ( this.material !== undefined ) {
  9594. if ( Array.isArray( this.material ) ) {
  9595. var uuids = [];
  9596. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  9597. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  9598. }
  9599. object.material = uuids;
  9600. } else {
  9601. object.material = serialize( meta.materials, this.material );
  9602. }
  9603. }
  9604. //
  9605. if ( this.children.length > 0 ) {
  9606. object.children = [];
  9607. for ( var i = 0; i < this.children.length; i ++ ) {
  9608. object.children.push( this.children[ i ].toJSON( meta ).object );
  9609. }
  9610. }
  9611. if ( isRootObject ) {
  9612. var geometries = extractFromCache( meta.geometries );
  9613. var materials = extractFromCache( meta.materials );
  9614. var textures = extractFromCache( meta.textures );
  9615. var images = extractFromCache( meta.images );
  9616. var shapes = extractFromCache( meta.shapes );
  9617. if ( geometries.length > 0 ) output.geometries = geometries;
  9618. if ( materials.length > 0 ) output.materials = materials;
  9619. if ( textures.length > 0 ) output.textures = textures;
  9620. if ( images.length > 0 ) output.images = images;
  9621. if ( shapes.length > 0 ) output.shapes = shapes;
  9622. }
  9623. output.object = object;
  9624. return output;
  9625. // extract data from the cache hash
  9626. // remove metadata on each item
  9627. // and return as array
  9628. function extractFromCache( cache ) {
  9629. var values = [];
  9630. for ( var key in cache ) {
  9631. var data = cache[ key ];
  9632. delete data.metadata;
  9633. values.push( data );
  9634. }
  9635. return values;
  9636. }
  9637. },
  9638. clone: function ( recursive ) {
  9639. return new this.constructor().copy( this, recursive );
  9640. },
  9641. copy: function ( source, recursive ) {
  9642. if ( recursive === undefined ) recursive = true;
  9643. this.name = source.name;
  9644. this.up.copy( source.up );
  9645. this.position.copy( source.position );
  9646. this.quaternion.copy( source.quaternion );
  9647. this.scale.copy( source.scale );
  9648. this.matrix.copy( source.matrix );
  9649. this.matrixWorld.copy( source.matrixWorld );
  9650. this.matrixAutoUpdate = source.matrixAutoUpdate;
  9651. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  9652. this.layers.mask = source.layers.mask;
  9653. this.visible = source.visible;
  9654. this.castShadow = source.castShadow;
  9655. this.receiveShadow = source.receiveShadow;
  9656. this.frustumCulled = source.frustumCulled;
  9657. this.renderOrder = source.renderOrder;
  9658. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  9659. if ( recursive === true ) {
  9660. for ( var i = 0; i < source.children.length; i ++ ) {
  9661. var child = source.children[ i ];
  9662. this.add( child.clone() );
  9663. }
  9664. }
  9665. return this;
  9666. }
  9667. } );
  9668. /**
  9669. * @author mrdoob / http://mrdoob.com/
  9670. * @author mikael emtinger / http://gomo.se/
  9671. * @author WestLangley / http://github.com/WestLangley
  9672. */
  9673. function Camera() {
  9674. Object3D.call( this );
  9675. this.type = 'Camera';
  9676. this.matrixWorldInverse = new Matrix4();
  9677. this.projectionMatrix = new Matrix4();
  9678. }
  9679. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9680. constructor: Camera,
  9681. isCamera: true,
  9682. copy: function ( source, recursive ) {
  9683. Object3D.prototype.copy.call( this, source, recursive );
  9684. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9685. this.projectionMatrix.copy( source.projectionMatrix );
  9686. return this;
  9687. },
  9688. getWorldDirection: function () {
  9689. var quaternion = new Quaternion();
  9690. return function getWorldDirection( target ) {
  9691. if ( target === undefined ) {
  9692. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  9693. target = new Vector3();
  9694. }
  9695. this.getWorldQuaternion( quaternion );
  9696. return target.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9697. };
  9698. }(),
  9699. updateMatrixWorld: function ( force ) {
  9700. Object3D.prototype.updateMatrixWorld.call( this, force );
  9701. this.matrixWorldInverse.getInverse( this.matrixWorld );
  9702. },
  9703. clone: function () {
  9704. return new this.constructor().copy( this );
  9705. }
  9706. } );
  9707. /**
  9708. * @author alteredq / http://alteredqualia.com/
  9709. * @author arose / http://github.com/arose
  9710. */
  9711. function OrthographicCamera( left, right, top, bottom, near, far ) {
  9712. Camera.call( this );
  9713. this.type = 'OrthographicCamera';
  9714. this.zoom = 1;
  9715. this.view = null;
  9716. this.left = left;
  9717. this.right = right;
  9718. this.top = top;
  9719. this.bottom = bottom;
  9720. this.near = ( near !== undefined ) ? near : 0.1;
  9721. this.far = ( far !== undefined ) ? far : 2000;
  9722. this.updateProjectionMatrix();
  9723. }
  9724. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9725. constructor: OrthographicCamera,
  9726. isOrthographicCamera: true,
  9727. copy: function ( source, recursive ) {
  9728. Camera.prototype.copy.call( this, source, recursive );
  9729. this.left = source.left;
  9730. this.right = source.right;
  9731. this.top = source.top;
  9732. this.bottom = source.bottom;
  9733. this.near = source.near;
  9734. this.far = source.far;
  9735. this.zoom = source.zoom;
  9736. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9737. return this;
  9738. },
  9739. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  9740. if ( this.view === null ) {
  9741. this.view = {
  9742. enabled: true,
  9743. fullWidth: 1,
  9744. fullHeight: 1,
  9745. offsetX: 0,
  9746. offsetY: 0,
  9747. width: 1,
  9748. height: 1
  9749. };
  9750. }
  9751. this.view.enabled = true;
  9752. this.view.fullWidth = fullWidth;
  9753. this.view.fullHeight = fullHeight;
  9754. this.view.offsetX = x;
  9755. this.view.offsetY = y;
  9756. this.view.width = width;
  9757. this.view.height = height;
  9758. this.updateProjectionMatrix();
  9759. },
  9760. clearViewOffset: function () {
  9761. if ( this.view !== null ) {
  9762. this.view.enabled = false;
  9763. }
  9764. this.updateProjectionMatrix();
  9765. },
  9766. updateProjectionMatrix: function () {
  9767. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9768. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9769. var cx = ( this.right + this.left ) / 2;
  9770. var cy = ( this.top + this.bottom ) / 2;
  9771. var left = cx - dx;
  9772. var right = cx + dx;
  9773. var top = cy + dy;
  9774. var bottom = cy - dy;
  9775. if ( this.view !== null && this.view.enabled ) {
  9776. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  9777. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  9778. var scaleW = ( this.right - this.left ) / this.view.width;
  9779. var scaleH = ( this.top - this.bottom ) / this.view.height;
  9780. left += scaleW * ( this.view.offsetX / zoomW );
  9781. right = left + scaleW * ( this.view.width / zoomW );
  9782. top -= scaleH * ( this.view.offsetY / zoomH );
  9783. bottom = top - scaleH * ( this.view.height / zoomH );
  9784. }
  9785. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9786. },
  9787. toJSON: function ( meta ) {
  9788. var data = Object3D.prototype.toJSON.call( this, meta );
  9789. data.object.zoom = this.zoom;
  9790. data.object.left = this.left;
  9791. data.object.right = this.right;
  9792. data.object.top = this.top;
  9793. data.object.bottom = this.bottom;
  9794. data.object.near = this.near;
  9795. data.object.far = this.far;
  9796. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9797. return data;
  9798. }
  9799. } );
  9800. /**
  9801. * @author mrdoob / http://mrdoob.com/
  9802. * @author alteredq / http://alteredqualia.com/
  9803. */
  9804. function Face3( a, b, c, normal, color, materialIndex ) {
  9805. this.a = a;
  9806. this.b = b;
  9807. this.c = c;
  9808. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  9809. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  9810. this.color = ( color && color.isColor ) ? color : new Color();
  9811. this.vertexColors = Array.isArray( color ) ? color : [];
  9812. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  9813. }
  9814. Object.assign( Face3.prototype, {
  9815. clone: function () {
  9816. return new this.constructor().copy( this );
  9817. },
  9818. copy: function ( source ) {
  9819. this.a = source.a;
  9820. this.b = source.b;
  9821. this.c = source.c;
  9822. this.normal.copy( source.normal );
  9823. this.color.copy( source.color );
  9824. this.materialIndex = source.materialIndex;
  9825. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  9826. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  9827. }
  9828. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  9829. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  9830. }
  9831. return this;
  9832. }
  9833. } );
  9834. /**
  9835. * @author mrdoob / http://mrdoob.com/
  9836. * @author kile / http://kile.stravaganza.org/
  9837. * @author alteredq / http://alteredqualia.com/
  9838. * @author mikael emtinger / http://gomo.se/
  9839. * @author zz85 / http://www.lab4games.net/zz85/blog
  9840. * @author bhouston / http://clara.io
  9841. */
  9842. var geometryId = 0; // Geometry uses even numbers as Id
  9843. function Geometry() {
  9844. Object.defineProperty( this, 'id', { value: geometryId += 2 } );
  9845. this.uuid = _Math.generateUUID();
  9846. this.name = '';
  9847. this.type = 'Geometry';
  9848. this.vertices = [];
  9849. this.colors = [];
  9850. this.faces = [];
  9851. this.faceVertexUvs = [[]];
  9852. this.morphTargets = [];
  9853. this.morphNormals = [];
  9854. this.skinWeights = [];
  9855. this.skinIndices = [];
  9856. this.lineDistances = [];
  9857. this.boundingBox = null;
  9858. this.boundingSphere = null;
  9859. // update flags
  9860. this.elementsNeedUpdate = false;
  9861. this.verticesNeedUpdate = false;
  9862. this.uvsNeedUpdate = false;
  9863. this.normalsNeedUpdate = false;
  9864. this.colorsNeedUpdate = false;
  9865. this.lineDistancesNeedUpdate = false;
  9866. this.groupsNeedUpdate = false;
  9867. }
  9868. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  9869. constructor: Geometry,
  9870. isGeometry: true,
  9871. applyMatrix: function ( matrix ) {
  9872. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  9873. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  9874. var vertex = this.vertices[ i ];
  9875. vertex.applyMatrix4( matrix );
  9876. }
  9877. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  9878. var face = this.faces[ i ];
  9879. face.normal.applyMatrix3( normalMatrix ).normalize();
  9880. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  9881. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  9882. }
  9883. }
  9884. if ( this.boundingBox !== null ) {
  9885. this.computeBoundingBox();
  9886. }
  9887. if ( this.boundingSphere !== null ) {
  9888. this.computeBoundingSphere();
  9889. }
  9890. this.verticesNeedUpdate = true;
  9891. this.normalsNeedUpdate = true;
  9892. return this;
  9893. },
  9894. rotateX: function () {
  9895. // rotate geometry around world x-axis
  9896. var m1 = new Matrix4();
  9897. return function rotateX( angle ) {
  9898. m1.makeRotationX( angle );
  9899. this.applyMatrix( m1 );
  9900. return this;
  9901. };
  9902. }(),
  9903. rotateY: function () {
  9904. // rotate geometry around world y-axis
  9905. var m1 = new Matrix4();
  9906. return function rotateY( angle ) {
  9907. m1.makeRotationY( angle );
  9908. this.applyMatrix( m1 );
  9909. return this;
  9910. };
  9911. }(),
  9912. rotateZ: function () {
  9913. // rotate geometry around world z-axis
  9914. var m1 = new Matrix4();
  9915. return function rotateZ( angle ) {
  9916. m1.makeRotationZ( angle );
  9917. this.applyMatrix( m1 );
  9918. return this;
  9919. };
  9920. }(),
  9921. translate: function () {
  9922. // translate geometry
  9923. var m1 = new Matrix4();
  9924. return function translate( x, y, z ) {
  9925. m1.makeTranslation( x, y, z );
  9926. this.applyMatrix( m1 );
  9927. return this;
  9928. };
  9929. }(),
  9930. scale: function () {
  9931. // scale geometry
  9932. var m1 = new Matrix4();
  9933. return function scale( x, y, z ) {
  9934. m1.makeScale( x, y, z );
  9935. this.applyMatrix( m1 );
  9936. return this;
  9937. };
  9938. }(),
  9939. lookAt: function () {
  9940. var obj = new Object3D();
  9941. return function lookAt( vector ) {
  9942. obj.lookAt( vector );
  9943. obj.updateMatrix();
  9944. this.applyMatrix( obj.matrix );
  9945. };
  9946. }(),
  9947. fromBufferGeometry: function ( geometry ) {
  9948. var scope = this;
  9949. var indices = geometry.index !== null ? geometry.index.array : undefined;
  9950. var attributes = geometry.attributes;
  9951. var positions = attributes.position.array;
  9952. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  9953. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  9954. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  9955. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  9956. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  9957. var tempNormals = [];
  9958. var tempUVs = [];
  9959. var tempUVs2 = [];
  9960. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  9961. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  9962. if ( normals !== undefined ) {
  9963. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  9964. }
  9965. if ( colors !== undefined ) {
  9966. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  9967. }
  9968. if ( uvs !== undefined ) {
  9969. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  9970. }
  9971. if ( uvs2 !== undefined ) {
  9972. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  9973. }
  9974. }
  9975. function addFace( a, b, c, materialIndex ) {
  9976. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  9977. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  9978. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  9979. scope.faces.push( face );
  9980. if ( uvs !== undefined ) {
  9981. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  9982. }
  9983. if ( uvs2 !== undefined ) {
  9984. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  9985. }
  9986. }
  9987. var groups = geometry.groups;
  9988. if ( groups.length > 0 ) {
  9989. for ( var i = 0; i < groups.length; i ++ ) {
  9990. var group = groups[ i ];
  9991. var start = group.start;
  9992. var count = group.count;
  9993. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  9994. if ( indices !== undefined ) {
  9995. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  9996. } else {
  9997. addFace( j, j + 1, j + 2, group.materialIndex );
  9998. }
  9999. }
  10000. }
  10001. } else {
  10002. if ( indices !== undefined ) {
  10003. for ( var i = 0; i < indices.length; i += 3 ) {
  10004. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  10005. }
  10006. } else {
  10007. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  10008. addFace( i, i + 1, i + 2 );
  10009. }
  10010. }
  10011. }
  10012. this.computeFaceNormals();
  10013. if ( geometry.boundingBox !== null ) {
  10014. this.boundingBox = geometry.boundingBox.clone();
  10015. }
  10016. if ( geometry.boundingSphere !== null ) {
  10017. this.boundingSphere = geometry.boundingSphere.clone();
  10018. }
  10019. return this;
  10020. },
  10021. center: function () {
  10022. var offset = new Vector3();
  10023. return function center() {
  10024. this.computeBoundingBox();
  10025. this.boundingBox.getCenter( offset ).negate();
  10026. this.translate( offset.x, offset.y, offset.z );
  10027. return this;
  10028. };
  10029. }(),
  10030. normalize: function () {
  10031. this.computeBoundingSphere();
  10032. var center = this.boundingSphere.center;
  10033. var radius = this.boundingSphere.radius;
  10034. var s = radius === 0 ? 1 : 1.0 / radius;
  10035. var matrix = new Matrix4();
  10036. matrix.set(
  10037. s, 0, 0, - s * center.x,
  10038. 0, s, 0, - s * center.y,
  10039. 0, 0, s, - s * center.z,
  10040. 0, 0, 0, 1
  10041. );
  10042. this.applyMatrix( matrix );
  10043. return this;
  10044. },
  10045. computeFaceNormals: function () {
  10046. var cb = new Vector3(), ab = new Vector3();
  10047. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10048. var face = this.faces[ f ];
  10049. var vA = this.vertices[ face.a ];
  10050. var vB = this.vertices[ face.b ];
  10051. var vC = this.vertices[ face.c ];
  10052. cb.subVectors( vC, vB );
  10053. ab.subVectors( vA, vB );
  10054. cb.cross( ab );
  10055. cb.normalize();
  10056. face.normal.copy( cb );
  10057. }
  10058. },
  10059. computeVertexNormals: function ( areaWeighted ) {
  10060. if ( areaWeighted === undefined ) areaWeighted = true;
  10061. var v, vl, f, fl, face, vertices;
  10062. vertices = new Array( this.vertices.length );
  10063. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  10064. vertices[ v ] = new Vector3();
  10065. }
  10066. if ( areaWeighted ) {
  10067. // vertex normals weighted by triangle areas
  10068. // http://www.iquilezles.org/www/articles/normals/normals.htm
  10069. var vA, vB, vC;
  10070. var cb = new Vector3(), ab = new Vector3();
  10071. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10072. face = this.faces[ f ];
  10073. vA = this.vertices[ face.a ];
  10074. vB = this.vertices[ face.b ];
  10075. vC = this.vertices[ face.c ];
  10076. cb.subVectors( vC, vB );
  10077. ab.subVectors( vA, vB );
  10078. cb.cross( ab );
  10079. vertices[ face.a ].add( cb );
  10080. vertices[ face.b ].add( cb );
  10081. vertices[ face.c ].add( cb );
  10082. }
  10083. } else {
  10084. this.computeFaceNormals();
  10085. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10086. face = this.faces[ f ];
  10087. vertices[ face.a ].add( face.normal );
  10088. vertices[ face.b ].add( face.normal );
  10089. vertices[ face.c ].add( face.normal );
  10090. }
  10091. }
  10092. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  10093. vertices[ v ].normalize();
  10094. }
  10095. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10096. face = this.faces[ f ];
  10097. var vertexNormals = face.vertexNormals;
  10098. if ( vertexNormals.length === 3 ) {
  10099. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  10100. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  10101. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  10102. } else {
  10103. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  10104. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  10105. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  10106. }
  10107. }
  10108. if ( this.faces.length > 0 ) {
  10109. this.normalsNeedUpdate = true;
  10110. }
  10111. },
  10112. computeFlatVertexNormals: function () {
  10113. var f, fl, face;
  10114. this.computeFaceNormals();
  10115. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10116. face = this.faces[ f ];
  10117. var vertexNormals = face.vertexNormals;
  10118. if ( vertexNormals.length === 3 ) {
  10119. vertexNormals[ 0 ].copy( face.normal );
  10120. vertexNormals[ 1 ].copy( face.normal );
  10121. vertexNormals[ 2 ].copy( face.normal );
  10122. } else {
  10123. vertexNormals[ 0 ] = face.normal.clone();
  10124. vertexNormals[ 1 ] = face.normal.clone();
  10125. vertexNormals[ 2 ] = face.normal.clone();
  10126. }
  10127. }
  10128. if ( this.faces.length > 0 ) {
  10129. this.normalsNeedUpdate = true;
  10130. }
  10131. },
  10132. computeMorphNormals: function () {
  10133. var i, il, f, fl, face;
  10134. // save original normals
  10135. // - create temp variables on first access
  10136. // otherwise just copy (for faster repeated calls)
  10137. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10138. face = this.faces[ f ];
  10139. if ( ! face.__originalFaceNormal ) {
  10140. face.__originalFaceNormal = face.normal.clone();
  10141. } else {
  10142. face.__originalFaceNormal.copy( face.normal );
  10143. }
  10144. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  10145. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  10146. if ( ! face.__originalVertexNormals[ i ] ) {
  10147. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  10148. } else {
  10149. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  10150. }
  10151. }
  10152. }
  10153. // use temp geometry to compute face and vertex normals for each morph
  10154. var tmpGeo = new Geometry();
  10155. tmpGeo.faces = this.faces;
  10156. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  10157. // create on first access
  10158. if ( ! this.morphNormals[ i ] ) {
  10159. this.morphNormals[ i ] = {};
  10160. this.morphNormals[ i ].faceNormals = [];
  10161. this.morphNormals[ i ].vertexNormals = [];
  10162. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  10163. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  10164. var faceNormal, vertexNormals;
  10165. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10166. faceNormal = new Vector3();
  10167. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  10168. dstNormalsFace.push( faceNormal );
  10169. dstNormalsVertex.push( vertexNormals );
  10170. }
  10171. }
  10172. var morphNormals = this.morphNormals[ i ];
  10173. // set vertices to morph target
  10174. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  10175. // compute morph normals
  10176. tmpGeo.computeFaceNormals();
  10177. tmpGeo.computeVertexNormals();
  10178. // store morph normals
  10179. var faceNormal, vertexNormals;
  10180. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10181. face = this.faces[ f ];
  10182. faceNormal = morphNormals.faceNormals[ f ];
  10183. vertexNormals = morphNormals.vertexNormals[ f ];
  10184. faceNormal.copy( face.normal );
  10185. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  10186. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  10187. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  10188. }
  10189. }
  10190. // restore original normals
  10191. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10192. face = this.faces[ f ];
  10193. face.normal = face.__originalFaceNormal;
  10194. face.vertexNormals = face.__originalVertexNormals;
  10195. }
  10196. },
  10197. computeBoundingBox: function () {
  10198. if ( this.boundingBox === null ) {
  10199. this.boundingBox = new Box3();
  10200. }
  10201. this.boundingBox.setFromPoints( this.vertices );
  10202. },
  10203. computeBoundingSphere: function () {
  10204. if ( this.boundingSphere === null ) {
  10205. this.boundingSphere = new Sphere();
  10206. }
  10207. this.boundingSphere.setFromPoints( this.vertices );
  10208. },
  10209. merge: function ( geometry, matrix, materialIndexOffset ) {
  10210. if ( ! ( geometry && geometry.isGeometry ) ) {
  10211. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  10212. return;
  10213. }
  10214. var normalMatrix,
  10215. vertexOffset = this.vertices.length,
  10216. vertices1 = this.vertices,
  10217. vertices2 = geometry.vertices,
  10218. faces1 = this.faces,
  10219. faces2 = geometry.faces,
  10220. uvs1 = this.faceVertexUvs[ 0 ],
  10221. uvs2 = geometry.faceVertexUvs[ 0 ],
  10222. colors1 = this.colors,
  10223. colors2 = geometry.colors;
  10224. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  10225. if ( matrix !== undefined ) {
  10226. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  10227. }
  10228. // vertices
  10229. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  10230. var vertex = vertices2[ i ];
  10231. var vertexCopy = vertex.clone();
  10232. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  10233. vertices1.push( vertexCopy );
  10234. }
  10235. // colors
  10236. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  10237. colors1.push( colors2[ i ].clone() );
  10238. }
  10239. // faces
  10240. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  10241. var face = faces2[ i ], faceCopy, normal, color,
  10242. faceVertexNormals = face.vertexNormals,
  10243. faceVertexColors = face.vertexColors;
  10244. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  10245. faceCopy.normal.copy( face.normal );
  10246. if ( normalMatrix !== undefined ) {
  10247. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  10248. }
  10249. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  10250. normal = faceVertexNormals[ j ].clone();
  10251. if ( normalMatrix !== undefined ) {
  10252. normal.applyMatrix3( normalMatrix ).normalize();
  10253. }
  10254. faceCopy.vertexNormals.push( normal );
  10255. }
  10256. faceCopy.color.copy( face.color );
  10257. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  10258. color = faceVertexColors[ j ];
  10259. faceCopy.vertexColors.push( color.clone() );
  10260. }
  10261. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  10262. faces1.push( faceCopy );
  10263. }
  10264. // uvs
  10265. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  10266. var uv = uvs2[ i ], uvCopy = [];
  10267. if ( uv === undefined ) {
  10268. continue;
  10269. }
  10270. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  10271. uvCopy.push( uv[ j ].clone() );
  10272. }
  10273. uvs1.push( uvCopy );
  10274. }
  10275. },
  10276. mergeMesh: function ( mesh ) {
  10277. if ( ! ( mesh && mesh.isMesh ) ) {
  10278. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  10279. return;
  10280. }
  10281. if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();
  10282. this.merge( mesh.geometry, mesh.matrix );
  10283. },
  10284. /*
  10285. * Checks for duplicate vertices with hashmap.
  10286. * Duplicated vertices are removed
  10287. * and faces' vertices are updated.
  10288. */
  10289. mergeVertices: function () {
  10290. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  10291. var unique = [], changes = [];
  10292. var v, key;
  10293. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  10294. var precision = Math.pow( 10, precisionPoints );
  10295. var i, il, face;
  10296. var indices, j, jl;
  10297. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  10298. v = this.vertices[ i ];
  10299. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  10300. if ( verticesMap[ key ] === undefined ) {
  10301. verticesMap[ key ] = i;
  10302. unique.push( this.vertices[ i ] );
  10303. changes[ i ] = unique.length - 1;
  10304. } else {
  10305. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  10306. changes[ i ] = changes[ verticesMap[ key ] ];
  10307. }
  10308. }
  10309. // if faces are completely degenerate after merging vertices, we
  10310. // have to remove them from the geometry.
  10311. var faceIndicesToRemove = [];
  10312. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  10313. face = this.faces[ i ];
  10314. face.a = changes[ face.a ];
  10315. face.b = changes[ face.b ];
  10316. face.c = changes[ face.c ];
  10317. indices = [ face.a, face.b, face.c ];
  10318. // if any duplicate vertices are found in a Face3
  10319. // we have to remove the face as nothing can be saved
  10320. for ( var n = 0; n < 3; n ++ ) {
  10321. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  10322. faceIndicesToRemove.push( i );
  10323. break;
  10324. }
  10325. }
  10326. }
  10327. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  10328. var idx = faceIndicesToRemove[ i ];
  10329. this.faces.splice( idx, 1 );
  10330. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  10331. this.faceVertexUvs[ j ].splice( idx, 1 );
  10332. }
  10333. }
  10334. // Use unique set of vertices
  10335. var diff = this.vertices.length - unique.length;
  10336. this.vertices = unique;
  10337. return diff;
  10338. },
  10339. setFromPoints: function ( points ) {
  10340. this.vertices = [];
  10341. for ( var i = 0, l = points.length; i < l; i ++ ) {
  10342. var point = points[ i ];
  10343. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  10344. }
  10345. return this;
  10346. },
  10347. sortFacesByMaterialIndex: function () {
  10348. var faces = this.faces;
  10349. var length = faces.length;
  10350. // tag faces
  10351. for ( var i = 0; i < length; i ++ ) {
  10352. faces[ i ]._id = i;
  10353. }
  10354. // sort faces
  10355. function materialIndexSort( a, b ) {
  10356. return a.materialIndex - b.materialIndex;
  10357. }
  10358. faces.sort( materialIndexSort );
  10359. // sort uvs
  10360. var uvs1 = this.faceVertexUvs[ 0 ];
  10361. var uvs2 = this.faceVertexUvs[ 1 ];
  10362. var newUvs1, newUvs2;
  10363. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  10364. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  10365. for ( var i = 0; i < length; i ++ ) {
  10366. var id = faces[ i ]._id;
  10367. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  10368. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  10369. }
  10370. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  10371. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  10372. },
  10373. toJSON: function () {
  10374. var data = {
  10375. metadata: {
  10376. version: 4.5,
  10377. type: 'Geometry',
  10378. generator: 'Geometry.toJSON'
  10379. }
  10380. };
  10381. // standard Geometry serialization
  10382. data.uuid = this.uuid;
  10383. data.type = this.type;
  10384. if ( this.name !== '' ) data.name = this.name;
  10385. if ( this.parameters !== undefined ) {
  10386. var parameters = this.parameters;
  10387. for ( var key in parameters ) {
  10388. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  10389. }
  10390. return data;
  10391. }
  10392. var vertices = [];
  10393. for ( var i = 0; i < this.vertices.length; i ++ ) {
  10394. var vertex = this.vertices[ i ];
  10395. vertices.push( vertex.x, vertex.y, vertex.z );
  10396. }
  10397. var faces = [];
  10398. var normals = [];
  10399. var normalsHash = {};
  10400. var colors = [];
  10401. var colorsHash = {};
  10402. var uvs = [];
  10403. var uvsHash = {};
  10404. for ( var i = 0; i < this.faces.length; i ++ ) {
  10405. var face = this.faces[ i ];
  10406. var hasMaterial = true;
  10407. var hasFaceUv = false; // deprecated
  10408. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  10409. var hasFaceNormal = face.normal.length() > 0;
  10410. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  10411. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  10412. var hasFaceVertexColor = face.vertexColors.length > 0;
  10413. var faceType = 0;
  10414. faceType = setBit( faceType, 0, 0 ); // isQuad
  10415. faceType = setBit( faceType, 1, hasMaterial );
  10416. faceType = setBit( faceType, 2, hasFaceUv );
  10417. faceType = setBit( faceType, 3, hasFaceVertexUv );
  10418. faceType = setBit( faceType, 4, hasFaceNormal );
  10419. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  10420. faceType = setBit( faceType, 6, hasFaceColor );
  10421. faceType = setBit( faceType, 7, hasFaceVertexColor );
  10422. faces.push( faceType );
  10423. faces.push( face.a, face.b, face.c );
  10424. faces.push( face.materialIndex );
  10425. if ( hasFaceVertexUv ) {
  10426. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  10427. faces.push(
  10428. getUvIndex( faceVertexUvs[ 0 ] ),
  10429. getUvIndex( faceVertexUvs[ 1 ] ),
  10430. getUvIndex( faceVertexUvs[ 2 ] )
  10431. );
  10432. }
  10433. if ( hasFaceNormal ) {
  10434. faces.push( getNormalIndex( face.normal ) );
  10435. }
  10436. if ( hasFaceVertexNormal ) {
  10437. var vertexNormals = face.vertexNormals;
  10438. faces.push(
  10439. getNormalIndex( vertexNormals[ 0 ] ),
  10440. getNormalIndex( vertexNormals[ 1 ] ),
  10441. getNormalIndex( vertexNormals[ 2 ] )
  10442. );
  10443. }
  10444. if ( hasFaceColor ) {
  10445. faces.push( getColorIndex( face.color ) );
  10446. }
  10447. if ( hasFaceVertexColor ) {
  10448. var vertexColors = face.vertexColors;
  10449. faces.push(
  10450. getColorIndex( vertexColors[ 0 ] ),
  10451. getColorIndex( vertexColors[ 1 ] ),
  10452. getColorIndex( vertexColors[ 2 ] )
  10453. );
  10454. }
  10455. }
  10456. function setBit( value, position, enabled ) {
  10457. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  10458. }
  10459. function getNormalIndex( normal ) {
  10460. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  10461. if ( normalsHash[ hash ] !== undefined ) {
  10462. return normalsHash[ hash ];
  10463. }
  10464. normalsHash[ hash ] = normals.length / 3;
  10465. normals.push( normal.x, normal.y, normal.z );
  10466. return normalsHash[ hash ];
  10467. }
  10468. function getColorIndex( color ) {
  10469. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  10470. if ( colorsHash[ hash ] !== undefined ) {
  10471. return colorsHash[ hash ];
  10472. }
  10473. colorsHash[ hash ] = colors.length;
  10474. colors.push( color.getHex() );
  10475. return colorsHash[ hash ];
  10476. }
  10477. function getUvIndex( uv ) {
  10478. var hash = uv.x.toString() + uv.y.toString();
  10479. if ( uvsHash[ hash ] !== undefined ) {
  10480. return uvsHash[ hash ];
  10481. }
  10482. uvsHash[ hash ] = uvs.length / 2;
  10483. uvs.push( uv.x, uv.y );
  10484. return uvsHash[ hash ];
  10485. }
  10486. data.data = {};
  10487. data.data.vertices = vertices;
  10488. data.data.normals = normals;
  10489. if ( colors.length > 0 ) data.data.colors = colors;
  10490. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  10491. data.data.faces = faces;
  10492. return data;
  10493. },
  10494. clone: function () {
  10495. /*
  10496. // Handle primitives
  10497. var parameters = this.parameters;
  10498. if ( parameters !== undefined ) {
  10499. var values = [];
  10500. for ( var key in parameters ) {
  10501. values.push( parameters[ key ] );
  10502. }
  10503. var geometry = Object.create( this.constructor.prototype );
  10504. this.constructor.apply( geometry, values );
  10505. return geometry;
  10506. }
  10507. return new this.constructor().copy( this );
  10508. */
  10509. return new Geometry().copy( this );
  10510. },
  10511. copy: function ( source ) {
  10512. var i, il, j, jl, k, kl;
  10513. // reset
  10514. this.vertices = [];
  10515. this.colors = [];
  10516. this.faces = [];
  10517. this.faceVertexUvs = [[]];
  10518. this.morphTargets = [];
  10519. this.morphNormals = [];
  10520. this.skinWeights = [];
  10521. this.skinIndices = [];
  10522. this.lineDistances = [];
  10523. this.boundingBox = null;
  10524. this.boundingSphere = null;
  10525. // name
  10526. this.name = source.name;
  10527. // vertices
  10528. var vertices = source.vertices;
  10529. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  10530. this.vertices.push( vertices[ i ].clone() );
  10531. }
  10532. // colors
  10533. var colors = source.colors;
  10534. for ( i = 0, il = colors.length; i < il; i ++ ) {
  10535. this.colors.push( colors[ i ].clone() );
  10536. }
  10537. // faces
  10538. var faces = source.faces;
  10539. for ( i = 0, il = faces.length; i < il; i ++ ) {
  10540. this.faces.push( faces[ i ].clone() );
  10541. }
  10542. // face vertex uvs
  10543. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  10544. var faceVertexUvs = source.faceVertexUvs[ i ];
  10545. if ( this.faceVertexUvs[ i ] === undefined ) {
  10546. this.faceVertexUvs[ i ] = [];
  10547. }
  10548. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  10549. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  10550. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  10551. var uv = uvs[ k ];
  10552. uvsCopy.push( uv.clone() );
  10553. }
  10554. this.faceVertexUvs[ i ].push( uvsCopy );
  10555. }
  10556. }
  10557. // morph targets
  10558. var morphTargets = source.morphTargets;
  10559. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  10560. var morphTarget = {};
  10561. morphTarget.name = morphTargets[ i ].name;
  10562. // vertices
  10563. if ( morphTargets[ i ].vertices !== undefined ) {
  10564. morphTarget.vertices = [];
  10565. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  10566. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  10567. }
  10568. }
  10569. // normals
  10570. if ( morphTargets[ i ].normals !== undefined ) {
  10571. morphTarget.normals = [];
  10572. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  10573. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  10574. }
  10575. }
  10576. this.morphTargets.push( morphTarget );
  10577. }
  10578. // morph normals
  10579. var morphNormals = source.morphNormals;
  10580. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  10581. var morphNormal = {};
  10582. // vertex normals
  10583. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  10584. morphNormal.vertexNormals = [];
  10585. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  10586. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  10587. var destVertexNormal = {};
  10588. destVertexNormal.a = srcVertexNormal.a.clone();
  10589. destVertexNormal.b = srcVertexNormal.b.clone();
  10590. destVertexNormal.c = srcVertexNormal.c.clone();
  10591. morphNormal.vertexNormals.push( destVertexNormal );
  10592. }
  10593. }
  10594. // face normals
  10595. if ( morphNormals[ i ].faceNormals !== undefined ) {
  10596. morphNormal.faceNormals = [];
  10597. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  10598. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  10599. }
  10600. }
  10601. this.morphNormals.push( morphNormal );
  10602. }
  10603. // skin weights
  10604. var skinWeights = source.skinWeights;
  10605. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  10606. this.skinWeights.push( skinWeights[ i ].clone() );
  10607. }
  10608. // skin indices
  10609. var skinIndices = source.skinIndices;
  10610. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  10611. this.skinIndices.push( skinIndices[ i ].clone() );
  10612. }
  10613. // line distances
  10614. var lineDistances = source.lineDistances;
  10615. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  10616. this.lineDistances.push( lineDistances[ i ] );
  10617. }
  10618. // bounding box
  10619. var boundingBox = source.boundingBox;
  10620. if ( boundingBox !== null ) {
  10621. this.boundingBox = boundingBox.clone();
  10622. }
  10623. // bounding sphere
  10624. var boundingSphere = source.boundingSphere;
  10625. if ( boundingSphere !== null ) {
  10626. this.boundingSphere = boundingSphere.clone();
  10627. }
  10628. // update flags
  10629. this.elementsNeedUpdate = source.elementsNeedUpdate;
  10630. this.verticesNeedUpdate = source.verticesNeedUpdate;
  10631. this.uvsNeedUpdate = source.uvsNeedUpdate;
  10632. this.normalsNeedUpdate = source.normalsNeedUpdate;
  10633. this.colorsNeedUpdate = source.colorsNeedUpdate;
  10634. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  10635. this.groupsNeedUpdate = source.groupsNeedUpdate;
  10636. return this;
  10637. },
  10638. dispose: function () {
  10639. this.dispatchEvent( { type: 'dispose' } );
  10640. }
  10641. } );
  10642. /**
  10643. * @author mrdoob / http://mrdoob.com/
  10644. */
  10645. function BufferAttribute( array, itemSize, normalized ) {
  10646. if ( Array.isArray( array ) ) {
  10647. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  10648. }
  10649. this.name = '';
  10650. this.array = array;
  10651. this.itemSize = itemSize;
  10652. this.count = array !== undefined ? array.length / itemSize : 0;
  10653. this.normalized = normalized === true;
  10654. this.dynamic = false;
  10655. this.updateRange = { offset: 0, count: - 1 };
  10656. this.version = 0;
  10657. }
  10658. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  10659. set: function ( value ) {
  10660. if ( value === true ) this.version ++;
  10661. }
  10662. } );
  10663. Object.assign( BufferAttribute.prototype, {
  10664. isBufferAttribute: true,
  10665. onUploadCallback: function () {},
  10666. setArray: function ( array ) {
  10667. if ( Array.isArray( array ) ) {
  10668. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  10669. }
  10670. this.count = array !== undefined ? array.length / this.itemSize : 0;
  10671. this.array = array;
  10672. return this;
  10673. },
  10674. setDynamic: function ( value ) {
  10675. this.dynamic = value;
  10676. return this;
  10677. },
  10678. copy: function ( source ) {
  10679. this.name = source.name;
  10680. this.array = new source.array.constructor( source.array );
  10681. this.itemSize = source.itemSize;
  10682. this.count = source.count;
  10683. this.normalized = source.normalized;
  10684. this.dynamic = source.dynamic;
  10685. return this;
  10686. },
  10687. copyAt: function ( index1, attribute, index2 ) {
  10688. index1 *= this.itemSize;
  10689. index2 *= attribute.itemSize;
  10690. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  10691. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  10692. }
  10693. return this;
  10694. },
  10695. copyArray: function ( array ) {
  10696. this.array.set( array );
  10697. return this;
  10698. },
  10699. copyColorsArray: function ( colors ) {
  10700. var array = this.array, offset = 0;
  10701. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  10702. var color = colors[ i ];
  10703. if ( color === undefined ) {
  10704. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  10705. color = new Color();
  10706. }
  10707. array[ offset ++ ] = color.r;
  10708. array[ offset ++ ] = color.g;
  10709. array[ offset ++ ] = color.b;
  10710. }
  10711. return this;
  10712. },
  10713. copyVector2sArray: function ( vectors ) {
  10714. var array = this.array, offset = 0;
  10715. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10716. var vector = vectors[ i ];
  10717. if ( vector === undefined ) {
  10718. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  10719. vector = new Vector2();
  10720. }
  10721. array[ offset ++ ] = vector.x;
  10722. array[ offset ++ ] = vector.y;
  10723. }
  10724. return this;
  10725. },
  10726. copyVector3sArray: function ( vectors ) {
  10727. var array = this.array, offset = 0;
  10728. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10729. var vector = vectors[ i ];
  10730. if ( vector === undefined ) {
  10731. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  10732. vector = new Vector3();
  10733. }
  10734. array[ offset ++ ] = vector.x;
  10735. array[ offset ++ ] = vector.y;
  10736. array[ offset ++ ] = vector.z;
  10737. }
  10738. return this;
  10739. },
  10740. copyVector4sArray: function ( vectors ) {
  10741. var array = this.array, offset = 0;
  10742. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10743. var vector = vectors[ i ];
  10744. if ( vector === undefined ) {
  10745. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  10746. vector = new Vector4();
  10747. }
  10748. array[ offset ++ ] = vector.x;
  10749. array[ offset ++ ] = vector.y;
  10750. array[ offset ++ ] = vector.z;
  10751. array[ offset ++ ] = vector.w;
  10752. }
  10753. return this;
  10754. },
  10755. set: function ( value, offset ) {
  10756. if ( offset === undefined ) offset = 0;
  10757. this.array.set( value, offset );
  10758. return this;
  10759. },
  10760. getX: function ( index ) {
  10761. return this.array[ index * this.itemSize ];
  10762. },
  10763. setX: function ( index, x ) {
  10764. this.array[ index * this.itemSize ] = x;
  10765. return this;
  10766. },
  10767. getY: function ( index ) {
  10768. return this.array[ index * this.itemSize + 1 ];
  10769. },
  10770. setY: function ( index, y ) {
  10771. this.array[ index * this.itemSize + 1 ] = y;
  10772. return this;
  10773. },
  10774. getZ: function ( index ) {
  10775. return this.array[ index * this.itemSize + 2 ];
  10776. },
  10777. setZ: function ( index, z ) {
  10778. this.array[ index * this.itemSize + 2 ] = z;
  10779. return this;
  10780. },
  10781. getW: function ( index ) {
  10782. return this.array[ index * this.itemSize + 3 ];
  10783. },
  10784. setW: function ( index, w ) {
  10785. this.array[ index * this.itemSize + 3 ] = w;
  10786. return this;
  10787. },
  10788. setXY: function ( index, x, y ) {
  10789. index *= this.itemSize;
  10790. this.array[ index + 0 ] = x;
  10791. this.array[ index + 1 ] = y;
  10792. return this;
  10793. },
  10794. setXYZ: function ( index, x, y, z ) {
  10795. index *= this.itemSize;
  10796. this.array[ index + 0 ] = x;
  10797. this.array[ index + 1 ] = y;
  10798. this.array[ index + 2 ] = z;
  10799. return this;
  10800. },
  10801. setXYZW: function ( index, x, y, z, w ) {
  10802. index *= this.itemSize;
  10803. this.array[ index + 0 ] = x;
  10804. this.array[ index + 1 ] = y;
  10805. this.array[ index + 2 ] = z;
  10806. this.array[ index + 3 ] = w;
  10807. return this;
  10808. },
  10809. onUpload: function ( callback ) {
  10810. this.onUploadCallback = callback;
  10811. return this;
  10812. },
  10813. clone: function () {
  10814. return new this.constructor( this.array, this.itemSize ).copy( this );
  10815. }
  10816. } );
  10817. //
  10818. function Int8BufferAttribute( array, itemSize, normalized ) {
  10819. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  10820. }
  10821. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10822. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  10823. function Uint8BufferAttribute( array, itemSize, normalized ) {
  10824. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  10825. }
  10826. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10827. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  10828. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  10829. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  10830. }
  10831. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10832. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  10833. function Int16BufferAttribute( array, itemSize, normalized ) {
  10834. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  10835. }
  10836. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10837. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  10838. function Uint16BufferAttribute( array, itemSize, normalized ) {
  10839. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  10840. }
  10841. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10842. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  10843. function Int32BufferAttribute( array, itemSize, normalized ) {
  10844. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  10845. }
  10846. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10847. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  10848. function Uint32BufferAttribute( array, itemSize, normalized ) {
  10849. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  10850. }
  10851. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10852. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  10853. function Float32BufferAttribute( array, itemSize, normalized ) {
  10854. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  10855. }
  10856. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10857. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  10858. function Float64BufferAttribute( array, itemSize, normalized ) {
  10859. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  10860. }
  10861. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10862. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  10863. /**
  10864. * @author mrdoob / http://mrdoob.com/
  10865. */
  10866. function DirectGeometry() {
  10867. this.vertices = [];
  10868. this.normals = [];
  10869. this.colors = [];
  10870. this.uvs = [];
  10871. this.uvs2 = [];
  10872. this.groups = [];
  10873. this.morphTargets = {};
  10874. this.skinWeights = [];
  10875. this.skinIndices = [];
  10876. // this.lineDistances = [];
  10877. this.boundingBox = null;
  10878. this.boundingSphere = null;
  10879. // update flags
  10880. this.verticesNeedUpdate = false;
  10881. this.normalsNeedUpdate = false;
  10882. this.colorsNeedUpdate = false;
  10883. this.uvsNeedUpdate = false;
  10884. this.groupsNeedUpdate = false;
  10885. }
  10886. Object.assign( DirectGeometry.prototype, {
  10887. computeGroups: function ( geometry ) {
  10888. var group;
  10889. var groups = [];
  10890. var materialIndex = undefined;
  10891. var faces = geometry.faces;
  10892. for ( var i = 0; i < faces.length; i ++ ) {
  10893. var face = faces[ i ];
  10894. // materials
  10895. if ( face.materialIndex !== materialIndex ) {
  10896. materialIndex = face.materialIndex;
  10897. if ( group !== undefined ) {
  10898. group.count = ( i * 3 ) - group.start;
  10899. groups.push( group );
  10900. }
  10901. group = {
  10902. start: i * 3,
  10903. materialIndex: materialIndex
  10904. };
  10905. }
  10906. }
  10907. if ( group !== undefined ) {
  10908. group.count = ( i * 3 ) - group.start;
  10909. groups.push( group );
  10910. }
  10911. this.groups = groups;
  10912. },
  10913. fromGeometry: function ( geometry ) {
  10914. var faces = geometry.faces;
  10915. var vertices = geometry.vertices;
  10916. var faceVertexUvs = geometry.faceVertexUvs;
  10917. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  10918. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  10919. // morphs
  10920. var morphTargets = geometry.morphTargets;
  10921. var morphTargetsLength = morphTargets.length;
  10922. var morphTargetsPosition;
  10923. if ( morphTargetsLength > 0 ) {
  10924. morphTargetsPosition = [];
  10925. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  10926. morphTargetsPosition[ i ] = [];
  10927. }
  10928. this.morphTargets.position = morphTargetsPosition;
  10929. }
  10930. var morphNormals = geometry.morphNormals;
  10931. var morphNormalsLength = morphNormals.length;
  10932. var morphTargetsNormal;
  10933. if ( morphNormalsLength > 0 ) {
  10934. morphTargetsNormal = [];
  10935. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  10936. morphTargetsNormal[ i ] = [];
  10937. }
  10938. this.morphTargets.normal = morphTargetsNormal;
  10939. }
  10940. // skins
  10941. var skinIndices = geometry.skinIndices;
  10942. var skinWeights = geometry.skinWeights;
  10943. var hasSkinIndices = skinIndices.length === vertices.length;
  10944. var hasSkinWeights = skinWeights.length === vertices.length;
  10945. //
  10946. for ( var i = 0; i < faces.length; i ++ ) {
  10947. var face = faces[ i ];
  10948. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  10949. var vertexNormals = face.vertexNormals;
  10950. if ( vertexNormals.length === 3 ) {
  10951. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  10952. } else {
  10953. var normal = face.normal;
  10954. this.normals.push( normal, normal, normal );
  10955. }
  10956. var vertexColors = face.vertexColors;
  10957. if ( vertexColors.length === 3 ) {
  10958. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  10959. } else {
  10960. var color = face.color;
  10961. this.colors.push( color, color, color );
  10962. }
  10963. if ( hasFaceVertexUv === true ) {
  10964. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  10965. if ( vertexUvs !== undefined ) {
  10966. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  10967. } else {
  10968. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  10969. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  10970. }
  10971. }
  10972. if ( hasFaceVertexUv2 === true ) {
  10973. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  10974. if ( vertexUvs !== undefined ) {
  10975. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  10976. } else {
  10977. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  10978. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  10979. }
  10980. }
  10981. // morphs
  10982. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  10983. var morphTarget = morphTargets[ j ].vertices;
  10984. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  10985. }
  10986. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  10987. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  10988. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  10989. }
  10990. // skins
  10991. if ( hasSkinIndices ) {
  10992. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  10993. }
  10994. if ( hasSkinWeights ) {
  10995. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  10996. }
  10997. }
  10998. this.computeGroups( geometry );
  10999. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11000. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11001. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11002. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11003. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11004. return this;
  11005. }
  11006. } );
  11007. /**
  11008. * @author mrdoob / http://mrdoob.com/
  11009. */
  11010. function arrayMax( array ) {
  11011. if ( array.length === 0 ) return - Infinity;
  11012. var max = array[ 0 ];
  11013. for ( var i = 1, l = array.length; i < l; ++ i ) {
  11014. if ( array[ i ] > max ) max = array[ i ];
  11015. }
  11016. return max;
  11017. }
  11018. /**
  11019. * @author alteredq / http://alteredqualia.com/
  11020. * @author mrdoob / http://mrdoob.com/
  11021. */
  11022. var bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  11023. function BufferGeometry() {
  11024. Object.defineProperty( this, 'id', { value: bufferGeometryId += 2 } );
  11025. this.uuid = _Math.generateUUID();
  11026. this.name = '';
  11027. this.type = 'BufferGeometry';
  11028. this.index = null;
  11029. this.attributes = {};
  11030. this.morphAttributes = {};
  11031. this.groups = [];
  11032. this.boundingBox = null;
  11033. this.boundingSphere = null;
  11034. this.drawRange = { start: 0, count: Infinity };
  11035. }
  11036. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  11037. constructor: BufferGeometry,
  11038. isBufferGeometry: true,
  11039. getIndex: function () {
  11040. return this.index;
  11041. },
  11042. setIndex: function ( index ) {
  11043. if ( Array.isArray( index ) ) {
  11044. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  11045. } else {
  11046. this.index = index;
  11047. }
  11048. },
  11049. addAttribute: function ( name, attribute ) {
  11050. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  11051. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  11052. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  11053. return;
  11054. }
  11055. if ( name === 'index' ) {
  11056. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  11057. this.setIndex( attribute );
  11058. return;
  11059. }
  11060. this.attributes[ name ] = attribute;
  11061. return this;
  11062. },
  11063. getAttribute: function ( name ) {
  11064. return this.attributes[ name ];
  11065. },
  11066. removeAttribute: function ( name ) {
  11067. delete this.attributes[ name ];
  11068. return this;
  11069. },
  11070. addGroup: function ( start, count, materialIndex ) {
  11071. this.groups.push( {
  11072. start: start,
  11073. count: count,
  11074. materialIndex: materialIndex !== undefined ? materialIndex : 0
  11075. } );
  11076. },
  11077. clearGroups: function () {
  11078. this.groups = [];
  11079. },
  11080. setDrawRange: function ( start, count ) {
  11081. this.drawRange.start = start;
  11082. this.drawRange.count = count;
  11083. },
  11084. applyMatrix: function ( matrix ) {
  11085. var position = this.attributes.position;
  11086. if ( position !== undefined ) {
  11087. matrix.applyToBufferAttribute( position );
  11088. position.needsUpdate = true;
  11089. }
  11090. var normal = this.attributes.normal;
  11091. if ( normal !== undefined ) {
  11092. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11093. normalMatrix.applyToBufferAttribute( normal );
  11094. normal.needsUpdate = true;
  11095. }
  11096. if ( this.boundingBox !== null ) {
  11097. this.computeBoundingBox();
  11098. }
  11099. if ( this.boundingSphere !== null ) {
  11100. this.computeBoundingSphere();
  11101. }
  11102. return this;
  11103. },
  11104. rotateX: function () {
  11105. // rotate geometry around world x-axis
  11106. var m1 = new Matrix4();
  11107. return function rotateX( angle ) {
  11108. m1.makeRotationX( angle );
  11109. this.applyMatrix( m1 );
  11110. return this;
  11111. };
  11112. }(),
  11113. rotateY: function () {
  11114. // rotate geometry around world y-axis
  11115. var m1 = new Matrix4();
  11116. return function rotateY( angle ) {
  11117. m1.makeRotationY( angle );
  11118. this.applyMatrix( m1 );
  11119. return this;
  11120. };
  11121. }(),
  11122. rotateZ: function () {
  11123. // rotate geometry around world z-axis
  11124. var m1 = new Matrix4();
  11125. return function rotateZ( angle ) {
  11126. m1.makeRotationZ( angle );
  11127. this.applyMatrix( m1 );
  11128. return this;
  11129. };
  11130. }(),
  11131. translate: function () {
  11132. // translate geometry
  11133. var m1 = new Matrix4();
  11134. return function translate( x, y, z ) {
  11135. m1.makeTranslation( x, y, z );
  11136. this.applyMatrix( m1 );
  11137. return this;
  11138. };
  11139. }(),
  11140. scale: function () {
  11141. // scale geometry
  11142. var m1 = new Matrix4();
  11143. return function scale( x, y, z ) {
  11144. m1.makeScale( x, y, z );
  11145. this.applyMatrix( m1 );
  11146. return this;
  11147. };
  11148. }(),
  11149. lookAt: function () {
  11150. var obj = new Object3D();
  11151. return function lookAt( vector ) {
  11152. obj.lookAt( vector );
  11153. obj.updateMatrix();
  11154. this.applyMatrix( obj.matrix );
  11155. };
  11156. }(),
  11157. center: function () {
  11158. var offset = new Vector3();
  11159. return function center() {
  11160. this.computeBoundingBox();
  11161. this.boundingBox.getCenter( offset ).negate();
  11162. this.translate( offset.x, offset.y, offset.z );
  11163. return this;
  11164. };
  11165. }(),
  11166. setFromObject: function ( object ) {
  11167. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  11168. var geometry = object.geometry;
  11169. if ( object.isPoints || object.isLine ) {
  11170. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  11171. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  11172. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  11173. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  11174. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  11175. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  11176. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  11177. }
  11178. if ( geometry.boundingSphere !== null ) {
  11179. this.boundingSphere = geometry.boundingSphere.clone();
  11180. }
  11181. if ( geometry.boundingBox !== null ) {
  11182. this.boundingBox = geometry.boundingBox.clone();
  11183. }
  11184. } else if ( object.isMesh ) {
  11185. if ( geometry && geometry.isGeometry ) {
  11186. this.fromGeometry( geometry );
  11187. }
  11188. }
  11189. return this;
  11190. },
  11191. setFromPoints: function ( points ) {
  11192. var position = [];
  11193. for ( var i = 0, l = points.length; i < l; i ++ ) {
  11194. var point = points[ i ];
  11195. position.push( point.x, point.y, point.z || 0 );
  11196. }
  11197. this.addAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  11198. return this;
  11199. },
  11200. updateFromObject: function ( object ) {
  11201. var geometry = object.geometry;
  11202. if ( object.isMesh ) {
  11203. var direct = geometry.__directGeometry;
  11204. if ( geometry.elementsNeedUpdate === true ) {
  11205. direct = undefined;
  11206. geometry.elementsNeedUpdate = false;
  11207. }
  11208. if ( direct === undefined ) {
  11209. return this.fromGeometry( geometry );
  11210. }
  11211. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11212. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11213. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11214. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11215. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11216. geometry.verticesNeedUpdate = false;
  11217. geometry.normalsNeedUpdate = false;
  11218. geometry.colorsNeedUpdate = false;
  11219. geometry.uvsNeedUpdate = false;
  11220. geometry.groupsNeedUpdate = false;
  11221. geometry = direct;
  11222. }
  11223. var attribute;
  11224. if ( geometry.verticesNeedUpdate === true ) {
  11225. attribute = this.attributes.position;
  11226. if ( attribute !== undefined ) {
  11227. attribute.copyVector3sArray( geometry.vertices );
  11228. attribute.needsUpdate = true;
  11229. }
  11230. geometry.verticesNeedUpdate = false;
  11231. }
  11232. if ( geometry.normalsNeedUpdate === true ) {
  11233. attribute = this.attributes.normal;
  11234. if ( attribute !== undefined ) {
  11235. attribute.copyVector3sArray( geometry.normals );
  11236. attribute.needsUpdate = true;
  11237. }
  11238. geometry.normalsNeedUpdate = false;
  11239. }
  11240. if ( geometry.colorsNeedUpdate === true ) {
  11241. attribute = this.attributes.color;
  11242. if ( attribute !== undefined ) {
  11243. attribute.copyColorsArray( geometry.colors );
  11244. attribute.needsUpdate = true;
  11245. }
  11246. geometry.colorsNeedUpdate = false;
  11247. }
  11248. if ( geometry.uvsNeedUpdate ) {
  11249. attribute = this.attributes.uv;
  11250. if ( attribute !== undefined ) {
  11251. attribute.copyVector2sArray( geometry.uvs );
  11252. attribute.needsUpdate = true;
  11253. }
  11254. geometry.uvsNeedUpdate = false;
  11255. }
  11256. if ( geometry.lineDistancesNeedUpdate ) {
  11257. attribute = this.attributes.lineDistance;
  11258. if ( attribute !== undefined ) {
  11259. attribute.copyArray( geometry.lineDistances );
  11260. attribute.needsUpdate = true;
  11261. }
  11262. geometry.lineDistancesNeedUpdate = false;
  11263. }
  11264. if ( geometry.groupsNeedUpdate ) {
  11265. geometry.computeGroups( object.geometry );
  11266. this.groups = geometry.groups;
  11267. geometry.groupsNeedUpdate = false;
  11268. }
  11269. return this;
  11270. },
  11271. fromGeometry: function ( geometry ) {
  11272. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  11273. return this.fromDirectGeometry( geometry.__directGeometry );
  11274. },
  11275. fromDirectGeometry: function ( geometry ) {
  11276. var positions = new Float32Array( geometry.vertices.length * 3 );
  11277. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  11278. if ( geometry.normals.length > 0 ) {
  11279. var normals = new Float32Array( geometry.normals.length * 3 );
  11280. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  11281. }
  11282. if ( geometry.colors.length > 0 ) {
  11283. var colors = new Float32Array( geometry.colors.length * 3 );
  11284. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  11285. }
  11286. if ( geometry.uvs.length > 0 ) {
  11287. var uvs = new Float32Array( geometry.uvs.length * 2 );
  11288. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  11289. }
  11290. if ( geometry.uvs2.length > 0 ) {
  11291. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  11292. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  11293. }
  11294. // groups
  11295. this.groups = geometry.groups;
  11296. // morphs
  11297. for ( var name in geometry.morphTargets ) {
  11298. var array = [];
  11299. var morphTargets = geometry.morphTargets[ name ];
  11300. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  11301. var morphTarget = morphTargets[ i ];
  11302. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  11303. array.push( attribute.copyVector3sArray( morphTarget ) );
  11304. }
  11305. this.morphAttributes[ name ] = array;
  11306. }
  11307. // skinning
  11308. if ( geometry.skinIndices.length > 0 ) {
  11309. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  11310. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  11311. }
  11312. if ( geometry.skinWeights.length > 0 ) {
  11313. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  11314. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  11315. }
  11316. //
  11317. if ( geometry.boundingSphere !== null ) {
  11318. this.boundingSphere = geometry.boundingSphere.clone();
  11319. }
  11320. if ( geometry.boundingBox !== null ) {
  11321. this.boundingBox = geometry.boundingBox.clone();
  11322. }
  11323. return this;
  11324. },
  11325. computeBoundingBox: function () {
  11326. if ( this.boundingBox === null ) {
  11327. this.boundingBox = new Box3();
  11328. }
  11329. var position = this.attributes.position;
  11330. if ( position !== undefined ) {
  11331. this.boundingBox.setFromBufferAttribute( position );
  11332. } else {
  11333. this.boundingBox.makeEmpty();
  11334. }
  11335. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  11336. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  11337. }
  11338. },
  11339. computeBoundingSphere: function () {
  11340. var box = new Box3();
  11341. var vector = new Vector3();
  11342. return function computeBoundingSphere() {
  11343. if ( this.boundingSphere === null ) {
  11344. this.boundingSphere = new Sphere();
  11345. }
  11346. var position = this.attributes.position;
  11347. if ( position ) {
  11348. var center = this.boundingSphere.center;
  11349. box.setFromBufferAttribute( position );
  11350. box.getCenter( center );
  11351. // hoping to find a boundingSphere with a radius smaller than the
  11352. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  11353. var maxRadiusSq = 0;
  11354. for ( var i = 0, il = position.count; i < il; i ++ ) {
  11355. vector.x = position.getX( i );
  11356. vector.y = position.getY( i );
  11357. vector.z = position.getZ( i );
  11358. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  11359. }
  11360. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  11361. if ( isNaN( this.boundingSphere.radius ) ) {
  11362. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  11363. }
  11364. }
  11365. };
  11366. }(),
  11367. computeFaceNormals: function () {
  11368. // backwards compatibility
  11369. },
  11370. computeVertexNormals: function () {
  11371. var index = this.index;
  11372. var attributes = this.attributes;
  11373. var groups = this.groups;
  11374. if ( attributes.position ) {
  11375. var positions = attributes.position.array;
  11376. if ( attributes.normal === undefined ) {
  11377. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  11378. } else {
  11379. // reset existing normals to zero
  11380. var array = attributes.normal.array;
  11381. for ( var i = 0, il = array.length; i < il; i ++ ) {
  11382. array[ i ] = 0;
  11383. }
  11384. }
  11385. var normals = attributes.normal.array;
  11386. var vA, vB, vC;
  11387. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  11388. var cb = new Vector3(), ab = new Vector3();
  11389. // indexed elements
  11390. if ( index ) {
  11391. var indices = index.array;
  11392. if ( groups.length === 0 ) {
  11393. this.addGroup( 0, indices.length );
  11394. }
  11395. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  11396. var group = groups[ j ];
  11397. var start = group.start;
  11398. var count = group.count;
  11399. for ( var i = start, il = start + count; i < il; i += 3 ) {
  11400. vA = indices[ i + 0 ] * 3;
  11401. vB = indices[ i + 1 ] * 3;
  11402. vC = indices[ i + 2 ] * 3;
  11403. pA.fromArray( positions, vA );
  11404. pB.fromArray( positions, vB );
  11405. pC.fromArray( positions, vC );
  11406. cb.subVectors( pC, pB );
  11407. ab.subVectors( pA, pB );
  11408. cb.cross( ab );
  11409. normals[ vA ] += cb.x;
  11410. normals[ vA + 1 ] += cb.y;
  11411. normals[ vA + 2 ] += cb.z;
  11412. normals[ vB ] += cb.x;
  11413. normals[ vB + 1 ] += cb.y;
  11414. normals[ vB + 2 ] += cb.z;
  11415. normals[ vC ] += cb.x;
  11416. normals[ vC + 1 ] += cb.y;
  11417. normals[ vC + 2 ] += cb.z;
  11418. }
  11419. }
  11420. } else {
  11421. // non-indexed elements (unconnected triangle soup)
  11422. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  11423. pA.fromArray( positions, i );
  11424. pB.fromArray( positions, i + 3 );
  11425. pC.fromArray( positions, i + 6 );
  11426. cb.subVectors( pC, pB );
  11427. ab.subVectors( pA, pB );
  11428. cb.cross( ab );
  11429. normals[ i ] = cb.x;
  11430. normals[ i + 1 ] = cb.y;
  11431. normals[ i + 2 ] = cb.z;
  11432. normals[ i + 3 ] = cb.x;
  11433. normals[ i + 4 ] = cb.y;
  11434. normals[ i + 5 ] = cb.z;
  11435. normals[ i + 6 ] = cb.x;
  11436. normals[ i + 7 ] = cb.y;
  11437. normals[ i + 8 ] = cb.z;
  11438. }
  11439. }
  11440. this.normalizeNormals();
  11441. attributes.normal.needsUpdate = true;
  11442. }
  11443. },
  11444. merge: function ( geometry, offset ) {
  11445. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  11446. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  11447. return;
  11448. }
  11449. if ( offset === undefined ) {
  11450. offset = 0;
  11451. console.warn(
  11452. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  11453. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  11454. );
  11455. }
  11456. var attributes = this.attributes;
  11457. for ( var key in attributes ) {
  11458. if ( geometry.attributes[ key ] === undefined ) continue;
  11459. var attribute1 = attributes[ key ];
  11460. var attributeArray1 = attribute1.array;
  11461. var attribute2 = geometry.attributes[ key ];
  11462. var attributeArray2 = attribute2.array;
  11463. var attributeSize = attribute2.itemSize;
  11464. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  11465. attributeArray1[ j ] = attributeArray2[ i ];
  11466. }
  11467. }
  11468. return this;
  11469. },
  11470. normalizeNormals: function () {
  11471. var vector = new Vector3();
  11472. return function normalizeNormals() {
  11473. var normals = this.attributes.normal;
  11474. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  11475. vector.x = normals.getX( i );
  11476. vector.y = normals.getY( i );
  11477. vector.z = normals.getZ( i );
  11478. vector.normalize();
  11479. normals.setXYZ( i, vector.x, vector.y, vector.z );
  11480. }
  11481. };
  11482. }(),
  11483. toNonIndexed: function () {
  11484. if ( this.index === null ) {
  11485. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  11486. return this;
  11487. }
  11488. var geometry2 = new BufferGeometry();
  11489. var indices = this.index.array;
  11490. var attributes = this.attributes;
  11491. for ( var name in attributes ) {
  11492. var attribute = attributes[ name ];
  11493. var array = attribute.array;
  11494. var itemSize = attribute.itemSize;
  11495. var array2 = new array.constructor( indices.length * itemSize );
  11496. var index = 0, index2 = 0;
  11497. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  11498. index = indices[ i ] * itemSize;
  11499. for ( var j = 0; j < itemSize; j ++ ) {
  11500. array2[ index2 ++ ] = array[ index ++ ];
  11501. }
  11502. }
  11503. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  11504. }
  11505. var groups = this.groups;
  11506. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  11507. var group = groups[ i ];
  11508. geometry2.addGroup( group.start, group.count, group.materialIndex );
  11509. }
  11510. return geometry2;
  11511. },
  11512. toJSON: function () {
  11513. var data = {
  11514. metadata: {
  11515. version: 4.5,
  11516. type: 'BufferGeometry',
  11517. generator: 'BufferGeometry.toJSON'
  11518. }
  11519. };
  11520. // standard BufferGeometry serialization
  11521. data.uuid = this.uuid;
  11522. data.type = this.type;
  11523. if ( this.name !== '' ) data.name = this.name;
  11524. if ( this.parameters !== undefined ) {
  11525. var parameters = this.parameters;
  11526. for ( var key in parameters ) {
  11527. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  11528. }
  11529. return data;
  11530. }
  11531. data.data = { attributes: {} };
  11532. var index = this.index;
  11533. if ( index !== null ) {
  11534. var array = Array.prototype.slice.call( index.array );
  11535. data.data.index = {
  11536. type: index.array.constructor.name,
  11537. array: array
  11538. };
  11539. }
  11540. var attributes = this.attributes;
  11541. for ( var key in attributes ) {
  11542. var attribute = attributes[ key ];
  11543. var array = Array.prototype.slice.call( attribute.array );
  11544. data.data.attributes[ key ] = {
  11545. itemSize: attribute.itemSize,
  11546. type: attribute.array.constructor.name,
  11547. array: array,
  11548. normalized: attribute.normalized
  11549. };
  11550. }
  11551. var groups = this.groups;
  11552. if ( groups.length > 0 ) {
  11553. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  11554. }
  11555. var boundingSphere = this.boundingSphere;
  11556. if ( boundingSphere !== null ) {
  11557. data.data.boundingSphere = {
  11558. center: boundingSphere.center.toArray(),
  11559. radius: boundingSphere.radius
  11560. };
  11561. }
  11562. return data;
  11563. },
  11564. clone: function () {
  11565. /*
  11566. // Handle primitives
  11567. var parameters = this.parameters;
  11568. if ( parameters !== undefined ) {
  11569. var values = [];
  11570. for ( var key in parameters ) {
  11571. values.push( parameters[ key ] );
  11572. }
  11573. var geometry = Object.create( this.constructor.prototype );
  11574. this.constructor.apply( geometry, values );
  11575. return geometry;
  11576. }
  11577. return new this.constructor().copy( this );
  11578. */
  11579. return new BufferGeometry().copy( this );
  11580. },
  11581. copy: function ( source ) {
  11582. var name, i, l;
  11583. // reset
  11584. this.index = null;
  11585. this.attributes = {};
  11586. this.morphAttributes = {};
  11587. this.groups = [];
  11588. this.boundingBox = null;
  11589. this.boundingSphere = null;
  11590. // name
  11591. this.name = source.name;
  11592. // index
  11593. var index = source.index;
  11594. if ( index !== null ) {
  11595. this.setIndex( index.clone() );
  11596. }
  11597. // attributes
  11598. var attributes = source.attributes;
  11599. for ( name in attributes ) {
  11600. var attribute = attributes[ name ];
  11601. this.addAttribute( name, attribute.clone() );
  11602. }
  11603. // morph attributes
  11604. var morphAttributes = source.morphAttributes;
  11605. for ( name in morphAttributes ) {
  11606. var array = [];
  11607. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11608. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  11609. array.push( morphAttribute[ i ].clone() );
  11610. }
  11611. this.morphAttributes[ name ] = array;
  11612. }
  11613. // groups
  11614. var groups = source.groups;
  11615. for ( i = 0, l = groups.length; i < l; i ++ ) {
  11616. var group = groups[ i ];
  11617. this.addGroup( group.start, group.count, group.materialIndex );
  11618. }
  11619. // bounding box
  11620. var boundingBox = source.boundingBox;
  11621. if ( boundingBox !== null ) {
  11622. this.boundingBox = boundingBox.clone();
  11623. }
  11624. // bounding sphere
  11625. var boundingSphere = source.boundingSphere;
  11626. if ( boundingSphere !== null ) {
  11627. this.boundingSphere = boundingSphere.clone();
  11628. }
  11629. // draw range
  11630. this.drawRange.start = source.drawRange.start;
  11631. this.drawRange.count = source.drawRange.count;
  11632. return this;
  11633. },
  11634. dispose: function () {
  11635. this.dispatchEvent( { type: 'dispose' } );
  11636. }
  11637. } );
  11638. /**
  11639. * @author mrdoob / http://mrdoob.com/
  11640. * @author Mugen87 / https://github.com/Mugen87
  11641. */
  11642. // BoxGeometry
  11643. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  11644. Geometry.call( this );
  11645. this.type = 'BoxGeometry';
  11646. this.parameters = {
  11647. width: width,
  11648. height: height,
  11649. depth: depth,
  11650. widthSegments: widthSegments,
  11651. heightSegments: heightSegments,
  11652. depthSegments: depthSegments
  11653. };
  11654. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  11655. this.mergeVertices();
  11656. }
  11657. BoxGeometry.prototype = Object.create( Geometry.prototype );
  11658. BoxGeometry.prototype.constructor = BoxGeometry;
  11659. // BoxBufferGeometry
  11660. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  11661. BufferGeometry.call( this );
  11662. this.type = 'BoxBufferGeometry';
  11663. this.parameters = {
  11664. width: width,
  11665. height: height,
  11666. depth: depth,
  11667. widthSegments: widthSegments,
  11668. heightSegments: heightSegments,
  11669. depthSegments: depthSegments
  11670. };
  11671. var scope = this;
  11672. width = width || 1;
  11673. height = height || 1;
  11674. depth = depth || 1;
  11675. // segments
  11676. widthSegments = Math.floor( widthSegments ) || 1;
  11677. heightSegments = Math.floor( heightSegments ) || 1;
  11678. depthSegments = Math.floor( depthSegments ) || 1;
  11679. // buffers
  11680. var indices = [];
  11681. var vertices = [];
  11682. var normals = [];
  11683. var uvs = [];
  11684. // helper variables
  11685. var numberOfVertices = 0;
  11686. var groupStart = 0;
  11687. // build each side of the box geometry
  11688. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  11689. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  11690. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  11691. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  11692. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  11693. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  11694. // build geometry
  11695. this.setIndex( indices );
  11696. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11697. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11698. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11699. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  11700. var segmentWidth = width / gridX;
  11701. var segmentHeight = height / gridY;
  11702. var widthHalf = width / 2;
  11703. var heightHalf = height / 2;
  11704. var depthHalf = depth / 2;
  11705. var gridX1 = gridX + 1;
  11706. var gridY1 = gridY + 1;
  11707. var vertexCounter = 0;
  11708. var groupCount = 0;
  11709. var ix, iy;
  11710. var vector = new Vector3();
  11711. // generate vertices, normals and uvs
  11712. for ( iy = 0; iy < gridY1; iy ++ ) {
  11713. var y = iy * segmentHeight - heightHalf;
  11714. for ( ix = 0; ix < gridX1; ix ++ ) {
  11715. var x = ix * segmentWidth - widthHalf;
  11716. // set values to correct vector component
  11717. vector[ u ] = x * udir;
  11718. vector[ v ] = y * vdir;
  11719. vector[ w ] = depthHalf;
  11720. // now apply vector to vertex buffer
  11721. vertices.push( vector.x, vector.y, vector.z );
  11722. // set values to correct vector component
  11723. vector[ u ] = 0;
  11724. vector[ v ] = 0;
  11725. vector[ w ] = depth > 0 ? 1 : - 1;
  11726. // now apply vector to normal buffer
  11727. normals.push( vector.x, vector.y, vector.z );
  11728. // uvs
  11729. uvs.push( ix / gridX );
  11730. uvs.push( 1 - ( iy / gridY ) );
  11731. // counters
  11732. vertexCounter += 1;
  11733. }
  11734. }
  11735. // indices
  11736. // 1. you need three indices to draw a single face
  11737. // 2. a single segment consists of two faces
  11738. // 3. so we need to generate six (2*3) indices per segment
  11739. for ( iy = 0; iy < gridY; iy ++ ) {
  11740. for ( ix = 0; ix < gridX; ix ++ ) {
  11741. var a = numberOfVertices + ix + gridX1 * iy;
  11742. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  11743. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  11744. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  11745. // faces
  11746. indices.push( a, b, d );
  11747. indices.push( b, c, d );
  11748. // increase counter
  11749. groupCount += 6;
  11750. }
  11751. }
  11752. // add a group to the geometry. this will ensure multi material support
  11753. scope.addGroup( groupStart, groupCount, materialIndex );
  11754. // calculate new start value for groups
  11755. groupStart += groupCount;
  11756. // update total number of vertices
  11757. numberOfVertices += vertexCounter;
  11758. }
  11759. }
  11760. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  11761. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  11762. /**
  11763. * @author mrdoob / http://mrdoob.com/
  11764. * @author Mugen87 / https://github.com/Mugen87
  11765. */
  11766. // PlaneGeometry
  11767. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  11768. Geometry.call( this );
  11769. this.type = 'PlaneGeometry';
  11770. this.parameters = {
  11771. width: width,
  11772. height: height,
  11773. widthSegments: widthSegments,
  11774. heightSegments: heightSegments
  11775. };
  11776. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  11777. this.mergeVertices();
  11778. }
  11779. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  11780. PlaneGeometry.prototype.constructor = PlaneGeometry;
  11781. // PlaneBufferGeometry
  11782. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  11783. BufferGeometry.call( this );
  11784. this.type = 'PlaneBufferGeometry';
  11785. this.parameters = {
  11786. width: width,
  11787. height: height,
  11788. widthSegments: widthSegments,
  11789. heightSegments: heightSegments
  11790. };
  11791. width = width || 1;
  11792. height = height || 1;
  11793. var width_half = width / 2;
  11794. var height_half = height / 2;
  11795. var gridX = Math.floor( widthSegments ) || 1;
  11796. var gridY = Math.floor( heightSegments ) || 1;
  11797. var gridX1 = gridX + 1;
  11798. var gridY1 = gridY + 1;
  11799. var segment_width = width / gridX;
  11800. var segment_height = height / gridY;
  11801. var ix, iy;
  11802. // buffers
  11803. var indices = [];
  11804. var vertices = [];
  11805. var normals = [];
  11806. var uvs = [];
  11807. // generate vertices, normals and uvs
  11808. for ( iy = 0; iy < gridY1; iy ++ ) {
  11809. var y = iy * segment_height - height_half;
  11810. for ( ix = 0; ix < gridX1; ix ++ ) {
  11811. var x = ix * segment_width - width_half;
  11812. vertices.push( x, - y, 0 );
  11813. normals.push( 0, 0, 1 );
  11814. uvs.push( ix / gridX );
  11815. uvs.push( 1 - ( iy / gridY ) );
  11816. }
  11817. }
  11818. // indices
  11819. for ( iy = 0; iy < gridY; iy ++ ) {
  11820. for ( ix = 0; ix < gridX; ix ++ ) {
  11821. var a = ix + gridX1 * iy;
  11822. var b = ix + gridX1 * ( iy + 1 );
  11823. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  11824. var d = ( ix + 1 ) + gridX1 * iy;
  11825. // faces
  11826. indices.push( a, b, d );
  11827. indices.push( b, c, d );
  11828. }
  11829. }
  11830. // build geometry
  11831. this.setIndex( indices );
  11832. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11833. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11834. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11835. }
  11836. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  11837. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  11838. /**
  11839. * @author mrdoob / http://mrdoob.com/
  11840. * @author alteredq / http://alteredqualia.com/
  11841. */
  11842. var materialId = 0;
  11843. function Material() {
  11844. Object.defineProperty( this, 'id', { value: materialId ++ } );
  11845. this.uuid = _Math.generateUUID();
  11846. this.name = '';
  11847. this.type = 'Material';
  11848. this.fog = true;
  11849. this.lights = true;
  11850. this.blending = NormalBlending;
  11851. this.side = FrontSide;
  11852. this.flatShading = false;
  11853. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  11854. this.opacity = 1;
  11855. this.transparent = false;
  11856. this.blendSrc = SrcAlphaFactor;
  11857. this.blendDst = OneMinusSrcAlphaFactor;
  11858. this.blendEquation = AddEquation;
  11859. this.blendSrcAlpha = null;
  11860. this.blendDstAlpha = null;
  11861. this.blendEquationAlpha = null;
  11862. this.depthFunc = LessEqualDepth;
  11863. this.depthTest = true;
  11864. this.depthWrite = true;
  11865. this.clippingPlanes = null;
  11866. this.clipIntersection = false;
  11867. this.clipShadows = false;
  11868. this.shadowSide = null;
  11869. this.colorWrite = true;
  11870. this.precision = null; // override the renderer's default precision for this material
  11871. this.polygonOffset = false;
  11872. this.polygonOffsetFactor = 0;
  11873. this.polygonOffsetUnits = 0;
  11874. this.dithering = false;
  11875. this.alphaTest = 0;
  11876. this.premultipliedAlpha = false;
  11877. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  11878. this.visible = true;
  11879. this.userData = {};
  11880. this.needsUpdate = true;
  11881. }
  11882. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  11883. constructor: Material,
  11884. isMaterial: true,
  11885. onBeforeCompile: function () {},
  11886. setValues: function ( values ) {
  11887. if ( values === undefined ) return;
  11888. for ( var key in values ) {
  11889. var newValue = values[ key ];
  11890. if ( newValue === undefined ) {
  11891. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  11892. continue;
  11893. }
  11894. // for backward compatability if shading is set in the constructor
  11895. if ( key === 'shading' ) {
  11896. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  11897. this.flatShading = ( newValue === FlatShading ) ? true : false;
  11898. continue;
  11899. }
  11900. var currentValue = this[ key ];
  11901. if ( currentValue === undefined ) {
  11902. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  11903. continue;
  11904. }
  11905. if ( currentValue && currentValue.isColor ) {
  11906. currentValue.set( newValue );
  11907. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  11908. currentValue.copy( newValue );
  11909. } else if ( key === 'overdraw' ) {
  11910. // ensure overdraw is backwards-compatible with legacy boolean type
  11911. this[ key ] = Number( newValue );
  11912. } else {
  11913. this[ key ] = newValue;
  11914. }
  11915. }
  11916. },
  11917. toJSON: function ( meta ) {
  11918. var isRoot = ( meta === undefined || typeof meta === 'string' );
  11919. if ( isRoot ) {
  11920. meta = {
  11921. textures: {},
  11922. images: {}
  11923. };
  11924. }
  11925. var data = {
  11926. metadata: {
  11927. version: 4.5,
  11928. type: 'Material',
  11929. generator: 'Material.toJSON'
  11930. }
  11931. };
  11932. // standard Material serialization
  11933. data.uuid = this.uuid;
  11934. data.type = this.type;
  11935. if ( this.name !== '' ) data.name = this.name;
  11936. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  11937. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  11938. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  11939. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  11940. if ( this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  11941. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  11942. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  11943. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  11944. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  11945. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  11946. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  11947. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  11948. if ( this.bumpMap && this.bumpMap.isTexture ) {
  11949. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  11950. data.bumpScale = this.bumpScale;
  11951. }
  11952. if ( this.normalMap && this.normalMap.isTexture ) {
  11953. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  11954. data.normalScale = this.normalScale.toArray();
  11955. }
  11956. if ( this.displacementMap && this.displacementMap.isTexture ) {
  11957. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  11958. data.displacementScale = this.displacementScale;
  11959. data.displacementBias = this.displacementBias;
  11960. }
  11961. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  11962. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  11963. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  11964. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  11965. if ( this.envMap && this.envMap.isTexture ) {
  11966. data.envMap = this.envMap.toJSON( meta ).uuid;
  11967. data.reflectivity = this.reflectivity; // Scale behind envMap
  11968. }
  11969. if ( this.gradientMap && this.gradientMap.isTexture ) {
  11970. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  11971. }
  11972. if ( this.size !== undefined ) data.size = this.size;
  11973. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  11974. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  11975. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  11976. if ( this.side !== FrontSide ) data.side = this.side;
  11977. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  11978. if ( this.opacity < 1 ) data.opacity = this.opacity;
  11979. if ( this.transparent === true ) data.transparent = this.transparent;
  11980. data.depthFunc = this.depthFunc;
  11981. data.depthTest = this.depthTest;
  11982. data.depthWrite = this.depthWrite;
  11983. // rotation (SpriteMaterial)
  11984. if ( this.rotation !== 0 ) data.rotation = this.rotation;
  11985. if ( this.linewidth !== 1 ) data.linewidth = this.linewidth;
  11986. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  11987. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  11988. if ( this.scale !== undefined ) data.scale = this.scale;
  11989. if ( this.dithering === true ) data.dithering = true;
  11990. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  11991. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  11992. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  11993. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  11994. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  11995. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  11996. if ( this.morphTargets === true ) data.morphTargets = true;
  11997. if ( this.skinning === true ) data.skinning = true;
  11998. if ( this.visible === false ) data.visible = false;
  11999. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  12000. // TODO: Copied from Object3D.toJSON
  12001. function extractFromCache( cache ) {
  12002. var values = [];
  12003. for ( var key in cache ) {
  12004. var data = cache[ key ];
  12005. delete data.metadata;
  12006. values.push( data );
  12007. }
  12008. return values;
  12009. }
  12010. if ( isRoot ) {
  12011. var textures = extractFromCache( meta.textures );
  12012. var images = extractFromCache( meta.images );
  12013. if ( textures.length > 0 ) data.textures = textures;
  12014. if ( images.length > 0 ) data.images = images;
  12015. }
  12016. return data;
  12017. },
  12018. clone: function () {
  12019. return new this.constructor().copy( this );
  12020. },
  12021. copy: function ( source ) {
  12022. this.name = source.name;
  12023. this.fog = source.fog;
  12024. this.lights = source.lights;
  12025. this.blending = source.blending;
  12026. this.side = source.side;
  12027. this.flatShading = source.flatShading;
  12028. this.vertexColors = source.vertexColors;
  12029. this.opacity = source.opacity;
  12030. this.transparent = source.transparent;
  12031. this.blendSrc = source.blendSrc;
  12032. this.blendDst = source.blendDst;
  12033. this.blendEquation = source.blendEquation;
  12034. this.blendSrcAlpha = source.blendSrcAlpha;
  12035. this.blendDstAlpha = source.blendDstAlpha;
  12036. this.blendEquationAlpha = source.blendEquationAlpha;
  12037. this.depthFunc = source.depthFunc;
  12038. this.depthTest = source.depthTest;
  12039. this.depthWrite = source.depthWrite;
  12040. this.colorWrite = source.colorWrite;
  12041. this.precision = source.precision;
  12042. this.polygonOffset = source.polygonOffset;
  12043. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12044. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12045. this.dithering = source.dithering;
  12046. this.alphaTest = source.alphaTest;
  12047. this.premultipliedAlpha = source.premultipliedAlpha;
  12048. this.overdraw = source.overdraw;
  12049. this.visible = source.visible;
  12050. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  12051. this.clipShadows = source.clipShadows;
  12052. this.clipIntersection = source.clipIntersection;
  12053. var srcPlanes = source.clippingPlanes,
  12054. dstPlanes = null;
  12055. if ( srcPlanes !== null ) {
  12056. var n = srcPlanes.length;
  12057. dstPlanes = new Array( n );
  12058. for ( var i = 0; i !== n; ++ i )
  12059. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12060. }
  12061. this.clippingPlanes = dstPlanes;
  12062. this.shadowSide = source.shadowSide;
  12063. return this;
  12064. },
  12065. dispose: function () {
  12066. this.dispatchEvent( { type: 'dispose' } );
  12067. }
  12068. } );
  12069. /**
  12070. * @author mrdoob / http://mrdoob.com/
  12071. * @author alteredq / http://alteredqualia.com/
  12072. *
  12073. * parameters = {
  12074. * color: <hex>,
  12075. * opacity: <float>,
  12076. * map: new THREE.Texture( <Image> ),
  12077. *
  12078. * lightMap: new THREE.Texture( <Image> ),
  12079. * lightMapIntensity: <float>
  12080. *
  12081. * aoMap: new THREE.Texture( <Image> ),
  12082. * aoMapIntensity: <float>
  12083. *
  12084. * specularMap: new THREE.Texture( <Image> ),
  12085. *
  12086. * alphaMap: new THREE.Texture( <Image> ),
  12087. *
  12088. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  12089. * combine: THREE.Multiply,
  12090. * reflectivity: <float>,
  12091. * refractionRatio: <float>,
  12092. *
  12093. * depthTest: <bool>,
  12094. * depthWrite: <bool>,
  12095. *
  12096. * wireframe: <boolean>,
  12097. * wireframeLinewidth: <float>,
  12098. *
  12099. * skinning: <bool>,
  12100. * morphTargets: <bool>
  12101. * }
  12102. */
  12103. function MeshBasicMaterial( parameters ) {
  12104. Material.call( this );
  12105. this.type = 'MeshBasicMaterial';
  12106. this.color = new Color( 0xffffff ); // emissive
  12107. this.map = null;
  12108. this.lightMap = null;
  12109. this.lightMapIntensity = 1.0;
  12110. this.aoMap = null;
  12111. this.aoMapIntensity = 1.0;
  12112. this.specularMap = null;
  12113. this.alphaMap = null;
  12114. this.envMap = null;
  12115. this.combine = MultiplyOperation;
  12116. this.reflectivity = 1;
  12117. this.refractionRatio = 0.98;
  12118. this.wireframe = false;
  12119. this.wireframeLinewidth = 1;
  12120. this.wireframeLinecap = 'round';
  12121. this.wireframeLinejoin = 'round';
  12122. this.skinning = false;
  12123. this.morphTargets = false;
  12124. this.lights = false;
  12125. this.setValues( parameters );
  12126. }
  12127. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  12128. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  12129. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  12130. MeshBasicMaterial.prototype.copy = function ( source ) {
  12131. Material.prototype.copy.call( this, source );
  12132. this.color.copy( source.color );
  12133. this.map = source.map;
  12134. this.lightMap = source.lightMap;
  12135. this.lightMapIntensity = source.lightMapIntensity;
  12136. this.aoMap = source.aoMap;
  12137. this.aoMapIntensity = source.aoMapIntensity;
  12138. this.specularMap = source.specularMap;
  12139. this.alphaMap = source.alphaMap;
  12140. this.envMap = source.envMap;
  12141. this.combine = source.combine;
  12142. this.reflectivity = source.reflectivity;
  12143. this.refractionRatio = source.refractionRatio;
  12144. this.wireframe = source.wireframe;
  12145. this.wireframeLinewidth = source.wireframeLinewidth;
  12146. this.wireframeLinecap = source.wireframeLinecap;
  12147. this.wireframeLinejoin = source.wireframeLinejoin;
  12148. this.skinning = source.skinning;
  12149. this.morphTargets = source.morphTargets;
  12150. return this;
  12151. };
  12152. /**
  12153. * @author alteredq / http://alteredqualia.com/
  12154. *
  12155. * parameters = {
  12156. * defines: { "label" : "value" },
  12157. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  12158. *
  12159. * fragmentShader: <string>,
  12160. * vertexShader: <string>,
  12161. *
  12162. * wireframe: <boolean>,
  12163. * wireframeLinewidth: <float>,
  12164. *
  12165. * lights: <bool>,
  12166. *
  12167. * skinning: <bool>,
  12168. * morphTargets: <bool>,
  12169. * morphNormals: <bool>
  12170. * }
  12171. */
  12172. function ShaderMaterial( parameters ) {
  12173. Material.call( this );
  12174. this.type = 'ShaderMaterial';
  12175. this.defines = {};
  12176. this.uniforms = {};
  12177. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  12178. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  12179. this.linewidth = 1;
  12180. this.wireframe = false;
  12181. this.wireframeLinewidth = 1;
  12182. this.fog = false; // set to use scene fog
  12183. this.lights = false; // set to use scene lights
  12184. this.clipping = false; // set to use user-defined clipping planes
  12185. this.skinning = false; // set to use skinning attribute streams
  12186. this.morphTargets = false; // set to use morph targets
  12187. this.morphNormals = false; // set to use morph normals
  12188. this.extensions = {
  12189. derivatives: false, // set to use derivatives
  12190. fragDepth: false, // set to use fragment depth values
  12191. drawBuffers: false, // set to use draw buffers
  12192. shaderTextureLOD: false // set to use shader texture LOD
  12193. };
  12194. // When rendered geometry doesn't include these attributes but the material does,
  12195. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12196. this.defaultAttributeValues = {
  12197. 'color': [ 1, 1, 1 ],
  12198. 'uv': [ 0, 0 ],
  12199. 'uv2': [ 0, 0 ]
  12200. };
  12201. this.index0AttributeName = undefined;
  12202. this.uniformsNeedUpdate = false;
  12203. if ( parameters !== undefined ) {
  12204. if ( parameters.attributes !== undefined ) {
  12205. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  12206. }
  12207. this.setValues( parameters );
  12208. }
  12209. }
  12210. ShaderMaterial.prototype = Object.create( Material.prototype );
  12211. ShaderMaterial.prototype.constructor = ShaderMaterial;
  12212. ShaderMaterial.prototype.isShaderMaterial = true;
  12213. ShaderMaterial.prototype.copy = function ( source ) {
  12214. Material.prototype.copy.call( this, source );
  12215. this.fragmentShader = source.fragmentShader;
  12216. this.vertexShader = source.vertexShader;
  12217. this.uniforms = UniformsUtils.clone( source.uniforms );
  12218. this.defines = Object.assign( {}, source.defines );
  12219. this.wireframe = source.wireframe;
  12220. this.wireframeLinewidth = source.wireframeLinewidth;
  12221. this.lights = source.lights;
  12222. this.clipping = source.clipping;
  12223. this.skinning = source.skinning;
  12224. this.morphTargets = source.morphTargets;
  12225. this.morphNormals = source.morphNormals;
  12226. this.extensions = source.extensions;
  12227. return this;
  12228. };
  12229. ShaderMaterial.prototype.toJSON = function ( meta ) {
  12230. var data = Material.prototype.toJSON.call( this, meta );
  12231. data.uniforms = this.uniforms;
  12232. data.vertexShader = this.vertexShader;
  12233. data.fragmentShader = this.fragmentShader;
  12234. return data;
  12235. };
  12236. /**
  12237. * @author bhouston / http://clara.io
  12238. */
  12239. function Ray( origin, direction ) {
  12240. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  12241. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  12242. }
  12243. Object.assign( Ray.prototype, {
  12244. set: function ( origin, direction ) {
  12245. this.origin.copy( origin );
  12246. this.direction.copy( direction );
  12247. return this;
  12248. },
  12249. clone: function () {
  12250. return new this.constructor().copy( this );
  12251. },
  12252. copy: function ( ray ) {
  12253. this.origin.copy( ray.origin );
  12254. this.direction.copy( ray.direction );
  12255. return this;
  12256. },
  12257. at: function ( t, target ) {
  12258. if ( target === undefined ) {
  12259. console.warn( 'THREE.Ray: .at() target is now required' );
  12260. target = new Vector3();
  12261. }
  12262. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  12263. },
  12264. lookAt: function ( v ) {
  12265. this.direction.copy( v ).sub( this.origin ).normalize();
  12266. return this;
  12267. },
  12268. recast: function () {
  12269. var v1 = new Vector3();
  12270. return function recast( t ) {
  12271. this.origin.copy( this.at( t, v1 ) );
  12272. return this;
  12273. };
  12274. }(),
  12275. closestPointToPoint: function ( point, target ) {
  12276. if ( target === undefined ) {
  12277. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  12278. target = new Vector3();
  12279. }
  12280. target.subVectors( point, this.origin );
  12281. var directionDistance = target.dot( this.direction );
  12282. if ( directionDistance < 0 ) {
  12283. return target.copy( this.origin );
  12284. }
  12285. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  12286. },
  12287. distanceToPoint: function ( point ) {
  12288. return Math.sqrt( this.distanceSqToPoint( point ) );
  12289. },
  12290. distanceSqToPoint: function () {
  12291. var v1 = new Vector3();
  12292. return function distanceSqToPoint( point ) {
  12293. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  12294. // point behind the ray
  12295. if ( directionDistance < 0 ) {
  12296. return this.origin.distanceToSquared( point );
  12297. }
  12298. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  12299. return v1.distanceToSquared( point );
  12300. };
  12301. }(),
  12302. distanceSqToSegment: function () {
  12303. var segCenter = new Vector3();
  12304. var segDir = new Vector3();
  12305. var diff = new Vector3();
  12306. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  12307. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  12308. // It returns the min distance between the ray and the segment
  12309. // defined by v0 and v1
  12310. // It can also set two optional targets :
  12311. // - The closest point on the ray
  12312. // - The closest point on the segment
  12313. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  12314. segDir.copy( v1 ).sub( v0 ).normalize();
  12315. diff.copy( this.origin ).sub( segCenter );
  12316. var segExtent = v0.distanceTo( v1 ) * 0.5;
  12317. var a01 = - this.direction.dot( segDir );
  12318. var b0 = diff.dot( this.direction );
  12319. var b1 = - diff.dot( segDir );
  12320. var c = diff.lengthSq();
  12321. var det = Math.abs( 1 - a01 * a01 );
  12322. var s0, s1, sqrDist, extDet;
  12323. if ( det > 0 ) {
  12324. // The ray and segment are not parallel.
  12325. s0 = a01 * b1 - b0;
  12326. s1 = a01 * b0 - b1;
  12327. extDet = segExtent * det;
  12328. if ( s0 >= 0 ) {
  12329. if ( s1 >= - extDet ) {
  12330. if ( s1 <= extDet ) {
  12331. // region 0
  12332. // Minimum at interior points of ray and segment.
  12333. var invDet = 1 / det;
  12334. s0 *= invDet;
  12335. s1 *= invDet;
  12336. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  12337. } else {
  12338. // region 1
  12339. s1 = segExtent;
  12340. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  12341. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12342. }
  12343. } else {
  12344. // region 5
  12345. s1 = - segExtent;
  12346. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  12347. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12348. }
  12349. } else {
  12350. if ( s1 <= - extDet ) {
  12351. // region 4
  12352. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  12353. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  12354. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12355. } else if ( s1 <= extDet ) {
  12356. // region 3
  12357. s0 = 0;
  12358. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  12359. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  12360. } else {
  12361. // region 2
  12362. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  12363. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  12364. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12365. }
  12366. }
  12367. } else {
  12368. // Ray and segment are parallel.
  12369. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  12370. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  12371. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12372. }
  12373. if ( optionalPointOnRay ) {
  12374. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  12375. }
  12376. if ( optionalPointOnSegment ) {
  12377. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  12378. }
  12379. return sqrDist;
  12380. };
  12381. }(),
  12382. intersectSphere: function () {
  12383. var v1 = new Vector3();
  12384. return function intersectSphere( sphere, target ) {
  12385. v1.subVectors( sphere.center, this.origin );
  12386. var tca = v1.dot( this.direction );
  12387. var d2 = v1.dot( v1 ) - tca * tca;
  12388. var radius2 = sphere.radius * sphere.radius;
  12389. if ( d2 > radius2 ) return null;
  12390. var thc = Math.sqrt( radius2 - d2 );
  12391. // t0 = first intersect point - entrance on front of sphere
  12392. var t0 = tca - thc;
  12393. // t1 = second intersect point - exit point on back of sphere
  12394. var t1 = tca + thc;
  12395. // test to see if both t0 and t1 are behind the ray - if so, return null
  12396. if ( t0 < 0 && t1 < 0 ) return null;
  12397. // test to see if t0 is behind the ray:
  12398. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  12399. // in order to always return an intersect point that is in front of the ray.
  12400. if ( t0 < 0 ) return this.at( t1, target );
  12401. // else t0 is in front of the ray, so return the first collision point scaled by t0
  12402. return this.at( t0, target );
  12403. };
  12404. }(),
  12405. intersectsSphere: function ( sphere ) {
  12406. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  12407. },
  12408. distanceToPlane: function ( plane ) {
  12409. var denominator = plane.normal.dot( this.direction );
  12410. if ( denominator === 0 ) {
  12411. // line is coplanar, return origin
  12412. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  12413. return 0;
  12414. }
  12415. // Null is preferable to undefined since undefined means.... it is undefined
  12416. return null;
  12417. }
  12418. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  12419. // Return if the ray never intersects the plane
  12420. return t >= 0 ? t : null;
  12421. },
  12422. intersectPlane: function ( plane, target ) {
  12423. var t = this.distanceToPlane( plane );
  12424. if ( t === null ) {
  12425. return null;
  12426. }
  12427. return this.at( t, target );
  12428. },
  12429. intersectsPlane: function ( plane ) {
  12430. // check if the ray lies on the plane first
  12431. var distToPoint = plane.distanceToPoint( this.origin );
  12432. if ( distToPoint === 0 ) {
  12433. return true;
  12434. }
  12435. var denominator = plane.normal.dot( this.direction );
  12436. if ( denominator * distToPoint < 0 ) {
  12437. return true;
  12438. }
  12439. // ray origin is behind the plane (and is pointing behind it)
  12440. return false;
  12441. },
  12442. intersectBox: function ( box, target ) {
  12443. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  12444. var invdirx = 1 / this.direction.x,
  12445. invdiry = 1 / this.direction.y,
  12446. invdirz = 1 / this.direction.z;
  12447. var origin = this.origin;
  12448. if ( invdirx >= 0 ) {
  12449. tmin = ( box.min.x - origin.x ) * invdirx;
  12450. tmax = ( box.max.x - origin.x ) * invdirx;
  12451. } else {
  12452. tmin = ( box.max.x - origin.x ) * invdirx;
  12453. tmax = ( box.min.x - origin.x ) * invdirx;
  12454. }
  12455. if ( invdiry >= 0 ) {
  12456. tymin = ( box.min.y - origin.y ) * invdiry;
  12457. tymax = ( box.max.y - origin.y ) * invdiry;
  12458. } else {
  12459. tymin = ( box.max.y - origin.y ) * invdiry;
  12460. tymax = ( box.min.y - origin.y ) * invdiry;
  12461. }
  12462. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  12463. // These lines also handle the case where tmin or tmax is NaN
  12464. // (result of 0 * Infinity). x !== x returns true if x is NaN
  12465. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  12466. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  12467. if ( invdirz >= 0 ) {
  12468. tzmin = ( box.min.z - origin.z ) * invdirz;
  12469. tzmax = ( box.max.z - origin.z ) * invdirz;
  12470. } else {
  12471. tzmin = ( box.max.z - origin.z ) * invdirz;
  12472. tzmax = ( box.min.z - origin.z ) * invdirz;
  12473. }
  12474. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  12475. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  12476. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  12477. //return point closest to the ray (positive side)
  12478. if ( tmax < 0 ) return null;
  12479. return this.at( tmin >= 0 ? tmin : tmax, target );
  12480. },
  12481. intersectsBox: ( function () {
  12482. var v = new Vector3();
  12483. return function intersectsBox( box ) {
  12484. return this.intersectBox( box, v ) !== null;
  12485. };
  12486. } )(),
  12487. intersectTriangle: function () {
  12488. // Compute the offset origin, edges, and normal.
  12489. var diff = new Vector3();
  12490. var edge1 = new Vector3();
  12491. var edge2 = new Vector3();
  12492. var normal = new Vector3();
  12493. return function intersectTriangle( a, b, c, backfaceCulling, target ) {
  12494. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  12495. edge1.subVectors( b, a );
  12496. edge2.subVectors( c, a );
  12497. normal.crossVectors( edge1, edge2 );
  12498. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  12499. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  12500. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  12501. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  12502. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  12503. var DdN = this.direction.dot( normal );
  12504. var sign;
  12505. if ( DdN > 0 ) {
  12506. if ( backfaceCulling ) return null;
  12507. sign = 1;
  12508. } else if ( DdN < 0 ) {
  12509. sign = - 1;
  12510. DdN = - DdN;
  12511. } else {
  12512. return null;
  12513. }
  12514. diff.subVectors( this.origin, a );
  12515. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  12516. // b1 < 0, no intersection
  12517. if ( DdQxE2 < 0 ) {
  12518. return null;
  12519. }
  12520. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  12521. // b2 < 0, no intersection
  12522. if ( DdE1xQ < 0 ) {
  12523. return null;
  12524. }
  12525. // b1+b2 > 1, no intersection
  12526. if ( DdQxE2 + DdE1xQ > DdN ) {
  12527. return null;
  12528. }
  12529. // Line intersects triangle, check if ray does.
  12530. var QdN = - sign * diff.dot( normal );
  12531. // t < 0, no intersection
  12532. if ( QdN < 0 ) {
  12533. return null;
  12534. }
  12535. // Ray intersects triangle.
  12536. return this.at( QdN / DdN, target );
  12537. };
  12538. }(),
  12539. applyMatrix4: function ( matrix4 ) {
  12540. this.origin.applyMatrix4( matrix4 );
  12541. this.direction.transformDirection( matrix4 );
  12542. return this;
  12543. },
  12544. equals: function ( ray ) {
  12545. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  12546. }
  12547. } );
  12548. /**
  12549. * @author bhouston / http://clara.io
  12550. */
  12551. function Line3( start, end ) {
  12552. this.start = ( start !== undefined ) ? start : new Vector3();
  12553. this.end = ( end !== undefined ) ? end : new Vector3();
  12554. }
  12555. Object.assign( Line3.prototype, {
  12556. set: function ( start, end ) {
  12557. this.start.copy( start );
  12558. this.end.copy( end );
  12559. return this;
  12560. },
  12561. clone: function () {
  12562. return new this.constructor().copy( this );
  12563. },
  12564. copy: function ( line ) {
  12565. this.start.copy( line.start );
  12566. this.end.copy( line.end );
  12567. return this;
  12568. },
  12569. getCenter: function ( target ) {
  12570. if ( target === undefined ) {
  12571. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  12572. target = new Vector3();
  12573. }
  12574. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  12575. },
  12576. delta: function ( target ) {
  12577. if ( target === undefined ) {
  12578. console.warn( 'THREE.Line3: .delta() target is now required' );
  12579. target = new Vector3();
  12580. }
  12581. return target.subVectors( this.end, this.start );
  12582. },
  12583. distanceSq: function () {
  12584. return this.start.distanceToSquared( this.end );
  12585. },
  12586. distance: function () {
  12587. return this.start.distanceTo( this.end );
  12588. },
  12589. at: function ( t, target ) {
  12590. if ( target === undefined ) {
  12591. console.warn( 'THREE.Line3: .at() target is now required' );
  12592. target = new Vector3();
  12593. }
  12594. return this.delta( target ).multiplyScalar( t ).add( this.start );
  12595. },
  12596. closestPointToPointParameter: function () {
  12597. var startP = new Vector3();
  12598. var startEnd = new Vector3();
  12599. return function closestPointToPointParameter( point, clampToLine ) {
  12600. startP.subVectors( point, this.start );
  12601. startEnd.subVectors( this.end, this.start );
  12602. var startEnd2 = startEnd.dot( startEnd );
  12603. var startEnd_startP = startEnd.dot( startP );
  12604. var t = startEnd_startP / startEnd2;
  12605. if ( clampToLine ) {
  12606. t = _Math.clamp( t, 0, 1 );
  12607. }
  12608. return t;
  12609. };
  12610. }(),
  12611. closestPointToPoint: function ( point, clampToLine, target ) {
  12612. var t = this.closestPointToPointParameter( point, clampToLine );
  12613. if ( target === undefined ) {
  12614. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  12615. target = new Vector3();
  12616. }
  12617. return this.delta( target ).multiplyScalar( t ).add( this.start );
  12618. },
  12619. applyMatrix4: function ( matrix ) {
  12620. this.start.applyMatrix4( matrix );
  12621. this.end.applyMatrix4( matrix );
  12622. return this;
  12623. },
  12624. equals: function ( line ) {
  12625. return line.start.equals( this.start ) && line.end.equals( this.end );
  12626. }
  12627. } );
  12628. /**
  12629. * @author bhouston / http://clara.io
  12630. * @author mrdoob / http://mrdoob.com/
  12631. */
  12632. function Triangle( a, b, c ) {
  12633. this.a = ( a !== undefined ) ? a : new Vector3();
  12634. this.b = ( b !== undefined ) ? b : new Vector3();
  12635. this.c = ( c !== undefined ) ? c : new Vector3();
  12636. }
  12637. Object.assign( Triangle, {
  12638. getNormal: function () {
  12639. var v0 = new Vector3();
  12640. return function getNormal( a, b, c, target ) {
  12641. if ( target === undefined ) {
  12642. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  12643. target = new Vector3();
  12644. }
  12645. target.subVectors( c, b );
  12646. v0.subVectors( a, b );
  12647. target.cross( v0 );
  12648. var targetLengthSq = target.lengthSq();
  12649. if ( targetLengthSq > 0 ) {
  12650. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  12651. }
  12652. return target.set( 0, 0, 0 );
  12653. };
  12654. }(),
  12655. // static/instance method to calculate barycentric coordinates
  12656. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  12657. getBarycoord: function () {
  12658. var v0 = new Vector3();
  12659. var v1 = new Vector3();
  12660. var v2 = new Vector3();
  12661. return function getBarycoord( point, a, b, c, target ) {
  12662. v0.subVectors( c, a );
  12663. v1.subVectors( b, a );
  12664. v2.subVectors( point, a );
  12665. var dot00 = v0.dot( v0 );
  12666. var dot01 = v0.dot( v1 );
  12667. var dot02 = v0.dot( v2 );
  12668. var dot11 = v1.dot( v1 );
  12669. var dot12 = v1.dot( v2 );
  12670. var denom = ( dot00 * dot11 - dot01 * dot01 );
  12671. if ( target === undefined ) {
  12672. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  12673. target = new Vector3();
  12674. }
  12675. // collinear or singular triangle
  12676. if ( denom === 0 ) {
  12677. // arbitrary location outside of triangle?
  12678. // not sure if this is the best idea, maybe should be returning undefined
  12679. return target.set( - 2, - 1, - 1 );
  12680. }
  12681. var invDenom = 1 / denom;
  12682. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  12683. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  12684. // barycentric coordinates must always sum to 1
  12685. return target.set( 1 - u - v, v, u );
  12686. };
  12687. }(),
  12688. containsPoint: function () {
  12689. var v1 = new Vector3();
  12690. return function containsPoint( point, a, b, c ) {
  12691. Triangle.getBarycoord( point, a, b, c, v1 );
  12692. return ( v1.x >= 0 ) && ( v1.y >= 0 ) && ( ( v1.x + v1.y ) <= 1 );
  12693. };
  12694. }()
  12695. } );
  12696. Object.assign( Triangle.prototype, {
  12697. set: function ( a, b, c ) {
  12698. this.a.copy( a );
  12699. this.b.copy( b );
  12700. this.c.copy( c );
  12701. return this;
  12702. },
  12703. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  12704. this.a.copy( points[ i0 ] );
  12705. this.b.copy( points[ i1 ] );
  12706. this.c.copy( points[ i2 ] );
  12707. return this;
  12708. },
  12709. clone: function () {
  12710. return new this.constructor().copy( this );
  12711. },
  12712. copy: function ( triangle ) {
  12713. this.a.copy( triangle.a );
  12714. this.b.copy( triangle.b );
  12715. this.c.copy( triangle.c );
  12716. return this;
  12717. },
  12718. getArea: function () {
  12719. var v0 = new Vector3();
  12720. var v1 = new Vector3();
  12721. return function getArea() {
  12722. v0.subVectors( this.c, this.b );
  12723. v1.subVectors( this.a, this.b );
  12724. return v0.cross( v1 ).length() * 0.5;
  12725. };
  12726. }(),
  12727. getMidpoint: function ( target ) {
  12728. if ( target === undefined ) {
  12729. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  12730. target = new Vector3();
  12731. }
  12732. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  12733. },
  12734. getNormal: function ( target ) {
  12735. return Triangle.getNormal( this.a, this.b, this.c, target );
  12736. },
  12737. getPlane: function ( target ) {
  12738. if ( target === undefined ) {
  12739. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  12740. target = new Vector3();
  12741. }
  12742. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  12743. },
  12744. getBarycoord: function ( point, target ) {
  12745. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  12746. },
  12747. containsPoint: function ( point ) {
  12748. return Triangle.containsPoint( point, this.a, this.b, this.c );
  12749. },
  12750. intersectsBox: function ( box ) {
  12751. return box.intersectsTriangle( this );
  12752. },
  12753. closestPointToPoint: function () {
  12754. var plane = new Plane();
  12755. var edgeList = [ new Line3(), new Line3(), new Line3() ];
  12756. var projectedPoint = new Vector3();
  12757. var closestPoint = new Vector3();
  12758. return function closestPointToPoint( point, target ) {
  12759. if ( target === undefined ) {
  12760. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  12761. target = new Vector3();
  12762. }
  12763. var minDistance = Infinity;
  12764. // project the point onto the plane of the triangle
  12765. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  12766. plane.projectPoint( point, projectedPoint );
  12767. // check if the projection lies within the triangle
  12768. if ( this.containsPoint( projectedPoint ) === true ) {
  12769. // if so, this is the closest point
  12770. target.copy( projectedPoint );
  12771. } else {
  12772. // if not, the point falls outside the triangle. the target is the closest point to the triangle's edges or vertices
  12773. edgeList[ 0 ].set( this.a, this.b );
  12774. edgeList[ 1 ].set( this.b, this.c );
  12775. edgeList[ 2 ].set( this.c, this.a );
  12776. for ( var i = 0; i < edgeList.length; i ++ ) {
  12777. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  12778. var distance = projectedPoint.distanceToSquared( closestPoint );
  12779. if ( distance < minDistance ) {
  12780. minDistance = distance;
  12781. target.copy( closestPoint );
  12782. }
  12783. }
  12784. }
  12785. return target;
  12786. };
  12787. }(),
  12788. equals: function ( triangle ) {
  12789. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  12790. }
  12791. } );
  12792. /**
  12793. * @author mrdoob / http://mrdoob.com/
  12794. * @author alteredq / http://alteredqualia.com/
  12795. * @author mikael emtinger / http://gomo.se/
  12796. * @author jonobr1 / http://jonobr1.com/
  12797. */
  12798. function Mesh( geometry, material ) {
  12799. Object3D.call( this );
  12800. this.type = 'Mesh';
  12801. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  12802. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  12803. this.drawMode = TrianglesDrawMode;
  12804. this.updateMorphTargets();
  12805. }
  12806. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  12807. constructor: Mesh,
  12808. isMesh: true,
  12809. setDrawMode: function ( value ) {
  12810. this.drawMode = value;
  12811. },
  12812. copy: function ( source ) {
  12813. Object3D.prototype.copy.call( this, source );
  12814. this.drawMode = source.drawMode;
  12815. if ( source.morphTargetInfluences !== undefined ) {
  12816. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  12817. }
  12818. if ( source.morphTargetDictionary !== undefined ) {
  12819. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  12820. }
  12821. return this;
  12822. },
  12823. updateMorphTargets: function () {
  12824. var geometry = this.geometry;
  12825. var m, ml, name;
  12826. if ( geometry.isBufferGeometry ) {
  12827. var morphAttributes = geometry.morphAttributes;
  12828. var keys = Object.keys( morphAttributes );
  12829. if ( keys.length > 0 ) {
  12830. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  12831. if ( morphAttribute !== undefined ) {
  12832. this.morphTargetInfluences = [];
  12833. this.morphTargetDictionary = {};
  12834. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  12835. name = morphAttribute[ m ].name || String( m );
  12836. this.morphTargetInfluences.push( 0 );
  12837. this.morphTargetDictionary[ name ] = m;
  12838. }
  12839. }
  12840. }
  12841. } else {
  12842. var morphTargets = geometry.morphTargets;
  12843. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  12844. this.morphTargetInfluences = [];
  12845. this.morphTargetDictionary = {};
  12846. for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  12847. name = morphTargets[ m ].name || String( m );
  12848. this.morphTargetInfluences.push( 0 );
  12849. this.morphTargetDictionary[ name ] = m;
  12850. }
  12851. }
  12852. }
  12853. },
  12854. raycast: ( function () {
  12855. var inverseMatrix = new Matrix4();
  12856. var ray = new Ray();
  12857. var sphere = new Sphere();
  12858. var vA = new Vector3();
  12859. var vB = new Vector3();
  12860. var vC = new Vector3();
  12861. var tempA = new Vector3();
  12862. var tempB = new Vector3();
  12863. var tempC = new Vector3();
  12864. var uvA = new Vector2();
  12865. var uvB = new Vector2();
  12866. var uvC = new Vector2();
  12867. var barycoord = new Vector3();
  12868. var intersectionPoint = new Vector3();
  12869. var intersectionPointWorld = new Vector3();
  12870. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  12871. Triangle.getBarycoord( point, p1, p2, p3, barycoord );
  12872. uv1.multiplyScalar( barycoord.x );
  12873. uv2.multiplyScalar( barycoord.y );
  12874. uv3.multiplyScalar( barycoord.z );
  12875. uv1.add( uv2 ).add( uv3 );
  12876. return uv1.clone();
  12877. }
  12878. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  12879. var intersect;
  12880. if ( material.side === BackSide ) {
  12881. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12882. } else {
  12883. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  12884. }
  12885. if ( intersect === null ) return null;
  12886. intersectionPointWorld.copy( point );
  12887. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12888. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  12889. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  12890. return {
  12891. distance: distance,
  12892. point: intersectionPointWorld.clone(),
  12893. object: object
  12894. };
  12895. }
  12896. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  12897. vA.fromBufferAttribute( position, a );
  12898. vB.fromBufferAttribute( position, b );
  12899. vC.fromBufferAttribute( position, c );
  12900. var intersection = checkIntersection( object, object.material, raycaster, ray, vA, vB, vC, intersectionPoint );
  12901. if ( intersection ) {
  12902. if ( uv ) {
  12903. uvA.fromBufferAttribute( uv, a );
  12904. uvB.fromBufferAttribute( uv, b );
  12905. uvC.fromBufferAttribute( uv, c );
  12906. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  12907. }
  12908. var face = new Face3( a, b, c );
  12909. Triangle.getNormal( vA, vB, vC, face.normal );
  12910. intersection.face = face;
  12911. intersection.faceIndex = a;
  12912. }
  12913. return intersection;
  12914. }
  12915. return function raycast( raycaster, intersects ) {
  12916. var geometry = this.geometry;
  12917. var material = this.material;
  12918. var matrixWorld = this.matrixWorld;
  12919. if ( material === undefined ) return;
  12920. // Checking boundingSphere distance to ray
  12921. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12922. sphere.copy( geometry.boundingSphere );
  12923. sphere.applyMatrix4( matrixWorld );
  12924. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  12925. //
  12926. inverseMatrix.getInverse( matrixWorld );
  12927. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12928. // Check boundingBox before continuing
  12929. if ( geometry.boundingBox !== null ) {
  12930. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  12931. }
  12932. var intersection;
  12933. if ( geometry.isBufferGeometry ) {
  12934. var a, b, c;
  12935. var index = geometry.index;
  12936. var position = geometry.attributes.position;
  12937. var uv = geometry.attributes.uv;
  12938. var i, l;
  12939. if ( index !== null ) {
  12940. // indexed buffer geometry
  12941. for ( i = 0, l = index.count; i < l; i += 3 ) {
  12942. a = index.getX( i );
  12943. b = index.getX( i + 1 );
  12944. c = index.getX( i + 2 );
  12945. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  12946. if ( intersection ) {
  12947. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  12948. intersects.push( intersection );
  12949. }
  12950. }
  12951. } else if ( position !== undefined ) {
  12952. // non-indexed buffer geometry
  12953. for ( i = 0, l = position.count; i < l; i += 3 ) {
  12954. a = i;
  12955. b = i + 1;
  12956. c = i + 2;
  12957. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  12958. if ( intersection ) intersects.push( intersection );
  12959. }
  12960. }
  12961. } else if ( geometry.isGeometry ) {
  12962. var fvA, fvB, fvC;
  12963. var isMultiMaterial = Array.isArray( material );
  12964. var vertices = geometry.vertices;
  12965. var faces = geometry.faces;
  12966. var uvs;
  12967. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  12968. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  12969. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  12970. var face = faces[ f ];
  12971. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  12972. if ( faceMaterial === undefined ) continue;
  12973. fvA = vertices[ face.a ];
  12974. fvB = vertices[ face.b ];
  12975. fvC = vertices[ face.c ];
  12976. if ( faceMaterial.morphTargets === true ) {
  12977. var morphTargets = geometry.morphTargets;
  12978. var morphInfluences = this.morphTargetInfluences;
  12979. vA.set( 0, 0, 0 );
  12980. vB.set( 0, 0, 0 );
  12981. vC.set( 0, 0, 0 );
  12982. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  12983. var influence = morphInfluences[ t ];
  12984. if ( influence === 0 ) continue;
  12985. var targets = morphTargets[ t ].vertices;
  12986. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  12987. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  12988. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  12989. }
  12990. vA.add( fvA );
  12991. vB.add( fvB );
  12992. vC.add( fvC );
  12993. fvA = vA;
  12994. fvB = vB;
  12995. fvC = vC;
  12996. }
  12997. intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  12998. if ( intersection ) {
  12999. if ( uvs && uvs[ f ] ) {
  13000. var uvs_f = uvs[ f ];
  13001. uvA.copy( uvs_f[ 0 ] );
  13002. uvB.copy( uvs_f[ 1 ] );
  13003. uvC.copy( uvs_f[ 2 ] );
  13004. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  13005. }
  13006. intersection.face = face;
  13007. intersection.faceIndex = f;
  13008. intersects.push( intersection );
  13009. }
  13010. }
  13011. }
  13012. };
  13013. }() ),
  13014. clone: function () {
  13015. return new this.constructor( this.geometry, this.material ).copy( this );
  13016. }
  13017. } );
  13018. /**
  13019. * @author mrdoob / http://mrdoob.com/
  13020. */
  13021. function WebGLBackground( renderer, state, geometries, premultipliedAlpha ) {
  13022. var clearColor = new Color( 0x000000 );
  13023. var clearAlpha = 0;
  13024. var planeCamera, planeMesh;
  13025. var boxMesh;
  13026. function render( renderList, scene, camera, forceClear ) {
  13027. var background = scene.background;
  13028. if ( background === null ) {
  13029. setClear( clearColor, clearAlpha );
  13030. } else if ( background && background.isColor ) {
  13031. setClear( background, 1 );
  13032. forceClear = true;
  13033. }
  13034. if ( renderer.autoClear || forceClear ) {
  13035. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  13036. }
  13037. if ( background && background.isCubeTexture ) {
  13038. if ( boxMesh === undefined ) {
  13039. boxMesh = new Mesh(
  13040. new BoxBufferGeometry( 1, 1, 1 ),
  13041. new ShaderMaterial( {
  13042. uniforms: ShaderLib.cube.uniforms,
  13043. vertexShader: ShaderLib.cube.vertexShader,
  13044. fragmentShader: ShaderLib.cube.fragmentShader,
  13045. side: BackSide,
  13046. depthTest: true,
  13047. depthWrite: false,
  13048. fog: false
  13049. } )
  13050. );
  13051. boxMesh.geometry.removeAttribute( 'normal' );
  13052. boxMesh.geometry.removeAttribute( 'uv' );
  13053. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  13054. this.matrixWorld.copyPosition( camera.matrixWorld );
  13055. };
  13056. geometries.update( boxMesh.geometry );
  13057. }
  13058. boxMesh.material.uniforms.tCube.value = background;
  13059. renderList.push( boxMesh, boxMesh.geometry, boxMesh.material, 0, null );
  13060. } else if ( background && background.isTexture ) {
  13061. if ( planeCamera === undefined ) {
  13062. planeCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  13063. planeMesh = new Mesh(
  13064. new PlaneBufferGeometry( 2, 2 ),
  13065. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  13066. );
  13067. geometries.update( planeMesh.geometry );
  13068. }
  13069. planeMesh.material.map = background;
  13070. // TODO Push this to renderList
  13071. renderer.renderBufferDirect( planeCamera, null, planeMesh.geometry, planeMesh.material, planeMesh, null );
  13072. }
  13073. }
  13074. function setClear( color, alpha ) {
  13075. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  13076. }
  13077. return {
  13078. getClearColor: function () {
  13079. return clearColor;
  13080. },
  13081. setClearColor: function ( color, alpha ) {
  13082. clearColor.set( color );
  13083. clearAlpha = alpha !== undefined ? alpha : 1;
  13084. setClear( clearColor, clearAlpha );
  13085. },
  13086. getClearAlpha: function () {
  13087. return clearAlpha;
  13088. },
  13089. setClearAlpha: function ( alpha ) {
  13090. clearAlpha = alpha;
  13091. setClear( clearColor, clearAlpha );
  13092. },
  13093. render: render
  13094. };
  13095. }
  13096. /**
  13097. * @author mrdoob / http://mrdoob.com/
  13098. */
  13099. function WebGLBufferRenderer( gl, extensions, info ) {
  13100. var mode;
  13101. function setMode( value ) {
  13102. mode = value;
  13103. }
  13104. function render( start, count ) {
  13105. gl.drawArrays( mode, start, count );
  13106. info.update( count, mode );
  13107. }
  13108. function renderInstances( geometry, start, count ) {
  13109. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  13110. if ( extension === null ) {
  13111. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  13112. return;
  13113. }
  13114. var position = geometry.attributes.position;
  13115. if ( position.isInterleavedBufferAttribute ) {
  13116. count = position.data.count;
  13117. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  13118. } else {
  13119. extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
  13120. }
  13121. info.update( count, mode, geometry.maxInstancedCount );
  13122. }
  13123. //
  13124. this.setMode = setMode;
  13125. this.render = render;
  13126. this.renderInstances = renderInstances;
  13127. }
  13128. /**
  13129. * @author mrdoob / http://mrdoob.com/
  13130. */
  13131. function WebGLCapabilities( gl, extensions, parameters ) {
  13132. var maxAnisotropy;
  13133. function getMaxAnisotropy() {
  13134. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  13135. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13136. if ( extension !== null ) {
  13137. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  13138. } else {
  13139. maxAnisotropy = 0;
  13140. }
  13141. return maxAnisotropy;
  13142. }
  13143. function getMaxPrecision( precision ) {
  13144. if ( precision === 'highp' ) {
  13145. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  13146. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  13147. return 'highp';
  13148. }
  13149. precision = 'mediump';
  13150. }
  13151. if ( precision === 'mediump' ) {
  13152. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  13153. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  13154. return 'mediump';
  13155. }
  13156. }
  13157. return 'lowp';
  13158. }
  13159. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  13160. var maxPrecision = getMaxPrecision( precision );
  13161. if ( maxPrecision !== precision ) {
  13162. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  13163. precision = maxPrecision;
  13164. }
  13165. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  13166. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  13167. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  13168. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  13169. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  13170. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  13171. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  13172. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  13173. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  13174. var vertexTextures = maxVertexTextures > 0;
  13175. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  13176. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  13177. return {
  13178. getMaxAnisotropy: getMaxAnisotropy,
  13179. getMaxPrecision: getMaxPrecision,
  13180. precision: precision,
  13181. logarithmicDepthBuffer: logarithmicDepthBuffer,
  13182. maxTextures: maxTextures,
  13183. maxVertexTextures: maxVertexTextures,
  13184. maxTextureSize: maxTextureSize,
  13185. maxCubemapSize: maxCubemapSize,
  13186. maxAttributes: maxAttributes,
  13187. maxVertexUniforms: maxVertexUniforms,
  13188. maxVaryings: maxVaryings,
  13189. maxFragmentUniforms: maxFragmentUniforms,
  13190. vertexTextures: vertexTextures,
  13191. floatFragmentTextures: floatFragmentTextures,
  13192. floatVertexTextures: floatVertexTextures
  13193. };
  13194. }
  13195. /**
  13196. * @author tschw
  13197. */
  13198. function WebGLClipping() {
  13199. var scope = this,
  13200. globalState = null,
  13201. numGlobalPlanes = 0,
  13202. localClippingEnabled = false,
  13203. renderingShadows = false,
  13204. plane = new Plane(),
  13205. viewNormalMatrix = new Matrix3(),
  13206. uniform = { value: null, needsUpdate: false };
  13207. this.uniform = uniform;
  13208. this.numPlanes = 0;
  13209. this.numIntersection = 0;
  13210. this.init = function ( planes, enableLocalClipping, camera ) {
  13211. var enabled =
  13212. planes.length !== 0 ||
  13213. enableLocalClipping ||
  13214. // enable state of previous frame - the clipping code has to
  13215. // run another frame in order to reset the state:
  13216. numGlobalPlanes !== 0 ||
  13217. localClippingEnabled;
  13218. localClippingEnabled = enableLocalClipping;
  13219. globalState = projectPlanes( planes, camera, 0 );
  13220. numGlobalPlanes = planes.length;
  13221. return enabled;
  13222. };
  13223. this.beginShadows = function () {
  13224. renderingShadows = true;
  13225. projectPlanes( null );
  13226. };
  13227. this.endShadows = function () {
  13228. renderingShadows = false;
  13229. resetGlobalState();
  13230. };
  13231. this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  13232. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  13233. // there's no local clipping
  13234. if ( renderingShadows ) {
  13235. // there's no global clipping
  13236. projectPlanes( null );
  13237. } else {
  13238. resetGlobalState();
  13239. }
  13240. } else {
  13241. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  13242. lGlobal = nGlobal * 4,
  13243. dstArray = cache.clippingState || null;
  13244. uniform.value = dstArray; // ensure unique state
  13245. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  13246. for ( var i = 0; i !== lGlobal; ++ i ) {
  13247. dstArray[ i ] = globalState[ i ];
  13248. }
  13249. cache.clippingState = dstArray;
  13250. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  13251. this.numPlanes += nGlobal;
  13252. }
  13253. };
  13254. function resetGlobalState() {
  13255. if ( uniform.value !== globalState ) {
  13256. uniform.value = globalState;
  13257. uniform.needsUpdate = numGlobalPlanes > 0;
  13258. }
  13259. scope.numPlanes = numGlobalPlanes;
  13260. scope.numIntersection = 0;
  13261. }
  13262. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  13263. var nPlanes = planes !== null ? planes.length : 0,
  13264. dstArray = null;
  13265. if ( nPlanes !== 0 ) {
  13266. dstArray = uniform.value;
  13267. if ( skipTransform !== true || dstArray === null ) {
  13268. var flatSize = dstOffset + nPlanes * 4,
  13269. viewMatrix = camera.matrixWorldInverse;
  13270. viewNormalMatrix.getNormalMatrix( viewMatrix );
  13271. if ( dstArray === null || dstArray.length < flatSize ) {
  13272. dstArray = new Float32Array( flatSize );
  13273. }
  13274. for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  13275. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  13276. plane.normal.toArray( dstArray, i4 );
  13277. dstArray[ i4 + 3 ] = plane.constant;
  13278. }
  13279. }
  13280. uniform.value = dstArray;
  13281. uniform.needsUpdate = true;
  13282. }
  13283. scope.numPlanes = nPlanes;
  13284. return dstArray;
  13285. }
  13286. }
  13287. /**
  13288. * @author mrdoob / http://mrdoob.com/
  13289. */
  13290. function WebGLExtensions( gl ) {
  13291. var extensions = {};
  13292. return {
  13293. get: function ( name ) {
  13294. if ( extensions[ name ] !== undefined ) {
  13295. return extensions[ name ];
  13296. }
  13297. var extension;
  13298. switch ( name ) {
  13299. case 'WEBGL_depth_texture':
  13300. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  13301. break;
  13302. case 'EXT_texture_filter_anisotropic':
  13303. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13304. break;
  13305. case 'WEBGL_compressed_texture_s3tc':
  13306. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13307. break;
  13308. case 'WEBGL_compressed_texture_pvrtc':
  13309. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  13310. break;
  13311. default:
  13312. extension = gl.getExtension( name );
  13313. }
  13314. if ( extension === null ) {
  13315. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  13316. }
  13317. extensions[ name ] = extension;
  13318. return extension;
  13319. }
  13320. };
  13321. }
  13322. /**
  13323. * @author mrdoob / http://mrdoob.com/
  13324. */
  13325. function WebGLGeometries( gl, attributes, info ) {
  13326. var geometries = {};
  13327. var wireframeAttributes = {};
  13328. function onGeometryDispose( event ) {
  13329. var geometry = event.target;
  13330. var buffergeometry = geometries[ geometry.id ];
  13331. if ( buffergeometry.index !== null ) {
  13332. attributes.remove( buffergeometry.index );
  13333. }
  13334. for ( var name in buffergeometry.attributes ) {
  13335. attributes.remove( buffergeometry.attributes[ name ] );
  13336. }
  13337. geometry.removeEventListener( 'dispose', onGeometryDispose );
  13338. delete geometries[ geometry.id ];
  13339. // TODO Remove duplicate code
  13340. var attribute = wireframeAttributes[ geometry.id ];
  13341. if ( attribute ) {
  13342. attributes.remove( attribute );
  13343. delete wireframeAttributes[ geometry.id ];
  13344. }
  13345. attribute = wireframeAttributes[ buffergeometry.id ];
  13346. if ( attribute ) {
  13347. attributes.remove( attribute );
  13348. delete wireframeAttributes[ buffergeometry.id ];
  13349. }
  13350. //
  13351. info.memory.geometries --;
  13352. }
  13353. function get( object, geometry ) {
  13354. var buffergeometry = geometries[ geometry.id ];
  13355. if ( buffergeometry ) return buffergeometry;
  13356. geometry.addEventListener( 'dispose', onGeometryDispose );
  13357. if ( geometry.isBufferGeometry ) {
  13358. buffergeometry = geometry;
  13359. } else if ( geometry.isGeometry ) {
  13360. if ( geometry._bufferGeometry === undefined ) {
  13361. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  13362. }
  13363. buffergeometry = geometry._bufferGeometry;
  13364. }
  13365. geometries[ geometry.id ] = buffergeometry;
  13366. info.memory.geometries ++;
  13367. return buffergeometry;
  13368. }
  13369. function update( geometry ) {
  13370. var index = geometry.index;
  13371. var geometryAttributes = geometry.attributes;
  13372. if ( index !== null ) {
  13373. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  13374. }
  13375. for ( var name in geometryAttributes ) {
  13376. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  13377. }
  13378. // morph targets
  13379. var morphAttributes = geometry.morphAttributes;
  13380. for ( var name in morphAttributes ) {
  13381. var array = morphAttributes[ name ];
  13382. for ( var i = 0, l = array.length; i < l; i ++ ) {
  13383. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  13384. }
  13385. }
  13386. }
  13387. function getWireframeAttribute( geometry ) {
  13388. var attribute = wireframeAttributes[ geometry.id ];
  13389. if ( attribute ) return attribute;
  13390. var indices = [];
  13391. var geometryIndex = geometry.index;
  13392. var geometryAttributes = geometry.attributes;
  13393. // console.time( 'wireframe' );
  13394. if ( geometryIndex !== null ) {
  13395. var array = geometryIndex.array;
  13396. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  13397. var a = array[ i + 0 ];
  13398. var b = array[ i + 1 ];
  13399. var c = array[ i + 2 ];
  13400. indices.push( a, b, b, c, c, a );
  13401. }
  13402. } else {
  13403. var array = geometryAttributes.position.array;
  13404. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  13405. var a = i + 0;
  13406. var b = i + 1;
  13407. var c = i + 2;
  13408. indices.push( a, b, b, c, c, a );
  13409. }
  13410. }
  13411. // console.timeEnd( 'wireframe' );
  13412. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  13413. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  13414. wireframeAttributes[ geometry.id ] = attribute;
  13415. return attribute;
  13416. }
  13417. return {
  13418. get: get,
  13419. update: update,
  13420. getWireframeAttribute: getWireframeAttribute
  13421. };
  13422. }
  13423. /**
  13424. * @author mrdoob / http://mrdoob.com/
  13425. */
  13426. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  13427. var mode;
  13428. function setMode( value ) {
  13429. mode = value;
  13430. }
  13431. var type, bytesPerElement;
  13432. function setIndex( value ) {
  13433. type = value.type;
  13434. bytesPerElement = value.bytesPerElement;
  13435. }
  13436. function render( start, count ) {
  13437. gl.drawElements( mode, count, type, start * bytesPerElement );
  13438. info.update( count, mode );
  13439. }
  13440. function renderInstances( geometry, start, count ) {
  13441. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  13442. if ( extension === null ) {
  13443. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  13444. return;
  13445. }
  13446. extension.drawElementsInstancedANGLE( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  13447. info.update( count, mode, geometry.maxInstancedCount );
  13448. }
  13449. //
  13450. this.setMode = setMode;
  13451. this.setIndex = setIndex;
  13452. this.render = render;
  13453. this.renderInstances = renderInstances;
  13454. }
  13455. /**
  13456. * @author Mugen87 / https://github.com/Mugen87
  13457. */
  13458. function WebGLInfo( gl ) {
  13459. var memory = {
  13460. geometries: 0,
  13461. textures: 0
  13462. };
  13463. var render = {
  13464. frame: 0,
  13465. calls: 0,
  13466. triangles: 0,
  13467. points: 0,
  13468. lines: 0
  13469. };
  13470. function update( count, mode, instanceCount ) {
  13471. instanceCount = instanceCount || 1;
  13472. render.calls ++;
  13473. switch ( mode ) {
  13474. case gl.TRIANGLES:
  13475. render.triangles += instanceCount * ( count / 3 );
  13476. break;
  13477. case gl.TRIANGLE_STRIP:
  13478. case gl.TRIANGLE_FAN:
  13479. render.triangles += instanceCount * ( count - 2 );
  13480. break;
  13481. case gl.LINES:
  13482. render.lines += instanceCount * ( count / 2 );
  13483. break;
  13484. case gl.LINE_STRIP:
  13485. render.lines += instanceCount * ( count - 1 );
  13486. break;
  13487. case gl.LINE_LOOP:
  13488. render.lines += instanceCount * count;
  13489. break;
  13490. case gl.POINTS:
  13491. render.points += instanceCount * count;
  13492. break;
  13493. default:
  13494. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  13495. break;
  13496. }
  13497. }
  13498. function reset() {
  13499. render.frame ++;
  13500. render.calls = 0;
  13501. render.triangles = 0;
  13502. render.points = 0;
  13503. render.lines = 0;
  13504. }
  13505. return {
  13506. memory: memory,
  13507. render: render,
  13508. programs: null,
  13509. autoReset: true,
  13510. reset: reset,
  13511. update: update
  13512. };
  13513. }
  13514. /**
  13515. * @author mrdoob / http://mrdoob.com/
  13516. */
  13517. function absNumericalSort( a, b ) {
  13518. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  13519. }
  13520. function WebGLMorphtargets( gl ) {
  13521. var influencesList = {};
  13522. var morphInfluences = new Float32Array( 8 );
  13523. function update( object, geometry, material, program ) {
  13524. var objectInfluences = object.morphTargetInfluences;
  13525. var length = objectInfluences.length;
  13526. var influences = influencesList[ geometry.id ];
  13527. if ( influences === undefined ) {
  13528. // initialise list
  13529. influences = [];
  13530. for ( var i = 0; i < length; i ++ ) {
  13531. influences[ i ] = [ i, 0 ];
  13532. }
  13533. influencesList[ geometry.id ] = influences;
  13534. }
  13535. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  13536. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  13537. // Remove current morphAttributes
  13538. for ( var i = 0; i < length; i ++ ) {
  13539. var influence = influences[ i ];
  13540. if ( influence[ 1 ] !== 0 ) {
  13541. if ( morphTargets ) geometry.removeAttribute( 'morphTarget' + i );
  13542. if ( morphNormals ) geometry.removeAttribute( 'morphNormal' + i );
  13543. }
  13544. }
  13545. // Collect influences
  13546. for ( var i = 0; i < length; i ++ ) {
  13547. var influence = influences[ i ];
  13548. influence[ 0 ] = i;
  13549. influence[ 1 ] = objectInfluences[ i ];
  13550. }
  13551. influences.sort( absNumericalSort );
  13552. // Add morphAttributes
  13553. for ( var i = 0; i < 8; i ++ ) {
  13554. var influence = influences[ i ];
  13555. if ( influence ) {
  13556. var index = influence[ 0 ];
  13557. var value = influence[ 1 ];
  13558. if ( value ) {
  13559. if ( morphTargets ) geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] );
  13560. if ( morphNormals ) geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] );
  13561. morphInfluences[ i ] = value;
  13562. continue;
  13563. }
  13564. }
  13565. morphInfluences[ i ] = 0;
  13566. }
  13567. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  13568. }
  13569. return {
  13570. update: update
  13571. };
  13572. }
  13573. /**
  13574. * @author mrdoob / http://mrdoob.com/
  13575. */
  13576. function WebGLObjects( geometries, info ) {
  13577. var updateList = {};
  13578. function update( object ) {
  13579. var frame = info.render.frame;
  13580. var geometry = object.geometry;
  13581. var buffergeometry = geometries.get( object, geometry );
  13582. // Update once per frame
  13583. if ( updateList[ buffergeometry.id ] !== frame ) {
  13584. if ( geometry.isGeometry ) {
  13585. buffergeometry.updateFromObject( object );
  13586. }
  13587. geometries.update( buffergeometry );
  13588. updateList[ buffergeometry.id ] = frame;
  13589. }
  13590. return buffergeometry;
  13591. }
  13592. function dispose() {
  13593. updateList = {};
  13594. }
  13595. return {
  13596. update: update,
  13597. dispose: dispose
  13598. };
  13599. }
  13600. /**
  13601. * @author mrdoob / http://mrdoob.com/
  13602. */
  13603. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  13604. images = images !== undefined ? images : [];
  13605. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  13606. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13607. this.flipY = false;
  13608. }
  13609. CubeTexture.prototype = Object.create( Texture.prototype );
  13610. CubeTexture.prototype.constructor = CubeTexture;
  13611. CubeTexture.prototype.isCubeTexture = true;
  13612. Object.defineProperty( CubeTexture.prototype, 'images', {
  13613. get: function () {
  13614. return this.image;
  13615. },
  13616. set: function ( value ) {
  13617. this.image = value;
  13618. }
  13619. } );
  13620. /**
  13621. * @author tschw
  13622. *
  13623. * Uniforms of a program.
  13624. * Those form a tree structure with a special top-level container for the root,
  13625. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  13626. *
  13627. *
  13628. * Properties of inner nodes including the top-level container:
  13629. *
  13630. * .seq - array of nested uniforms
  13631. * .map - nested uniforms by name
  13632. *
  13633. *
  13634. * Methods of all nodes except the top-level container:
  13635. *
  13636. * .setValue( gl, value, [renderer] )
  13637. *
  13638. * uploads a uniform value(s)
  13639. * the 'renderer' parameter is needed for sampler uniforms
  13640. *
  13641. *
  13642. * Static methods of the top-level container (renderer factorizations):
  13643. *
  13644. * .upload( gl, seq, values, renderer )
  13645. *
  13646. * sets uniforms in 'seq' to 'values[id].value'
  13647. *
  13648. * .seqWithValue( seq, values ) : filteredSeq
  13649. *
  13650. * filters 'seq' entries with corresponding entry in values
  13651. *
  13652. *
  13653. * Methods of the top-level container (renderer factorizations):
  13654. *
  13655. * .setValue( gl, name, value )
  13656. *
  13657. * sets uniform with name 'name' to 'value'
  13658. *
  13659. * .set( gl, obj, prop )
  13660. *
  13661. * sets uniform from object and property with same name than uniform
  13662. *
  13663. * .setOptional( gl, obj, prop )
  13664. *
  13665. * like .set for an optional property of the object
  13666. *
  13667. */
  13668. var emptyTexture = new Texture();
  13669. var emptyCubeTexture = new CubeTexture();
  13670. // --- Base for inner nodes (including the root) ---
  13671. function UniformContainer() {
  13672. this.seq = [];
  13673. this.map = {};
  13674. }
  13675. // --- Utilities ---
  13676. // Array Caches (provide typed arrays for temporary by size)
  13677. var arrayCacheF32 = [];
  13678. var arrayCacheI32 = [];
  13679. // Float32Array caches used for uploading Matrix uniforms
  13680. var mat4array = new Float32Array( 16 );
  13681. var mat3array = new Float32Array( 9 );
  13682. // Flattening for arrays of vectors and matrices
  13683. function flatten( array, nBlocks, blockSize ) {
  13684. var firstElem = array[ 0 ];
  13685. if ( firstElem <= 0 || firstElem > 0 ) return array;
  13686. // unoptimized: ! isNaN( firstElem )
  13687. // see http://jacksondunstan.com/articles/983
  13688. var n = nBlocks * blockSize,
  13689. r = arrayCacheF32[ n ];
  13690. if ( r === undefined ) {
  13691. r = new Float32Array( n );
  13692. arrayCacheF32[ n ] = r;
  13693. }
  13694. if ( nBlocks !== 0 ) {
  13695. firstElem.toArray( r, 0 );
  13696. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  13697. offset += blockSize;
  13698. array[ i ].toArray( r, offset );
  13699. }
  13700. }
  13701. return r;
  13702. }
  13703. // Texture unit allocation
  13704. function allocTexUnits( renderer, n ) {
  13705. var r = arrayCacheI32[ n ];
  13706. if ( r === undefined ) {
  13707. r = new Int32Array( n );
  13708. arrayCacheI32[ n ] = r;
  13709. }
  13710. for ( var i = 0; i !== n; ++ i )
  13711. r[ i ] = renderer.allocTextureUnit();
  13712. return r;
  13713. }
  13714. // --- Setters ---
  13715. // Note: Defining these methods externally, because they come in a bunch
  13716. // and this way their names minify.
  13717. // Single scalar
  13718. function setValue1f( gl, v ) {
  13719. gl.uniform1f( this.addr, v );
  13720. }
  13721. function setValue1i( gl, v ) {
  13722. gl.uniform1i( this.addr, v );
  13723. }
  13724. // Single float vector (from flat array or THREE.VectorN)
  13725. function setValue2fv( gl, v ) {
  13726. if ( v.x === undefined ) {
  13727. gl.uniform2fv( this.addr, v );
  13728. } else {
  13729. gl.uniform2f( this.addr, v.x, v.y );
  13730. }
  13731. }
  13732. function setValue3fv( gl, v ) {
  13733. if ( v.x !== undefined ) {
  13734. gl.uniform3f( this.addr, v.x, v.y, v.z );
  13735. } else if ( v.r !== undefined ) {
  13736. gl.uniform3f( this.addr, v.r, v.g, v.b );
  13737. } else {
  13738. gl.uniform3fv( this.addr, v );
  13739. }
  13740. }
  13741. function setValue4fv( gl, v ) {
  13742. if ( v.x === undefined ) {
  13743. gl.uniform4fv( this.addr, v );
  13744. } else {
  13745. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  13746. }
  13747. }
  13748. // Single matrix (from flat array or MatrixN)
  13749. function setValue2fm( gl, v ) {
  13750. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  13751. }
  13752. function setValue3fm( gl, v ) {
  13753. if ( v.elements === undefined ) {
  13754. gl.uniformMatrix3fv( this.addr, false, v );
  13755. } else {
  13756. mat3array.set( v.elements );
  13757. gl.uniformMatrix3fv( this.addr, false, mat3array );
  13758. }
  13759. }
  13760. function setValue4fm( gl, v ) {
  13761. if ( v.elements === undefined ) {
  13762. gl.uniformMatrix4fv( this.addr, false, v );
  13763. } else {
  13764. mat4array.set( v.elements );
  13765. gl.uniformMatrix4fv( this.addr, false, mat4array );
  13766. }
  13767. }
  13768. // Single texture (2D / Cube)
  13769. function setValueT1( gl, v, renderer ) {
  13770. var unit = renderer.allocTextureUnit();
  13771. gl.uniform1i( this.addr, unit );
  13772. renderer.setTexture2D( v || emptyTexture, unit );
  13773. }
  13774. function setValueT6( gl, v, renderer ) {
  13775. var unit = renderer.allocTextureUnit();
  13776. gl.uniform1i( this.addr, unit );
  13777. renderer.setTextureCube( v || emptyCubeTexture, unit );
  13778. }
  13779. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  13780. function setValue2iv( gl, v ) {
  13781. gl.uniform2iv( this.addr, v );
  13782. }
  13783. function setValue3iv( gl, v ) {
  13784. gl.uniform3iv( this.addr, v );
  13785. }
  13786. function setValue4iv( gl, v ) {
  13787. gl.uniform4iv( this.addr, v );
  13788. }
  13789. // Helper to pick the right setter for the singular case
  13790. function getSingularSetter( type ) {
  13791. switch ( type ) {
  13792. case 0x1406: return setValue1f; // FLOAT
  13793. case 0x8b50: return setValue2fv; // _VEC2
  13794. case 0x8b51: return setValue3fv; // _VEC3
  13795. case 0x8b52: return setValue4fv; // _VEC4
  13796. case 0x8b5a: return setValue2fm; // _MAT2
  13797. case 0x8b5b: return setValue3fm; // _MAT3
  13798. case 0x8b5c: return setValue4fm; // _MAT4
  13799. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  13800. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  13801. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  13802. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  13803. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  13804. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  13805. }
  13806. }
  13807. // Array of scalars
  13808. function setValue1fv( gl, v ) {
  13809. gl.uniform1fv( this.addr, v );
  13810. }
  13811. function setValue1iv( gl, v ) {
  13812. gl.uniform1iv( this.addr, v );
  13813. }
  13814. // Array of vectors (flat or from THREE classes)
  13815. function setValueV2a( gl, v ) {
  13816. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  13817. }
  13818. function setValueV3a( gl, v ) {
  13819. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  13820. }
  13821. function setValueV4a( gl, v ) {
  13822. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  13823. }
  13824. // Array of matrices (flat or from THREE clases)
  13825. function setValueM2a( gl, v ) {
  13826. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  13827. }
  13828. function setValueM3a( gl, v ) {
  13829. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  13830. }
  13831. function setValueM4a( gl, v ) {
  13832. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  13833. }
  13834. // Array of textures (2D / Cube)
  13835. function setValueT1a( gl, v, renderer ) {
  13836. var n = v.length,
  13837. units = allocTexUnits( renderer, n );
  13838. gl.uniform1iv( this.addr, units );
  13839. for ( var i = 0; i !== n; ++ i ) {
  13840. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  13841. }
  13842. }
  13843. function setValueT6a( gl, v, renderer ) {
  13844. var n = v.length,
  13845. units = allocTexUnits( renderer, n );
  13846. gl.uniform1iv( this.addr, units );
  13847. for ( var i = 0; i !== n; ++ i ) {
  13848. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  13849. }
  13850. }
  13851. // Helper to pick the right setter for a pure (bottom-level) array
  13852. function getPureArraySetter( type ) {
  13853. switch ( type ) {
  13854. case 0x1406: return setValue1fv; // FLOAT
  13855. case 0x8b50: return setValueV2a; // _VEC2
  13856. case 0x8b51: return setValueV3a; // _VEC3
  13857. case 0x8b52: return setValueV4a; // _VEC4
  13858. case 0x8b5a: return setValueM2a; // _MAT2
  13859. case 0x8b5b: return setValueM3a; // _MAT3
  13860. case 0x8b5c: return setValueM4a; // _MAT4
  13861. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  13862. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  13863. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  13864. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  13865. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  13866. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  13867. }
  13868. }
  13869. // --- Uniform Classes ---
  13870. function SingleUniform( id, activeInfo, addr ) {
  13871. this.id = id;
  13872. this.addr = addr;
  13873. this.setValue = getSingularSetter( activeInfo.type );
  13874. // this.path = activeInfo.name; // DEBUG
  13875. }
  13876. function PureArrayUniform( id, activeInfo, addr ) {
  13877. this.id = id;
  13878. this.addr = addr;
  13879. this.size = activeInfo.size;
  13880. this.setValue = getPureArraySetter( activeInfo.type );
  13881. // this.path = activeInfo.name; // DEBUG
  13882. }
  13883. function StructuredUniform( id ) {
  13884. this.id = id;
  13885. UniformContainer.call( this ); // mix-in
  13886. }
  13887. StructuredUniform.prototype.setValue = function ( gl, value ) {
  13888. // Note: Don't need an extra 'renderer' parameter, since samplers
  13889. // are not allowed in structured uniforms.
  13890. var seq = this.seq;
  13891. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  13892. var u = seq[ i ];
  13893. u.setValue( gl, value[ u.id ] );
  13894. }
  13895. };
  13896. // --- Top-level ---
  13897. // Parser - builds up the property tree from the path strings
  13898. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  13899. // extracts
  13900. // - the identifier (member name or array index)
  13901. // - followed by an optional right bracket (found when array index)
  13902. // - followed by an optional left bracket or dot (type of subscript)
  13903. //
  13904. // Note: These portions can be read in a non-overlapping fashion and
  13905. // allow straightforward parsing of the hierarchy that WebGL encodes
  13906. // in the uniform names.
  13907. function addUniform( container, uniformObject ) {
  13908. container.seq.push( uniformObject );
  13909. container.map[ uniformObject.id ] = uniformObject;
  13910. }
  13911. function parseUniform( activeInfo, addr, container ) {
  13912. var path = activeInfo.name,
  13913. pathLength = path.length;
  13914. // reset RegExp object, because of the early exit of a previous run
  13915. RePathPart.lastIndex = 0;
  13916. for ( ; ; ) {
  13917. var match = RePathPart.exec( path ),
  13918. matchEnd = RePathPart.lastIndex,
  13919. id = match[ 1 ],
  13920. idIsIndex = match[ 2 ] === ']',
  13921. subscript = match[ 3 ];
  13922. if ( idIsIndex ) id = id | 0; // convert to integer
  13923. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  13924. // bare name or "pure" bottom-level array "[0]" suffix
  13925. addUniform( container, subscript === undefined ?
  13926. new SingleUniform( id, activeInfo, addr ) :
  13927. new PureArrayUniform( id, activeInfo, addr ) );
  13928. break;
  13929. } else {
  13930. // step into inner node / create it in case it doesn't exist
  13931. var map = container.map, next = map[ id ];
  13932. if ( next === undefined ) {
  13933. next = new StructuredUniform( id );
  13934. addUniform( container, next );
  13935. }
  13936. container = next;
  13937. }
  13938. }
  13939. }
  13940. // Root Container
  13941. function WebGLUniforms( gl, program, renderer ) {
  13942. UniformContainer.call( this );
  13943. this.renderer = renderer;
  13944. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  13945. for ( var i = 0; i < n; ++ i ) {
  13946. var info = gl.getActiveUniform( program, i ),
  13947. addr = gl.getUniformLocation( program, info.name );
  13948. parseUniform( info, addr, this );
  13949. }
  13950. }
  13951. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  13952. var u = this.map[ name ];
  13953. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  13954. };
  13955. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  13956. var v = object[ name ];
  13957. if ( v !== undefined ) this.setValue( gl, name, v );
  13958. };
  13959. // Static interface
  13960. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  13961. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  13962. var u = seq[ i ],
  13963. v = values[ u.id ];
  13964. if ( v.needsUpdate !== false ) {
  13965. // note: always updating when .needsUpdate is undefined
  13966. u.setValue( gl, v.value, renderer );
  13967. }
  13968. }
  13969. };
  13970. WebGLUniforms.seqWithValue = function ( seq, values ) {
  13971. var r = [];
  13972. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  13973. var u = seq[ i ];
  13974. if ( u.id in values ) r.push( u );
  13975. }
  13976. return r;
  13977. };
  13978. /**
  13979. * @author mrdoob / http://mrdoob.com/
  13980. */
  13981. function addLineNumbers( string ) {
  13982. var lines = string.split( '\n' );
  13983. for ( var i = 0; i < lines.length; i ++ ) {
  13984. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  13985. }
  13986. return lines.join( '\n' );
  13987. }
  13988. function WebGLShader( gl, type, string ) {
  13989. var shader = gl.createShader( type );
  13990. gl.shaderSource( shader, string );
  13991. gl.compileShader( shader );
  13992. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  13993. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  13994. }
  13995. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  13996. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  13997. }
  13998. // --enable-privileged-webgl-extension
  13999. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14000. return shader;
  14001. }
  14002. /**
  14003. * @author mrdoob / http://mrdoob.com/
  14004. */
  14005. var programIdCount = 0;
  14006. function getEncodingComponents( encoding ) {
  14007. switch ( encoding ) {
  14008. case LinearEncoding:
  14009. return [ 'Linear', '( value )' ];
  14010. case sRGBEncoding:
  14011. return [ 'sRGB', '( value )' ];
  14012. case RGBEEncoding:
  14013. return [ 'RGBE', '( value )' ];
  14014. case RGBM7Encoding:
  14015. return [ 'RGBM', '( value, 7.0 )' ];
  14016. case RGBM16Encoding:
  14017. return [ 'RGBM', '( value, 16.0 )' ];
  14018. case RGBDEncoding:
  14019. return [ 'RGBD', '( value, 256.0 )' ];
  14020. case GammaEncoding:
  14021. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  14022. default:
  14023. throw new Error( 'unsupported encoding: ' + encoding );
  14024. }
  14025. }
  14026. function getTexelDecodingFunction( functionName, encoding ) {
  14027. var components = getEncodingComponents( encoding );
  14028. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  14029. }
  14030. function getTexelEncodingFunction( functionName, encoding ) {
  14031. var components = getEncodingComponents( encoding );
  14032. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  14033. }
  14034. function getToneMappingFunction( functionName, toneMapping ) {
  14035. var toneMappingName;
  14036. switch ( toneMapping ) {
  14037. case LinearToneMapping:
  14038. toneMappingName = 'Linear';
  14039. break;
  14040. case ReinhardToneMapping:
  14041. toneMappingName = 'Reinhard';
  14042. break;
  14043. case Uncharted2ToneMapping:
  14044. toneMappingName = 'Uncharted2';
  14045. break;
  14046. case CineonToneMapping:
  14047. toneMappingName = 'OptimizedCineon';
  14048. break;
  14049. default:
  14050. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  14051. }
  14052. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  14053. }
  14054. function generateExtensions( extensions, parameters, rendererExtensions ) {
  14055. extensions = extensions || {};
  14056. var chunks = [
  14057. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  14058. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  14059. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  14060. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  14061. ];
  14062. return chunks.filter( filterEmptyLine ).join( '\n' );
  14063. }
  14064. function generateDefines( defines ) {
  14065. var chunks = [];
  14066. for ( var name in defines ) {
  14067. var value = defines[ name ];
  14068. if ( value === false ) continue;
  14069. chunks.push( '#define ' + name + ' ' + value );
  14070. }
  14071. return chunks.join( '\n' );
  14072. }
  14073. function fetchAttributeLocations( gl, program ) {
  14074. var attributes = {};
  14075. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  14076. for ( var i = 0; i < n; i ++ ) {
  14077. var info = gl.getActiveAttrib( program, i );
  14078. var name = info.name;
  14079. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  14080. attributes[ name ] = gl.getAttribLocation( program, name );
  14081. }
  14082. return attributes;
  14083. }
  14084. function filterEmptyLine( string ) {
  14085. return string !== '';
  14086. }
  14087. function replaceLightNums( string, parameters ) {
  14088. return string
  14089. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  14090. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  14091. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  14092. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  14093. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  14094. }
  14095. function replaceClippingPlaneNums( string, parameters ) {
  14096. return string
  14097. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  14098. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  14099. }
  14100. function parseIncludes( string ) {
  14101. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  14102. function replace( match, include ) {
  14103. var replace = ShaderChunk[ include ];
  14104. if ( replace === undefined ) {
  14105. throw new Error( 'Can not resolve #include <' + include + '>' );
  14106. }
  14107. return parseIncludes( replace );
  14108. }
  14109. return string.replace( pattern, replace );
  14110. }
  14111. function unrollLoops( string ) {
  14112. var pattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  14113. function replace( match, start, end, snippet ) {
  14114. var unroll = '';
  14115. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  14116. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  14117. }
  14118. return unroll;
  14119. }
  14120. return string.replace( pattern, replace );
  14121. }
  14122. function WebGLProgram( renderer, extensions, code, material, shader, parameters ) {
  14123. var gl = renderer.context;
  14124. var defines = material.defines;
  14125. var vertexShader = shader.vertexShader;
  14126. var fragmentShader = shader.fragmentShader;
  14127. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14128. if ( parameters.shadowMapType === PCFShadowMap ) {
  14129. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14130. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  14131. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14132. }
  14133. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14134. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14135. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14136. if ( parameters.envMap ) {
  14137. switch ( material.envMap.mapping ) {
  14138. case CubeReflectionMapping:
  14139. case CubeRefractionMapping:
  14140. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14141. break;
  14142. case CubeUVReflectionMapping:
  14143. case CubeUVRefractionMapping:
  14144. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  14145. break;
  14146. case EquirectangularReflectionMapping:
  14147. case EquirectangularRefractionMapping:
  14148. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14149. break;
  14150. case SphericalReflectionMapping:
  14151. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14152. break;
  14153. }
  14154. switch ( material.envMap.mapping ) {
  14155. case CubeRefractionMapping:
  14156. case EquirectangularRefractionMapping:
  14157. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14158. break;
  14159. }
  14160. switch ( material.combine ) {
  14161. case MultiplyOperation:
  14162. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14163. break;
  14164. case MixOperation:
  14165. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  14166. break;
  14167. case AddOperation:
  14168. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  14169. break;
  14170. }
  14171. }
  14172. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  14173. // console.log( 'building new program ' );
  14174. //
  14175. var customExtensions = generateExtensions( material.extensions, parameters, extensions );
  14176. var customDefines = generateDefines( defines );
  14177. //
  14178. var program = gl.createProgram();
  14179. var prefixVertex, prefixFragment;
  14180. if ( material.isRawShaderMaterial ) {
  14181. prefixVertex = [
  14182. customDefines
  14183. ].filter( filterEmptyLine ).join( '\n' );
  14184. if ( prefixVertex.length > 0 ) {
  14185. prefixVertex += '\n';
  14186. }
  14187. prefixFragment = [
  14188. customExtensions,
  14189. customDefines
  14190. ].filter( filterEmptyLine ).join( '\n' );
  14191. if ( prefixFragment.length > 0 ) {
  14192. prefixFragment += '\n';
  14193. }
  14194. } else {
  14195. prefixVertex = [
  14196. 'precision ' + parameters.precision + ' float;',
  14197. 'precision ' + parameters.precision + ' int;',
  14198. '#define SHADER_NAME ' + shader.name,
  14199. customDefines,
  14200. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  14201. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14202. '#define MAX_BONES ' + parameters.maxBones,
  14203. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14204. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14205. parameters.map ? '#define USE_MAP' : '',
  14206. parameters.envMap ? '#define USE_ENVMAP' : '',
  14207. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14208. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14209. parameters.aoMap ? '#define USE_AOMAP' : '',
  14210. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14211. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14212. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14213. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  14214. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14215. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  14216. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  14217. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14218. parameters.vertexColors ? '#define USE_COLOR' : '',
  14219. parameters.flatShading ? '#define FLAT_SHADED' : '',
  14220. parameters.skinning ? '#define USE_SKINNING' : '',
  14221. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  14222. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  14223. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  14224. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14225. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14226. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14227. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14228. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  14229. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14230. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14231. 'uniform mat4 modelMatrix;',
  14232. 'uniform mat4 modelViewMatrix;',
  14233. 'uniform mat4 projectionMatrix;',
  14234. 'uniform mat4 viewMatrix;',
  14235. 'uniform mat3 normalMatrix;',
  14236. 'uniform vec3 cameraPosition;',
  14237. 'attribute vec3 position;',
  14238. 'attribute vec3 normal;',
  14239. 'attribute vec2 uv;',
  14240. '#ifdef USE_COLOR',
  14241. ' attribute vec3 color;',
  14242. '#endif',
  14243. '#ifdef USE_MORPHTARGETS',
  14244. ' attribute vec3 morphTarget0;',
  14245. ' attribute vec3 morphTarget1;',
  14246. ' attribute vec3 morphTarget2;',
  14247. ' attribute vec3 morphTarget3;',
  14248. ' #ifdef USE_MORPHNORMALS',
  14249. ' attribute vec3 morphNormal0;',
  14250. ' attribute vec3 morphNormal1;',
  14251. ' attribute vec3 morphNormal2;',
  14252. ' attribute vec3 morphNormal3;',
  14253. ' #else',
  14254. ' attribute vec3 morphTarget4;',
  14255. ' attribute vec3 morphTarget5;',
  14256. ' attribute vec3 morphTarget6;',
  14257. ' attribute vec3 morphTarget7;',
  14258. ' #endif',
  14259. '#endif',
  14260. '#ifdef USE_SKINNING',
  14261. ' attribute vec4 skinIndex;',
  14262. ' attribute vec4 skinWeight;',
  14263. '#endif',
  14264. '\n'
  14265. ].filter( filterEmptyLine ).join( '\n' );
  14266. prefixFragment = [
  14267. customExtensions,
  14268. 'precision ' + parameters.precision + ' float;',
  14269. 'precision ' + parameters.precision + ' int;',
  14270. '#define SHADER_NAME ' + shader.name,
  14271. customDefines,
  14272. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  14273. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14274. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14275. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14276. parameters.map ? '#define USE_MAP' : '',
  14277. parameters.envMap ? '#define USE_ENVMAP' : '',
  14278. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  14279. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14280. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  14281. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14282. parameters.aoMap ? '#define USE_AOMAP' : '',
  14283. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14284. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14285. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14286. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14287. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  14288. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  14289. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14290. parameters.vertexColors ? '#define USE_COLOR' : '',
  14291. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  14292. parameters.flatShading ? '#define FLAT_SHADED' : '',
  14293. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14294. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14295. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14296. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14297. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  14298. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  14299. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14300. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14301. parameters.envMap && extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  14302. 'uniform mat4 viewMatrix;',
  14303. 'uniform vec3 cameraPosition;',
  14304. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  14305. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  14306. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  14307. parameters.dithering ? '#define DITHERING' : '',
  14308. ( 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
  14309. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  14310. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  14311. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  14312. parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '',
  14313. parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '',
  14314. '\n'
  14315. ].filter( filterEmptyLine ).join( '\n' );
  14316. }
  14317. vertexShader = parseIncludes( vertexShader );
  14318. vertexShader = replaceLightNums( vertexShader, parameters );
  14319. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  14320. fragmentShader = parseIncludes( fragmentShader );
  14321. fragmentShader = replaceLightNums( fragmentShader, parameters );
  14322. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  14323. vertexShader = unrollLoops( vertexShader );
  14324. fragmentShader = unrollLoops( fragmentShader );
  14325. var vertexGlsl = prefixVertex + vertexShader;
  14326. var fragmentGlsl = prefixFragment + fragmentShader;
  14327. // console.log( '*VERTEX*', vertexGlsl );
  14328. // console.log( '*FRAGMENT*', fragmentGlsl );
  14329. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  14330. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  14331. gl.attachShader( program, glVertexShader );
  14332. gl.attachShader( program, glFragmentShader );
  14333. // Force a particular attribute to index 0.
  14334. if ( material.index0AttributeName !== undefined ) {
  14335. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  14336. } else if ( parameters.morphTargets === true ) {
  14337. // programs with morphTargets displace position out of attribute 0
  14338. gl.bindAttribLocation( program, 0, 'position' );
  14339. }
  14340. gl.linkProgram( program );
  14341. var programLog = gl.getProgramInfoLog( program ).trim();
  14342. var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  14343. var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  14344. var runnable = true;
  14345. var haveDiagnostics = true;
  14346. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  14347. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  14348. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  14349. runnable = false;
  14350. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  14351. } else if ( programLog !== '' ) {
  14352. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  14353. } else if ( vertexLog === '' || fragmentLog === '' ) {
  14354. haveDiagnostics = false;
  14355. }
  14356. if ( haveDiagnostics ) {
  14357. this.diagnostics = {
  14358. runnable: runnable,
  14359. material: material,
  14360. programLog: programLog,
  14361. vertexShader: {
  14362. log: vertexLog,
  14363. prefix: prefixVertex
  14364. },
  14365. fragmentShader: {
  14366. log: fragmentLog,
  14367. prefix: prefixFragment
  14368. }
  14369. };
  14370. }
  14371. // clean up
  14372. gl.deleteShader( glVertexShader );
  14373. gl.deleteShader( glFragmentShader );
  14374. // set up caching for uniform locations
  14375. var cachedUniforms;
  14376. this.getUniforms = function () {
  14377. if ( cachedUniforms === undefined ) {
  14378. cachedUniforms = new WebGLUniforms( gl, program, renderer );
  14379. }
  14380. return cachedUniforms;
  14381. };
  14382. // set up caching for attribute locations
  14383. var cachedAttributes;
  14384. this.getAttributes = function () {
  14385. if ( cachedAttributes === undefined ) {
  14386. cachedAttributes = fetchAttributeLocations( gl, program );
  14387. }
  14388. return cachedAttributes;
  14389. };
  14390. // free resource
  14391. this.destroy = function () {
  14392. gl.deleteProgram( program );
  14393. this.program = undefined;
  14394. };
  14395. // DEPRECATED
  14396. Object.defineProperties( this, {
  14397. uniforms: {
  14398. get: function () {
  14399. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  14400. return this.getUniforms();
  14401. }
  14402. },
  14403. attributes: {
  14404. get: function () {
  14405. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  14406. return this.getAttributes();
  14407. }
  14408. }
  14409. } );
  14410. //
  14411. this.name = shader.name;
  14412. this.id = programIdCount ++;
  14413. this.code = code;
  14414. this.usedTimes = 1;
  14415. this.program = program;
  14416. this.vertexShader = glVertexShader;
  14417. this.fragmentShader = glFragmentShader;
  14418. return this;
  14419. }
  14420. /**
  14421. * @author mrdoob / http://mrdoob.com/
  14422. */
  14423. function WebGLPrograms( renderer, extensions, capabilities ) {
  14424. var programs = [];
  14425. var shaderIDs = {
  14426. MeshDepthMaterial: 'depth',
  14427. MeshDistanceMaterial: 'distanceRGBA',
  14428. MeshNormalMaterial: 'normal',
  14429. MeshBasicMaterial: 'basic',
  14430. MeshLambertMaterial: 'lambert',
  14431. MeshPhongMaterial: 'phong',
  14432. MeshToonMaterial: 'phong',
  14433. MeshStandardMaterial: 'physical',
  14434. MeshPhysicalMaterial: 'physical',
  14435. LineBasicMaterial: 'basic',
  14436. LineDashedMaterial: 'dashed',
  14437. PointsMaterial: 'points',
  14438. ShadowMaterial: 'shadow'
  14439. };
  14440. var parameterNames = [
  14441. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  14442. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  14443. "roughnessMap", "metalnessMap", "gradientMap",
  14444. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  14445. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  14446. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  14447. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  14448. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  14449. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  14450. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  14451. ];
  14452. function allocateBones( object ) {
  14453. var skeleton = object.skeleton;
  14454. var bones = skeleton.bones;
  14455. if ( capabilities.floatVertexTextures ) {
  14456. return 1024;
  14457. } else {
  14458. // default for when object is not specified
  14459. // ( for example when prebuilding shader to be used with multiple objects )
  14460. //
  14461. // - leave some extra space for other uniforms
  14462. // - limit here is ANGLE's 254 max uniform vectors
  14463. // (up to 54 should be safe)
  14464. var nVertexUniforms = capabilities.maxVertexUniforms;
  14465. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14466. var maxBones = Math.min( nVertexMatrices, bones.length );
  14467. if ( maxBones < bones.length ) {
  14468. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  14469. return 0;
  14470. }
  14471. return maxBones;
  14472. }
  14473. }
  14474. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  14475. var encoding;
  14476. if ( ! map ) {
  14477. encoding = LinearEncoding;
  14478. } else if ( map.isTexture ) {
  14479. encoding = map.encoding;
  14480. } else if ( map.isWebGLRenderTarget ) {
  14481. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  14482. encoding = map.texture.encoding;
  14483. }
  14484. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  14485. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  14486. encoding = GammaEncoding;
  14487. }
  14488. return encoding;
  14489. }
  14490. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  14491. var shaderID = shaderIDs[ material.type ];
  14492. // heuristics to create shader parameters according to lights in the scene
  14493. // (not to blow over maxLights budget)
  14494. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  14495. var precision = capabilities.precision;
  14496. if ( material.precision !== null ) {
  14497. precision = capabilities.getMaxPrecision( material.precision );
  14498. if ( precision !== material.precision ) {
  14499. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  14500. }
  14501. }
  14502. var currentRenderTarget = renderer.getRenderTarget();
  14503. var parameters = {
  14504. shaderID: shaderID,
  14505. precision: precision,
  14506. supportsVertexTextures: capabilities.vertexTextures,
  14507. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  14508. map: !! material.map,
  14509. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  14510. envMap: !! material.envMap,
  14511. envMapMode: material.envMap && material.envMap.mapping,
  14512. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  14513. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  14514. lightMap: !! material.lightMap,
  14515. aoMap: !! material.aoMap,
  14516. emissiveMap: !! material.emissiveMap,
  14517. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  14518. bumpMap: !! material.bumpMap,
  14519. normalMap: !! material.normalMap,
  14520. displacementMap: !! material.displacementMap,
  14521. roughnessMap: !! material.roughnessMap,
  14522. metalnessMap: !! material.metalnessMap,
  14523. specularMap: !! material.specularMap,
  14524. alphaMap: !! material.alphaMap,
  14525. gradientMap: !! material.gradientMap,
  14526. combine: material.combine,
  14527. vertexColors: material.vertexColors,
  14528. fog: !! fog,
  14529. useFog: material.fog,
  14530. fogExp: ( fog && fog.isFogExp2 ),
  14531. flatShading: material.flatShading,
  14532. sizeAttenuation: material.sizeAttenuation,
  14533. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  14534. skinning: material.skinning && maxBones > 0,
  14535. maxBones: maxBones,
  14536. useVertexTexture: capabilities.floatVertexTextures,
  14537. morphTargets: material.morphTargets,
  14538. morphNormals: material.morphNormals,
  14539. maxMorphTargets: renderer.maxMorphTargets,
  14540. maxMorphNormals: renderer.maxMorphNormals,
  14541. numDirLights: lights.directional.length,
  14542. numPointLights: lights.point.length,
  14543. numSpotLights: lights.spot.length,
  14544. numRectAreaLights: lights.rectArea.length,
  14545. numHemiLights: lights.hemi.length,
  14546. numClippingPlanes: nClipPlanes,
  14547. numClipIntersection: nClipIntersection,
  14548. dithering: material.dithering,
  14549. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,
  14550. shadowMapType: renderer.shadowMap.type,
  14551. toneMapping: renderer.toneMapping,
  14552. physicallyCorrectLights: renderer.physicallyCorrectLights,
  14553. premultipliedAlpha: material.premultipliedAlpha,
  14554. alphaTest: material.alphaTest,
  14555. doubleSided: material.side === DoubleSide,
  14556. flipSided: material.side === BackSide,
  14557. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  14558. };
  14559. return parameters;
  14560. };
  14561. this.getProgramCode = function ( material, parameters ) {
  14562. var array = [];
  14563. if ( parameters.shaderID ) {
  14564. array.push( parameters.shaderID );
  14565. } else {
  14566. array.push( material.fragmentShader );
  14567. array.push( material.vertexShader );
  14568. }
  14569. if ( material.defines !== undefined ) {
  14570. for ( var name in material.defines ) {
  14571. array.push( name );
  14572. array.push( material.defines[ name ] );
  14573. }
  14574. }
  14575. for ( var i = 0; i < parameterNames.length; i ++ ) {
  14576. array.push( parameters[ parameterNames[ i ] ] );
  14577. }
  14578. array.push( material.onBeforeCompile.toString() );
  14579. array.push( renderer.gammaOutput );
  14580. return array.join();
  14581. };
  14582. this.acquireProgram = function ( material, shader, parameters, code ) {
  14583. var program;
  14584. // Check if code has been already compiled
  14585. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  14586. var programInfo = programs[ p ];
  14587. if ( programInfo.code === code ) {
  14588. program = programInfo;
  14589. ++ program.usedTimes;
  14590. break;
  14591. }
  14592. }
  14593. if ( program === undefined ) {
  14594. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters );
  14595. programs.push( program );
  14596. }
  14597. return program;
  14598. };
  14599. this.releaseProgram = function ( program ) {
  14600. if ( -- program.usedTimes === 0 ) {
  14601. // Remove from unordered set
  14602. var i = programs.indexOf( program );
  14603. programs[ i ] = programs[ programs.length - 1 ];
  14604. programs.pop();
  14605. // Free WebGL resources
  14606. program.destroy();
  14607. }
  14608. };
  14609. // Exposed for resource monitoring & error feedback via renderer.info:
  14610. this.programs = programs;
  14611. }
  14612. /**
  14613. * @author fordacious / fordacious.github.io
  14614. */
  14615. function WebGLProperties() {
  14616. var properties = new WeakMap();
  14617. function get( object ) {
  14618. var map = properties.get( object );
  14619. if ( map === undefined ) {
  14620. map = {};
  14621. properties.set( object, map );
  14622. }
  14623. return map;
  14624. }
  14625. function remove( object ) {
  14626. properties.delete( object );
  14627. }
  14628. function update( object, key, value ) {
  14629. properties.get( object )[ key ] = value;
  14630. }
  14631. function dispose() {
  14632. properties = new WeakMap();
  14633. }
  14634. return {
  14635. get: get,
  14636. remove: remove,
  14637. update: update,
  14638. dispose: dispose
  14639. };
  14640. }
  14641. /**
  14642. * @author mrdoob / http://mrdoob.com/
  14643. */
  14644. function painterSortStable( a, b ) {
  14645. if ( a.renderOrder !== b.renderOrder ) {
  14646. return a.renderOrder - b.renderOrder;
  14647. } else if ( a.program && b.program && a.program !== b.program ) {
  14648. return a.program.id - b.program.id;
  14649. } else if ( a.material.id !== b.material.id ) {
  14650. return a.material.id - b.material.id;
  14651. } else if ( a.z !== b.z ) {
  14652. return a.z - b.z;
  14653. } else {
  14654. return a.id - b.id;
  14655. }
  14656. }
  14657. function reversePainterSortStable( a, b ) {
  14658. if ( a.renderOrder !== b.renderOrder ) {
  14659. return a.renderOrder - b.renderOrder;
  14660. } if ( a.z !== b.z ) {
  14661. return b.z - a.z;
  14662. } else {
  14663. return a.id - b.id;
  14664. }
  14665. }
  14666. function WebGLRenderList() {
  14667. var renderItems = [];
  14668. var renderItemsIndex = 0;
  14669. var opaque = [];
  14670. var transparent = [];
  14671. function init() {
  14672. renderItemsIndex = 0;
  14673. opaque.length = 0;
  14674. transparent.length = 0;
  14675. }
  14676. function push( object, geometry, material, z, group ) {
  14677. var renderItem = renderItems[ renderItemsIndex ];
  14678. if ( renderItem === undefined ) {
  14679. renderItem = {
  14680. id: object.id,
  14681. object: object,
  14682. geometry: geometry,
  14683. material: material,
  14684. program: material.program,
  14685. renderOrder: object.renderOrder,
  14686. z: z,
  14687. group: group
  14688. };
  14689. renderItems[ renderItemsIndex ] = renderItem;
  14690. } else {
  14691. renderItem.id = object.id;
  14692. renderItem.object = object;
  14693. renderItem.geometry = geometry;
  14694. renderItem.material = material;
  14695. renderItem.program = material.program;
  14696. renderItem.renderOrder = object.renderOrder;
  14697. renderItem.z = z;
  14698. renderItem.group = group;
  14699. }
  14700. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  14701. renderItemsIndex ++;
  14702. }
  14703. function sort() {
  14704. if ( opaque.length > 1 ) opaque.sort( painterSortStable );
  14705. if ( transparent.length > 1 ) transparent.sort( reversePainterSortStable );
  14706. }
  14707. return {
  14708. opaque: opaque,
  14709. transparent: transparent,
  14710. init: init,
  14711. push: push,
  14712. sort: sort
  14713. };
  14714. }
  14715. function WebGLRenderLists() {
  14716. var lists = {};
  14717. function get( scene, camera ) {
  14718. var hash = scene.id + ',' + camera.id;
  14719. var list = lists[ hash ];
  14720. if ( list === undefined ) {
  14721. // console.log( 'THREE.WebGLRenderLists:', hash );
  14722. list = new WebGLRenderList();
  14723. lists[ hash ] = list;
  14724. }
  14725. return list;
  14726. }
  14727. function dispose() {
  14728. lists = {};
  14729. }
  14730. return {
  14731. get: get,
  14732. dispose: dispose
  14733. };
  14734. }
  14735. /**
  14736. * @author mrdoob / http://mrdoob.com/
  14737. */
  14738. function UniformsCache() {
  14739. var lights = {};
  14740. return {
  14741. get: function ( light ) {
  14742. if ( lights[ light.id ] !== undefined ) {
  14743. return lights[ light.id ];
  14744. }
  14745. var uniforms;
  14746. switch ( light.type ) {
  14747. case 'DirectionalLight':
  14748. uniforms = {
  14749. direction: new Vector3(),
  14750. color: new Color(),
  14751. shadow: false,
  14752. shadowBias: 0,
  14753. shadowRadius: 1,
  14754. shadowMapSize: new Vector2()
  14755. };
  14756. break;
  14757. case 'SpotLight':
  14758. uniforms = {
  14759. position: new Vector3(),
  14760. direction: new Vector3(),
  14761. color: new Color(),
  14762. distance: 0,
  14763. coneCos: 0,
  14764. penumbraCos: 0,
  14765. decay: 0,
  14766. shadow: false,
  14767. shadowBias: 0,
  14768. shadowRadius: 1,
  14769. shadowMapSize: new Vector2()
  14770. };
  14771. break;
  14772. case 'PointLight':
  14773. uniforms = {
  14774. position: new Vector3(),
  14775. color: new Color(),
  14776. distance: 0,
  14777. decay: 0,
  14778. shadow: false,
  14779. shadowBias: 0,
  14780. shadowRadius: 1,
  14781. shadowMapSize: new Vector2(),
  14782. shadowCameraNear: 1,
  14783. shadowCameraFar: 1000
  14784. };
  14785. break;
  14786. case 'HemisphereLight':
  14787. uniforms = {
  14788. direction: new Vector3(),
  14789. skyColor: new Color(),
  14790. groundColor: new Color()
  14791. };
  14792. break;
  14793. case 'RectAreaLight':
  14794. uniforms = {
  14795. color: new Color(),
  14796. position: new Vector3(),
  14797. halfWidth: new Vector3(),
  14798. halfHeight: new Vector3()
  14799. // TODO (abelnation): set RectAreaLight shadow uniforms
  14800. };
  14801. break;
  14802. }
  14803. lights[ light.id ] = uniforms;
  14804. return uniforms;
  14805. }
  14806. };
  14807. }
  14808. var count = 0;
  14809. function WebGLLights() {
  14810. var cache = new UniformsCache();
  14811. var state = {
  14812. id: count ++,
  14813. hash: '',
  14814. ambient: [ 0, 0, 0 ],
  14815. directional: [],
  14816. directionalShadowMap: [],
  14817. directionalShadowMatrix: [],
  14818. spot: [],
  14819. spotShadowMap: [],
  14820. spotShadowMatrix: [],
  14821. rectArea: [],
  14822. point: [],
  14823. pointShadowMap: [],
  14824. pointShadowMatrix: [],
  14825. hemi: []
  14826. };
  14827. var vector3 = new Vector3();
  14828. var matrix4 = new Matrix4();
  14829. var matrix42 = new Matrix4();
  14830. function setup( lights, shadows, camera ) {
  14831. var r = 0, g = 0, b = 0;
  14832. var directionalLength = 0;
  14833. var pointLength = 0;
  14834. var spotLength = 0;
  14835. var rectAreaLength = 0;
  14836. var hemiLength = 0;
  14837. var viewMatrix = camera.matrixWorldInverse;
  14838. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  14839. var light = lights[ i ];
  14840. var color = light.color;
  14841. var intensity = light.intensity;
  14842. var distance = light.distance;
  14843. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  14844. if ( light.isAmbientLight ) {
  14845. r += color.r * intensity;
  14846. g += color.g * intensity;
  14847. b += color.b * intensity;
  14848. } else if ( light.isDirectionalLight ) {
  14849. var uniforms = cache.get( light );
  14850. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  14851. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14852. vector3.setFromMatrixPosition( light.target.matrixWorld );
  14853. uniforms.direction.sub( vector3 );
  14854. uniforms.direction.transformDirection( viewMatrix );
  14855. uniforms.shadow = light.castShadow;
  14856. if ( light.castShadow ) {
  14857. var shadow = light.shadow;
  14858. uniforms.shadowBias = shadow.bias;
  14859. uniforms.shadowRadius = shadow.radius;
  14860. uniforms.shadowMapSize = shadow.mapSize;
  14861. }
  14862. state.directionalShadowMap[ directionalLength ] = shadowMap;
  14863. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  14864. state.directional[ directionalLength ] = uniforms;
  14865. directionalLength ++;
  14866. } else if ( light.isSpotLight ) {
  14867. var uniforms = cache.get( light );
  14868. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14869. uniforms.position.applyMatrix4( viewMatrix );
  14870. uniforms.color.copy( color ).multiplyScalar( intensity );
  14871. uniforms.distance = distance;
  14872. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14873. vector3.setFromMatrixPosition( light.target.matrixWorld );
  14874. uniforms.direction.sub( vector3 );
  14875. uniforms.direction.transformDirection( viewMatrix );
  14876. uniforms.coneCos = Math.cos( light.angle );
  14877. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  14878. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  14879. uniforms.shadow = light.castShadow;
  14880. if ( light.castShadow ) {
  14881. var shadow = light.shadow;
  14882. uniforms.shadowBias = shadow.bias;
  14883. uniforms.shadowRadius = shadow.radius;
  14884. uniforms.shadowMapSize = shadow.mapSize;
  14885. }
  14886. state.spotShadowMap[ spotLength ] = shadowMap;
  14887. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  14888. state.spot[ spotLength ] = uniforms;
  14889. spotLength ++;
  14890. } else if ( light.isRectAreaLight ) {
  14891. var uniforms = cache.get( light );
  14892. // (a) intensity is the total visible light emitted
  14893. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  14894. // (b) intensity is the brightness of the light
  14895. uniforms.color.copy( color ).multiplyScalar( intensity );
  14896. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14897. uniforms.position.applyMatrix4( viewMatrix );
  14898. // extract local rotation of light to derive width/height half vectors
  14899. matrix42.identity();
  14900. matrix4.copy( light.matrixWorld );
  14901. matrix4.premultiply( viewMatrix );
  14902. matrix42.extractRotation( matrix4 );
  14903. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  14904. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  14905. uniforms.halfWidth.applyMatrix4( matrix42 );
  14906. uniforms.halfHeight.applyMatrix4( matrix42 );
  14907. // TODO (abelnation): RectAreaLight distance?
  14908. // uniforms.distance = distance;
  14909. state.rectArea[ rectAreaLength ] = uniforms;
  14910. rectAreaLength ++;
  14911. } else if ( light.isPointLight ) {
  14912. var uniforms = cache.get( light );
  14913. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14914. uniforms.position.applyMatrix4( viewMatrix );
  14915. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  14916. uniforms.distance = light.distance;
  14917. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  14918. uniforms.shadow = light.castShadow;
  14919. if ( light.castShadow ) {
  14920. var shadow = light.shadow;
  14921. uniforms.shadowBias = shadow.bias;
  14922. uniforms.shadowRadius = shadow.radius;
  14923. uniforms.shadowMapSize = shadow.mapSize;
  14924. uniforms.shadowCameraNear = shadow.camera.near;
  14925. uniforms.shadowCameraFar = shadow.camera.far;
  14926. }
  14927. state.pointShadowMap[ pointLength ] = shadowMap;
  14928. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  14929. state.point[ pointLength ] = uniforms;
  14930. pointLength ++;
  14931. } else if ( light.isHemisphereLight ) {
  14932. var uniforms = cache.get( light );
  14933. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14934. uniforms.direction.transformDirection( viewMatrix );
  14935. uniforms.direction.normalize();
  14936. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  14937. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  14938. state.hemi[ hemiLength ] = uniforms;
  14939. hemiLength ++;
  14940. }
  14941. }
  14942. state.ambient[ 0 ] = r;
  14943. state.ambient[ 1 ] = g;
  14944. state.ambient[ 2 ] = b;
  14945. state.directional.length = directionalLength;
  14946. state.spot.length = spotLength;
  14947. state.rectArea.length = rectAreaLength;
  14948. state.point.length = pointLength;
  14949. state.hemi.length = hemiLength;
  14950. state.hash = state.id + ',' + directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + shadows.length;
  14951. }
  14952. return {
  14953. setup: setup,
  14954. state: state
  14955. };
  14956. }
  14957. /**
  14958. * @author Mugen87 / https://github.com/Mugen87
  14959. */
  14960. function WebGLRenderState() {
  14961. var lights = new WebGLLights();
  14962. var lightsArray = [];
  14963. var shadowsArray = [];
  14964. var spritesArray = [];
  14965. function init() {
  14966. lightsArray.length = 0;
  14967. shadowsArray.length = 0;
  14968. spritesArray.length = 0;
  14969. }
  14970. function pushLight( light ) {
  14971. lightsArray.push( light );
  14972. }
  14973. function pushShadow( shadowLight ) {
  14974. shadowsArray.push( shadowLight );
  14975. }
  14976. function pushSprite( shadowLight ) {
  14977. spritesArray.push( shadowLight );
  14978. }
  14979. function setupLights( camera ) {
  14980. lights.setup( lightsArray, shadowsArray, camera );
  14981. }
  14982. var state = {
  14983. lightsArray: lightsArray,
  14984. shadowsArray: shadowsArray,
  14985. spritesArray: spritesArray,
  14986. lights: lights
  14987. };
  14988. return {
  14989. init: init,
  14990. state: state,
  14991. setupLights: setupLights,
  14992. pushLight: pushLight,
  14993. pushShadow: pushShadow,
  14994. pushSprite: pushSprite
  14995. };
  14996. }
  14997. function WebGLRenderStates() {
  14998. var renderStates = {};
  14999. function get( scene, camera ) {
  15000. var hash = scene.id + ',' + camera.id;
  15001. var renderState = renderStates[ hash ];
  15002. if ( renderState === undefined ) {
  15003. renderState = new WebGLRenderState();
  15004. renderStates[ hash ] = renderState;
  15005. }
  15006. return renderState;
  15007. }
  15008. function dispose() {
  15009. renderStates = {};
  15010. }
  15011. return {
  15012. get: get,
  15013. dispose: dispose
  15014. };
  15015. }
  15016. /**
  15017. * @author mrdoob / http://mrdoob.com/
  15018. * @author alteredq / http://alteredqualia.com/
  15019. * @author bhouston / https://clara.io
  15020. * @author WestLangley / http://github.com/WestLangley
  15021. *
  15022. * parameters = {
  15023. *
  15024. * opacity: <float>,
  15025. *
  15026. * map: new THREE.Texture( <Image> ),
  15027. *
  15028. * alphaMap: new THREE.Texture( <Image> ),
  15029. *
  15030. * displacementMap: new THREE.Texture( <Image> ),
  15031. * displacementScale: <float>,
  15032. * displacementBias: <float>,
  15033. *
  15034. * wireframe: <boolean>,
  15035. * wireframeLinewidth: <float>
  15036. * }
  15037. */
  15038. function MeshDepthMaterial( parameters ) {
  15039. Material.call( this );
  15040. this.type = 'MeshDepthMaterial';
  15041. this.depthPacking = BasicDepthPacking;
  15042. this.skinning = false;
  15043. this.morphTargets = false;
  15044. this.map = null;
  15045. this.alphaMap = null;
  15046. this.displacementMap = null;
  15047. this.displacementScale = 1;
  15048. this.displacementBias = 0;
  15049. this.wireframe = false;
  15050. this.wireframeLinewidth = 1;
  15051. this.fog = false;
  15052. this.lights = false;
  15053. this.setValues( parameters );
  15054. }
  15055. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  15056. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  15057. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  15058. MeshDepthMaterial.prototype.copy = function ( source ) {
  15059. Material.prototype.copy.call( this, source );
  15060. this.depthPacking = source.depthPacking;
  15061. this.skinning = source.skinning;
  15062. this.morphTargets = source.morphTargets;
  15063. this.map = source.map;
  15064. this.alphaMap = source.alphaMap;
  15065. this.displacementMap = source.displacementMap;
  15066. this.displacementScale = source.displacementScale;
  15067. this.displacementBias = source.displacementBias;
  15068. this.wireframe = source.wireframe;
  15069. this.wireframeLinewidth = source.wireframeLinewidth;
  15070. return this;
  15071. };
  15072. /**
  15073. * @author WestLangley / http://github.com/WestLangley
  15074. *
  15075. * parameters = {
  15076. *
  15077. * referencePosition: <float>,
  15078. * nearDistance: <float>,
  15079. * farDistance: <float>,
  15080. *
  15081. * skinning: <bool>,
  15082. * morphTargets: <bool>,
  15083. *
  15084. * map: new THREE.Texture( <Image> ),
  15085. *
  15086. * alphaMap: new THREE.Texture( <Image> ),
  15087. *
  15088. * displacementMap: new THREE.Texture( <Image> ),
  15089. * displacementScale: <float>,
  15090. * displacementBias: <float>
  15091. *
  15092. * }
  15093. */
  15094. function MeshDistanceMaterial( parameters ) {
  15095. Material.call( this );
  15096. this.type = 'MeshDistanceMaterial';
  15097. this.referencePosition = new Vector3();
  15098. this.nearDistance = 1;
  15099. this.farDistance = 1000;
  15100. this.skinning = false;
  15101. this.morphTargets = false;
  15102. this.map = null;
  15103. this.alphaMap = null;
  15104. this.displacementMap = null;
  15105. this.displacementScale = 1;
  15106. this.displacementBias = 0;
  15107. this.fog = false;
  15108. this.lights = false;
  15109. this.setValues( parameters );
  15110. }
  15111. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  15112. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  15113. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  15114. MeshDistanceMaterial.prototype.copy = function ( source ) {
  15115. Material.prototype.copy.call( this, source );
  15116. this.referencePosition.copy( source.referencePosition );
  15117. this.nearDistance = source.nearDistance;
  15118. this.farDistance = source.farDistance;
  15119. this.skinning = source.skinning;
  15120. this.morphTargets = source.morphTargets;
  15121. this.map = source.map;
  15122. this.alphaMap = source.alphaMap;
  15123. this.displacementMap = source.displacementMap;
  15124. this.displacementScale = source.displacementScale;
  15125. this.displacementBias = source.displacementBias;
  15126. return this;
  15127. };
  15128. /**
  15129. * @author alteredq / http://alteredqualia.com/
  15130. * @author mrdoob / http://mrdoob.com/
  15131. */
  15132. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  15133. var _frustum = new Frustum(),
  15134. _projScreenMatrix = new Matrix4(),
  15135. _shadowMapSize = new Vector2(),
  15136. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  15137. _lookTarget = new Vector3(),
  15138. _lightPositionWorld = new Vector3(),
  15139. _MorphingFlag = 1,
  15140. _SkinningFlag = 2,
  15141. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  15142. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  15143. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  15144. _materialCache = {};
  15145. var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  15146. var cubeDirections = [
  15147. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  15148. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  15149. ];
  15150. var cubeUps = [
  15151. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  15152. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  15153. ];
  15154. var cube2DViewPorts = [
  15155. new Vector4(), new Vector4(), new Vector4(),
  15156. new Vector4(), new Vector4(), new Vector4()
  15157. ];
  15158. // init
  15159. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  15160. var useMorphing = ( i & _MorphingFlag ) !== 0;
  15161. var useSkinning = ( i & _SkinningFlag ) !== 0;
  15162. var depthMaterial = new MeshDepthMaterial( {
  15163. depthPacking: RGBADepthPacking,
  15164. morphTargets: useMorphing,
  15165. skinning: useSkinning
  15166. } );
  15167. _depthMaterials[ i ] = depthMaterial;
  15168. //
  15169. var distanceMaterial = new MeshDistanceMaterial( {
  15170. morphTargets: useMorphing,
  15171. skinning: useSkinning
  15172. } );
  15173. _distanceMaterials[ i ] = distanceMaterial;
  15174. }
  15175. //
  15176. var scope = this;
  15177. this.enabled = false;
  15178. this.autoUpdate = true;
  15179. this.needsUpdate = false;
  15180. this.type = PCFShadowMap;
  15181. this.render = function ( lights, scene, camera ) {
  15182. if ( scope.enabled === false ) return;
  15183. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  15184. if ( lights.length === 0 ) return;
  15185. // TODO Clean up (needed in case of contextlost)
  15186. var _gl = _renderer.context;
  15187. var _state = _renderer.state;
  15188. // Set GL state for depth map.
  15189. _state.disable( _gl.BLEND );
  15190. _state.buffers.color.setClear( 1, 1, 1, 1 );
  15191. _state.buffers.depth.setTest( true );
  15192. _state.setScissorTest( false );
  15193. // render depth map
  15194. var faceCount;
  15195. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  15196. var light = lights[ i ];
  15197. var shadow = light.shadow;
  15198. var isPointLight = light && light.isPointLight;
  15199. if ( shadow === undefined ) {
  15200. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  15201. continue;
  15202. }
  15203. var shadowCamera = shadow.camera;
  15204. _shadowMapSize.copy( shadow.mapSize );
  15205. _shadowMapSize.min( _maxShadowMapSize );
  15206. if ( isPointLight ) {
  15207. var vpWidth = _shadowMapSize.x;
  15208. var vpHeight = _shadowMapSize.y;
  15209. // These viewports map a cube-map onto a 2D texture with the
  15210. // following orientation:
  15211. //
  15212. // xzXZ
  15213. // y Y
  15214. //
  15215. // X - Positive x direction
  15216. // x - Negative x direction
  15217. // Y - Positive y direction
  15218. // y - Negative y direction
  15219. // Z - Positive z direction
  15220. // z - Negative z direction
  15221. // positive X
  15222. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  15223. // negative X
  15224. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  15225. // positive Z
  15226. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  15227. // negative Z
  15228. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  15229. // positive Y
  15230. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  15231. // negative Y
  15232. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  15233. _shadowMapSize.x *= 4.0;
  15234. _shadowMapSize.y *= 2.0;
  15235. }
  15236. if ( shadow.map === null ) {
  15237. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  15238. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  15239. shadow.map.texture.name = light.name + ".shadowMap";
  15240. shadowCamera.updateProjectionMatrix();
  15241. }
  15242. if ( shadow.isSpotLightShadow ) {
  15243. shadow.update( light );
  15244. }
  15245. var shadowMap = shadow.map;
  15246. var shadowMatrix = shadow.matrix;
  15247. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  15248. shadowCamera.position.copy( _lightPositionWorld );
  15249. if ( isPointLight ) {
  15250. faceCount = 6;
  15251. // for point lights we set the shadow matrix to be a translation-only matrix
  15252. // equal to inverse of the light's position
  15253. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  15254. } else {
  15255. faceCount = 1;
  15256. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  15257. shadowCamera.lookAt( _lookTarget );
  15258. shadowCamera.updateMatrixWorld();
  15259. // compute shadow matrix
  15260. shadowMatrix.set(
  15261. 0.5, 0.0, 0.0, 0.5,
  15262. 0.0, 0.5, 0.0, 0.5,
  15263. 0.0, 0.0, 0.5, 0.5,
  15264. 0.0, 0.0, 0.0, 1.0
  15265. );
  15266. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  15267. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  15268. }
  15269. _renderer.setRenderTarget( shadowMap );
  15270. _renderer.clear();
  15271. // render shadow map for each cube face (if omni-directional) or
  15272. // run a single pass if not
  15273. for ( var face = 0; face < faceCount; face ++ ) {
  15274. if ( isPointLight ) {
  15275. _lookTarget.copy( shadowCamera.position );
  15276. _lookTarget.add( cubeDirections[ face ] );
  15277. shadowCamera.up.copy( cubeUps[ face ] );
  15278. shadowCamera.lookAt( _lookTarget );
  15279. shadowCamera.updateMatrixWorld();
  15280. var vpDimensions = cube2DViewPorts[ face ];
  15281. _state.viewport( vpDimensions );
  15282. }
  15283. // update camera matrices and frustum
  15284. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  15285. _frustum.setFromMatrix( _projScreenMatrix );
  15286. // set object matrices & frustum culling
  15287. renderObject( scene, camera, shadowCamera, isPointLight );
  15288. }
  15289. }
  15290. scope.needsUpdate = false;
  15291. };
  15292. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  15293. var geometry = object.geometry;
  15294. var result = null;
  15295. var materialVariants = _depthMaterials;
  15296. var customMaterial = object.customDepthMaterial;
  15297. if ( isPointLight ) {
  15298. materialVariants = _distanceMaterials;
  15299. customMaterial = object.customDistanceMaterial;
  15300. }
  15301. if ( ! customMaterial ) {
  15302. var useMorphing = false;
  15303. if ( material.morphTargets ) {
  15304. if ( geometry && geometry.isBufferGeometry ) {
  15305. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  15306. } else if ( geometry && geometry.isGeometry ) {
  15307. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  15308. }
  15309. }
  15310. if ( object.isSkinnedMesh && material.skinning === false ) {
  15311. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  15312. }
  15313. var useSkinning = object.isSkinnedMesh && material.skinning;
  15314. var variantIndex = 0;
  15315. if ( useMorphing ) variantIndex |= _MorphingFlag;
  15316. if ( useSkinning ) variantIndex |= _SkinningFlag;
  15317. result = materialVariants[ variantIndex ];
  15318. } else {
  15319. result = customMaterial;
  15320. }
  15321. if ( _renderer.localClippingEnabled &&
  15322. material.clipShadows === true &&
  15323. material.clippingPlanes.length !== 0 ) {
  15324. // in this case we need a unique material instance reflecting the
  15325. // appropriate state
  15326. var keyA = result.uuid, keyB = material.uuid;
  15327. var materialsForVariant = _materialCache[ keyA ];
  15328. if ( materialsForVariant === undefined ) {
  15329. materialsForVariant = {};
  15330. _materialCache[ keyA ] = materialsForVariant;
  15331. }
  15332. var cachedMaterial = materialsForVariant[ keyB ];
  15333. if ( cachedMaterial === undefined ) {
  15334. cachedMaterial = result.clone();
  15335. materialsForVariant[ keyB ] = cachedMaterial;
  15336. }
  15337. result = cachedMaterial;
  15338. }
  15339. result.visible = material.visible;
  15340. result.wireframe = material.wireframe;
  15341. result.side = ( material.shadowSide != null ) ? material.shadowSide : shadowSide[ material.side ];
  15342. result.clipShadows = material.clipShadows;
  15343. result.clippingPlanes = material.clippingPlanes;
  15344. result.clipIntersection = material.clipIntersection;
  15345. result.wireframeLinewidth = material.wireframeLinewidth;
  15346. result.linewidth = material.linewidth;
  15347. if ( isPointLight && result.isMeshDistanceMaterial ) {
  15348. result.referencePosition.copy( lightPositionWorld );
  15349. result.nearDistance = shadowCameraNear;
  15350. result.farDistance = shadowCameraFar;
  15351. }
  15352. return result;
  15353. }
  15354. function renderObject( object, camera, shadowCamera, isPointLight ) {
  15355. if ( object.visible === false ) return;
  15356. var visible = object.layers.test( camera.layers );
  15357. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  15358. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  15359. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  15360. var geometry = _objects.update( object );
  15361. var material = object.material;
  15362. if ( Array.isArray( material ) ) {
  15363. var groups = geometry.groups;
  15364. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  15365. var group = groups[ k ];
  15366. var groupMaterial = material[ group.materialIndex ];
  15367. if ( groupMaterial && groupMaterial.visible ) {
  15368. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  15369. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  15370. }
  15371. }
  15372. } else if ( material.visible ) {
  15373. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  15374. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  15375. }
  15376. }
  15377. }
  15378. var children = object.children;
  15379. for ( var i = 0, l = children.length; i < l; i ++ ) {
  15380. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  15381. }
  15382. }
  15383. }
  15384. /**
  15385. * @author mrdoob / http://mrdoob.com/
  15386. */
  15387. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  15388. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15389. this.needsUpdate = true;
  15390. }
  15391. CanvasTexture.prototype = Object.create( Texture.prototype );
  15392. CanvasTexture.prototype.constructor = CanvasTexture;
  15393. /**
  15394. * @author mikael emtinger / http://gomo.se/
  15395. * @author alteredq / http://alteredqualia.com/
  15396. */
  15397. function WebGLSpriteRenderer( renderer, gl, state, textures, capabilities ) {
  15398. var vertexBuffer, elementBuffer;
  15399. var program, attributes, uniforms;
  15400. var texture;
  15401. // decompose matrixWorld
  15402. var spritePosition = new Vector3();
  15403. var spriteRotation = new Quaternion();
  15404. var spriteScale = new Vector3();
  15405. function init() {
  15406. var vertices = new Float32Array( [
  15407. - 0.5, - 0.5, 0, 0,
  15408. 0.5, - 0.5, 1, 0,
  15409. 0.5, 0.5, 1, 1,
  15410. - 0.5, 0.5, 0, 1
  15411. ] );
  15412. var faces = new Uint16Array( [
  15413. 0, 1, 2,
  15414. 0, 2, 3
  15415. ] );
  15416. vertexBuffer = gl.createBuffer();
  15417. elementBuffer = gl.createBuffer();
  15418. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15419. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  15420. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15421. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  15422. program = createProgram();
  15423. attributes = {
  15424. position: gl.getAttribLocation( program, 'position' ),
  15425. uv: gl.getAttribLocation( program, 'uv' )
  15426. };
  15427. uniforms = {
  15428. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  15429. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  15430. rotation: gl.getUniformLocation( program, 'rotation' ),
  15431. center: gl.getUniformLocation( program, 'center' ),
  15432. scale: gl.getUniformLocation( program, 'scale' ),
  15433. color: gl.getUniformLocation( program, 'color' ),
  15434. map: gl.getUniformLocation( program, 'map' ),
  15435. opacity: gl.getUniformLocation( program, 'opacity' ),
  15436. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  15437. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  15438. fogType: gl.getUniformLocation( program, 'fogType' ),
  15439. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  15440. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  15441. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  15442. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  15443. fogDepth: gl.getUniformLocation( program, 'fogDepth' ),
  15444. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  15445. };
  15446. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  15447. canvas.width = 8;
  15448. canvas.height = 8;
  15449. var context = canvas.getContext( '2d' );
  15450. context.fillStyle = 'white';
  15451. context.fillRect( 0, 0, 8, 8 );
  15452. texture = new CanvasTexture( canvas );
  15453. }
  15454. this.render = function ( sprites, scene, camera ) {
  15455. if ( sprites.length === 0 ) return;
  15456. // setup gl
  15457. if ( program === undefined ) {
  15458. init();
  15459. }
  15460. state.useProgram( program );
  15461. state.initAttributes();
  15462. state.enableAttribute( attributes.position );
  15463. state.enableAttribute( attributes.uv );
  15464. state.disableUnusedAttributes();
  15465. state.disable( gl.CULL_FACE );
  15466. state.enable( gl.BLEND );
  15467. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15468. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  15469. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  15470. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15471. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15472. state.activeTexture( gl.TEXTURE0 );
  15473. gl.uniform1i( uniforms.map, 0 );
  15474. var oldFogType = 0;
  15475. var sceneFogType = 0;
  15476. var fog = scene.fog;
  15477. if ( fog ) {
  15478. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  15479. if ( fog.isFog ) {
  15480. gl.uniform1f( uniforms.fogNear, fog.near );
  15481. gl.uniform1f( uniforms.fogFar, fog.far );
  15482. gl.uniform1i( uniforms.fogType, 1 );
  15483. oldFogType = 1;
  15484. sceneFogType = 1;
  15485. } else if ( fog.isFogExp2 ) {
  15486. gl.uniform1f( uniforms.fogDensity, fog.density );
  15487. gl.uniform1i( uniforms.fogType, 2 );
  15488. oldFogType = 2;
  15489. sceneFogType = 2;
  15490. }
  15491. } else {
  15492. gl.uniform1i( uniforms.fogType, 0 );
  15493. oldFogType = 0;
  15494. sceneFogType = 0;
  15495. }
  15496. // update positions and sort
  15497. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15498. var sprite = sprites[ i ];
  15499. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  15500. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  15501. }
  15502. sprites.sort( painterSortStable );
  15503. // render all sprites
  15504. var scale = [];
  15505. var center = [];
  15506. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15507. var sprite = sprites[ i ];
  15508. var material = sprite.material;
  15509. if ( material.visible === false ) continue;
  15510. sprite.onBeforeRender( renderer, scene, camera, undefined, material, undefined );
  15511. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  15512. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  15513. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  15514. scale[ 0 ] = spriteScale.x;
  15515. scale[ 1 ] = spriteScale.y;
  15516. center[ 0 ] = sprite.center.x - 0.5;
  15517. center[ 1 ] = sprite.center.y - 0.5;
  15518. var fogType = 0;
  15519. if ( scene.fog && material.fog ) {
  15520. fogType = sceneFogType;
  15521. }
  15522. if ( oldFogType !== fogType ) {
  15523. gl.uniform1i( uniforms.fogType, fogType );
  15524. oldFogType = fogType;
  15525. }
  15526. if ( material.map !== null ) {
  15527. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  15528. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  15529. } else {
  15530. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  15531. gl.uniform2f( uniforms.uvScale, 1, 1 );
  15532. }
  15533. gl.uniform1f( uniforms.opacity, material.opacity );
  15534. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  15535. gl.uniform1f( uniforms.rotation, material.rotation );
  15536. gl.uniform2fv( uniforms.center, center );
  15537. gl.uniform2fv( uniforms.scale, scale );
  15538. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  15539. state.buffers.depth.setTest( material.depthTest );
  15540. state.buffers.depth.setMask( material.depthWrite );
  15541. state.buffers.color.setMask( material.colorWrite );
  15542. textures.setTexture2D( material.map || texture, 0 );
  15543. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15544. sprite.onAfterRender( renderer, scene, camera, undefined, material, undefined );
  15545. }
  15546. // restore gl
  15547. state.enable( gl.CULL_FACE );
  15548. state.reset();
  15549. };
  15550. function createProgram() {
  15551. var program = gl.createProgram();
  15552. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  15553. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  15554. gl.shaderSource( vertexShader, [
  15555. 'precision ' + capabilities.precision + ' float;',
  15556. '#define SHADER_NAME ' + 'SpriteMaterial',
  15557. 'uniform mat4 modelViewMatrix;',
  15558. 'uniform mat4 projectionMatrix;',
  15559. 'uniform float rotation;',
  15560. 'uniform vec2 center;',
  15561. 'uniform vec2 scale;',
  15562. 'uniform vec2 uvOffset;',
  15563. 'uniform vec2 uvScale;',
  15564. 'attribute vec2 position;',
  15565. 'attribute vec2 uv;',
  15566. 'varying vec2 vUV;',
  15567. 'varying float fogDepth;',
  15568. 'void main() {',
  15569. ' vUV = uvOffset + uv * uvScale;',
  15570. ' vec2 alignedPosition = ( position - center ) * scale;',
  15571. ' vec2 rotatedPosition;',
  15572. ' rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  15573. ' rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  15574. ' vec4 mvPosition;',
  15575. ' mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  15576. ' mvPosition.xy += rotatedPosition;',
  15577. ' gl_Position = projectionMatrix * mvPosition;',
  15578. ' fogDepth = - mvPosition.z;',
  15579. '}'
  15580. ].join( '\n' ) );
  15581. gl.shaderSource( fragmentShader, [
  15582. 'precision ' + capabilities.precision + ' float;',
  15583. '#define SHADER_NAME ' + 'SpriteMaterial',
  15584. 'uniform vec3 color;',
  15585. 'uniform sampler2D map;',
  15586. 'uniform float opacity;',
  15587. 'uniform int fogType;',
  15588. 'uniform vec3 fogColor;',
  15589. 'uniform float fogDensity;',
  15590. 'uniform float fogNear;',
  15591. 'uniform float fogFar;',
  15592. 'uniform float alphaTest;',
  15593. 'varying vec2 vUV;',
  15594. 'varying float fogDepth;',
  15595. 'void main() {',
  15596. ' vec4 texture = texture2D( map, vUV );',
  15597. ' gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  15598. ' if ( gl_FragColor.a < alphaTest ) discard;',
  15599. ' if ( fogType > 0 ) {',
  15600. ' float fogFactor = 0.0;',
  15601. ' if ( fogType == 1 ) {',
  15602. ' fogFactor = smoothstep( fogNear, fogFar, fogDepth );',
  15603. ' } else {',
  15604. ' const float LOG2 = 1.442695;',
  15605. ' fogFactor = exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 );',
  15606. ' fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  15607. ' }',
  15608. ' gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );',
  15609. ' }',
  15610. '}'
  15611. ].join( '\n' ) );
  15612. gl.compileShader( vertexShader );
  15613. gl.compileShader( fragmentShader );
  15614. gl.attachShader( program, vertexShader );
  15615. gl.attachShader( program, fragmentShader );
  15616. gl.linkProgram( program );
  15617. return program;
  15618. }
  15619. function painterSortStable( a, b ) {
  15620. if ( a.renderOrder !== b.renderOrder ) {
  15621. return a.renderOrder - b.renderOrder;
  15622. } else if ( a.z !== b.z ) {
  15623. return b.z - a.z;
  15624. } else {
  15625. return b.id - a.id;
  15626. }
  15627. }
  15628. }
  15629. /**
  15630. * @author mrdoob / http://mrdoob.com/
  15631. */
  15632. function WebGLState( gl, extensions, utils ) {
  15633. function ColorBuffer() {
  15634. var locked = false;
  15635. var color = new Vector4();
  15636. var currentColorMask = null;
  15637. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  15638. return {
  15639. setMask: function ( colorMask ) {
  15640. if ( currentColorMask !== colorMask && ! locked ) {
  15641. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  15642. currentColorMask = colorMask;
  15643. }
  15644. },
  15645. setLocked: function ( lock ) {
  15646. locked = lock;
  15647. },
  15648. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  15649. if ( premultipliedAlpha === true ) {
  15650. r *= a; g *= a; b *= a;
  15651. }
  15652. color.set( r, g, b, a );
  15653. if ( currentColorClear.equals( color ) === false ) {
  15654. gl.clearColor( r, g, b, a );
  15655. currentColorClear.copy( color );
  15656. }
  15657. },
  15658. reset: function () {
  15659. locked = false;
  15660. currentColorMask = null;
  15661. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  15662. }
  15663. };
  15664. }
  15665. function DepthBuffer() {
  15666. var locked = false;
  15667. var currentDepthMask = null;
  15668. var currentDepthFunc = null;
  15669. var currentDepthClear = null;
  15670. return {
  15671. setTest: function ( depthTest ) {
  15672. if ( depthTest ) {
  15673. enable( gl.DEPTH_TEST );
  15674. } else {
  15675. disable( gl.DEPTH_TEST );
  15676. }
  15677. },
  15678. setMask: function ( depthMask ) {
  15679. if ( currentDepthMask !== depthMask && ! locked ) {
  15680. gl.depthMask( depthMask );
  15681. currentDepthMask = depthMask;
  15682. }
  15683. },
  15684. setFunc: function ( depthFunc ) {
  15685. if ( currentDepthFunc !== depthFunc ) {
  15686. if ( depthFunc ) {
  15687. switch ( depthFunc ) {
  15688. case NeverDepth:
  15689. gl.depthFunc( gl.NEVER );
  15690. break;
  15691. case AlwaysDepth:
  15692. gl.depthFunc( gl.ALWAYS );
  15693. break;
  15694. case LessDepth:
  15695. gl.depthFunc( gl.LESS );
  15696. break;
  15697. case LessEqualDepth:
  15698. gl.depthFunc( gl.LEQUAL );
  15699. break;
  15700. case EqualDepth:
  15701. gl.depthFunc( gl.EQUAL );
  15702. break;
  15703. case GreaterEqualDepth:
  15704. gl.depthFunc( gl.GEQUAL );
  15705. break;
  15706. case GreaterDepth:
  15707. gl.depthFunc( gl.GREATER );
  15708. break;
  15709. case NotEqualDepth:
  15710. gl.depthFunc( gl.NOTEQUAL );
  15711. break;
  15712. default:
  15713. gl.depthFunc( gl.LEQUAL );
  15714. }
  15715. } else {
  15716. gl.depthFunc( gl.LEQUAL );
  15717. }
  15718. currentDepthFunc = depthFunc;
  15719. }
  15720. },
  15721. setLocked: function ( lock ) {
  15722. locked = lock;
  15723. },
  15724. setClear: function ( depth ) {
  15725. if ( currentDepthClear !== depth ) {
  15726. gl.clearDepth( depth );
  15727. currentDepthClear = depth;
  15728. }
  15729. },
  15730. reset: function () {
  15731. locked = false;
  15732. currentDepthMask = null;
  15733. currentDepthFunc = null;
  15734. currentDepthClear = null;
  15735. }
  15736. };
  15737. }
  15738. function StencilBuffer() {
  15739. var locked = false;
  15740. var currentStencilMask = null;
  15741. var currentStencilFunc = null;
  15742. var currentStencilRef = null;
  15743. var currentStencilFuncMask = null;
  15744. var currentStencilFail = null;
  15745. var currentStencilZFail = null;
  15746. var currentStencilZPass = null;
  15747. var currentStencilClear = null;
  15748. return {
  15749. setTest: function ( stencilTest ) {
  15750. if ( stencilTest ) {
  15751. enable( gl.STENCIL_TEST );
  15752. } else {
  15753. disable( gl.STENCIL_TEST );
  15754. }
  15755. },
  15756. setMask: function ( stencilMask ) {
  15757. if ( currentStencilMask !== stencilMask && ! locked ) {
  15758. gl.stencilMask( stencilMask );
  15759. currentStencilMask = stencilMask;
  15760. }
  15761. },
  15762. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  15763. if ( currentStencilFunc !== stencilFunc ||
  15764. currentStencilRef !== stencilRef ||
  15765. currentStencilFuncMask !== stencilMask ) {
  15766. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  15767. currentStencilFunc = stencilFunc;
  15768. currentStencilRef = stencilRef;
  15769. currentStencilFuncMask = stencilMask;
  15770. }
  15771. },
  15772. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  15773. if ( currentStencilFail !== stencilFail ||
  15774. currentStencilZFail !== stencilZFail ||
  15775. currentStencilZPass !== stencilZPass ) {
  15776. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  15777. currentStencilFail = stencilFail;
  15778. currentStencilZFail = stencilZFail;
  15779. currentStencilZPass = stencilZPass;
  15780. }
  15781. },
  15782. setLocked: function ( lock ) {
  15783. locked = lock;
  15784. },
  15785. setClear: function ( stencil ) {
  15786. if ( currentStencilClear !== stencil ) {
  15787. gl.clearStencil( stencil );
  15788. currentStencilClear = stencil;
  15789. }
  15790. },
  15791. reset: function () {
  15792. locked = false;
  15793. currentStencilMask = null;
  15794. currentStencilFunc = null;
  15795. currentStencilRef = null;
  15796. currentStencilFuncMask = null;
  15797. currentStencilFail = null;
  15798. currentStencilZFail = null;
  15799. currentStencilZPass = null;
  15800. currentStencilClear = null;
  15801. }
  15802. };
  15803. }
  15804. //
  15805. var colorBuffer = new ColorBuffer();
  15806. var depthBuffer = new DepthBuffer();
  15807. var stencilBuffer = new StencilBuffer();
  15808. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  15809. var newAttributes = new Uint8Array( maxVertexAttributes );
  15810. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  15811. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  15812. var capabilities = {};
  15813. var compressedTextureFormats = null;
  15814. var currentProgram = null;
  15815. var currentBlending = null;
  15816. var currentBlendEquation = null;
  15817. var currentBlendSrc = null;
  15818. var currentBlendDst = null;
  15819. var currentBlendEquationAlpha = null;
  15820. var currentBlendSrcAlpha = null;
  15821. var currentBlendDstAlpha = null;
  15822. var currentPremultipledAlpha = false;
  15823. var currentFlipSided = null;
  15824. var currentCullFace = null;
  15825. var currentLineWidth = null;
  15826. var currentPolygonOffsetFactor = null;
  15827. var currentPolygonOffsetUnits = null;
  15828. var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  15829. var lineWidthAvailable = false;
  15830. var version = 0;
  15831. var glVersion = gl.getParameter( gl.VERSION );
  15832. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  15833. version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
  15834. lineWidthAvailable = ( version >= 1.0 );
  15835. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  15836. version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
  15837. lineWidthAvailable = ( version >= 2.0 );
  15838. }
  15839. var currentTextureSlot = null;
  15840. var currentBoundTextures = {};
  15841. var currentScissor = new Vector4();
  15842. var currentViewport = new Vector4();
  15843. function createTexture( type, target, count ) {
  15844. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  15845. var texture = gl.createTexture();
  15846. gl.bindTexture( type, texture );
  15847. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  15848. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  15849. for ( var i = 0; i < count; i ++ ) {
  15850. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  15851. }
  15852. return texture;
  15853. }
  15854. var emptyTextures = {};
  15855. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  15856. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  15857. // init
  15858. colorBuffer.setClear( 0, 0, 0, 1 );
  15859. depthBuffer.setClear( 1 );
  15860. stencilBuffer.setClear( 0 );
  15861. enable( gl.DEPTH_TEST );
  15862. depthBuffer.setFunc( LessEqualDepth );
  15863. setFlipSided( false );
  15864. setCullFace( CullFaceBack );
  15865. enable( gl.CULL_FACE );
  15866. enable( gl.BLEND );
  15867. setBlending( NormalBlending );
  15868. //
  15869. function initAttributes() {
  15870. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  15871. newAttributes[ i ] = 0;
  15872. }
  15873. }
  15874. function enableAttribute( attribute ) {
  15875. newAttributes[ attribute ] = 1;
  15876. if ( enabledAttributes[ attribute ] === 0 ) {
  15877. gl.enableVertexAttribArray( attribute );
  15878. enabledAttributes[ attribute ] = 1;
  15879. }
  15880. if ( attributeDivisors[ attribute ] !== 0 ) {
  15881. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  15882. extension.vertexAttribDivisorANGLE( attribute, 0 );
  15883. attributeDivisors[ attribute ] = 0;
  15884. }
  15885. }
  15886. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  15887. newAttributes[ attribute ] = 1;
  15888. if ( enabledAttributes[ attribute ] === 0 ) {
  15889. gl.enableVertexAttribArray( attribute );
  15890. enabledAttributes[ attribute ] = 1;
  15891. }
  15892. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  15893. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  15894. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  15895. attributeDivisors[ attribute ] = meshPerAttribute;
  15896. }
  15897. }
  15898. function disableUnusedAttributes() {
  15899. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  15900. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  15901. gl.disableVertexAttribArray( i );
  15902. enabledAttributes[ i ] = 0;
  15903. }
  15904. }
  15905. }
  15906. function enable( id ) {
  15907. if ( capabilities[ id ] !== true ) {
  15908. gl.enable( id );
  15909. capabilities[ id ] = true;
  15910. }
  15911. }
  15912. function disable( id ) {
  15913. if ( capabilities[ id ] !== false ) {
  15914. gl.disable( id );
  15915. capabilities[ id ] = false;
  15916. }
  15917. }
  15918. function getCompressedTextureFormats() {
  15919. if ( compressedTextureFormats === null ) {
  15920. compressedTextureFormats = [];
  15921. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  15922. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  15923. extensions.get( 'WEBGL_compressed_texture_etc1' ) ||
  15924. extensions.get( 'WEBGL_compressed_texture_astc' ) ) {
  15925. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  15926. for ( var i = 0; i < formats.length; i ++ ) {
  15927. compressedTextureFormats.push( formats[ i ] );
  15928. }
  15929. }
  15930. }
  15931. return compressedTextureFormats;
  15932. }
  15933. function useProgram( program ) {
  15934. if ( currentProgram !== program ) {
  15935. gl.useProgram( program );
  15936. currentProgram = program;
  15937. return true;
  15938. }
  15939. return false;
  15940. }
  15941. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  15942. if ( blending !== NoBlending ) {
  15943. enable( gl.BLEND );
  15944. } else {
  15945. disable( gl.BLEND );
  15946. }
  15947. if ( blending !== CustomBlending ) {
  15948. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  15949. switch ( blending ) {
  15950. case AdditiveBlending:
  15951. if ( premultipliedAlpha ) {
  15952. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15953. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  15954. } else {
  15955. gl.blendEquation( gl.FUNC_ADD );
  15956. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  15957. }
  15958. break;
  15959. case SubtractiveBlending:
  15960. if ( premultipliedAlpha ) {
  15961. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15962. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  15963. } else {
  15964. gl.blendEquation( gl.FUNC_ADD );
  15965. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  15966. }
  15967. break;
  15968. case MultiplyBlending:
  15969. if ( premultipliedAlpha ) {
  15970. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15971. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  15972. } else {
  15973. gl.blendEquation( gl.FUNC_ADD );
  15974. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  15975. }
  15976. break;
  15977. default:
  15978. if ( premultipliedAlpha ) {
  15979. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15980. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  15981. } else {
  15982. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15983. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  15984. }
  15985. }
  15986. }
  15987. currentBlendEquation = null;
  15988. currentBlendSrc = null;
  15989. currentBlendDst = null;
  15990. currentBlendEquationAlpha = null;
  15991. currentBlendSrcAlpha = null;
  15992. currentBlendDstAlpha = null;
  15993. } else {
  15994. blendEquationAlpha = blendEquationAlpha || blendEquation;
  15995. blendSrcAlpha = blendSrcAlpha || blendSrc;
  15996. blendDstAlpha = blendDstAlpha || blendDst;
  15997. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  15998. gl.blendEquationSeparate( utils.convert( blendEquation ), utils.convert( blendEquationAlpha ) );
  15999. currentBlendEquation = blendEquation;
  16000. currentBlendEquationAlpha = blendEquationAlpha;
  16001. }
  16002. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  16003. gl.blendFuncSeparate( utils.convert( blendSrc ), utils.convert( blendDst ), utils.convert( blendSrcAlpha ), utils.convert( blendDstAlpha ) );
  16004. currentBlendSrc = blendSrc;
  16005. currentBlendDst = blendDst;
  16006. currentBlendSrcAlpha = blendSrcAlpha;
  16007. currentBlendDstAlpha = blendDstAlpha;
  16008. }
  16009. }
  16010. currentBlending = blending;
  16011. currentPremultipledAlpha = premultipliedAlpha;
  16012. }
  16013. function setMaterial( material, frontFaceCW ) {
  16014. material.side === DoubleSide
  16015. ? disable( gl.CULL_FACE )
  16016. : enable( gl.CULL_FACE );
  16017. var flipSided = ( material.side === BackSide );
  16018. if ( frontFaceCW ) flipSided = ! flipSided;
  16019. setFlipSided( flipSided );
  16020. material.transparent === true
  16021. ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  16022. : setBlending( NoBlending );
  16023. depthBuffer.setFunc( material.depthFunc );
  16024. depthBuffer.setTest( material.depthTest );
  16025. depthBuffer.setMask( material.depthWrite );
  16026. colorBuffer.setMask( material.colorWrite );
  16027. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  16028. }
  16029. //
  16030. function setFlipSided( flipSided ) {
  16031. if ( currentFlipSided !== flipSided ) {
  16032. if ( flipSided ) {
  16033. gl.frontFace( gl.CW );
  16034. } else {
  16035. gl.frontFace( gl.CCW );
  16036. }
  16037. currentFlipSided = flipSided;
  16038. }
  16039. }
  16040. function setCullFace( cullFace ) {
  16041. if ( cullFace !== CullFaceNone ) {
  16042. enable( gl.CULL_FACE );
  16043. if ( cullFace !== currentCullFace ) {
  16044. if ( cullFace === CullFaceBack ) {
  16045. gl.cullFace( gl.BACK );
  16046. } else if ( cullFace === CullFaceFront ) {
  16047. gl.cullFace( gl.FRONT );
  16048. } else {
  16049. gl.cullFace( gl.FRONT_AND_BACK );
  16050. }
  16051. }
  16052. } else {
  16053. disable( gl.CULL_FACE );
  16054. }
  16055. currentCullFace = cullFace;
  16056. }
  16057. function setLineWidth( width ) {
  16058. if ( width !== currentLineWidth ) {
  16059. if ( lineWidthAvailable ) gl.lineWidth( width );
  16060. currentLineWidth = width;
  16061. }
  16062. }
  16063. function setPolygonOffset( polygonOffset, factor, units ) {
  16064. if ( polygonOffset ) {
  16065. enable( gl.POLYGON_OFFSET_FILL );
  16066. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  16067. gl.polygonOffset( factor, units );
  16068. currentPolygonOffsetFactor = factor;
  16069. currentPolygonOffsetUnits = units;
  16070. }
  16071. } else {
  16072. disable( gl.POLYGON_OFFSET_FILL );
  16073. }
  16074. }
  16075. function setScissorTest( scissorTest ) {
  16076. if ( scissorTest ) {
  16077. enable( gl.SCISSOR_TEST );
  16078. } else {
  16079. disable( gl.SCISSOR_TEST );
  16080. }
  16081. }
  16082. // texture
  16083. function activeTexture( webglSlot ) {
  16084. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  16085. if ( currentTextureSlot !== webglSlot ) {
  16086. gl.activeTexture( webglSlot );
  16087. currentTextureSlot = webglSlot;
  16088. }
  16089. }
  16090. function bindTexture( webglType, webglTexture ) {
  16091. if ( currentTextureSlot === null ) {
  16092. activeTexture();
  16093. }
  16094. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  16095. if ( boundTexture === undefined ) {
  16096. boundTexture = { type: undefined, texture: undefined };
  16097. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  16098. }
  16099. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  16100. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  16101. boundTexture.type = webglType;
  16102. boundTexture.texture = webglTexture;
  16103. }
  16104. }
  16105. function compressedTexImage2D() {
  16106. try {
  16107. gl.compressedTexImage2D.apply( gl, arguments );
  16108. } catch ( error ) {
  16109. console.error( 'THREE.WebGLState:', error );
  16110. }
  16111. }
  16112. function texImage2D() {
  16113. try {
  16114. gl.texImage2D.apply( gl, arguments );
  16115. } catch ( error ) {
  16116. console.error( 'THREE.WebGLState:', error );
  16117. }
  16118. }
  16119. //
  16120. function scissor( scissor ) {
  16121. if ( currentScissor.equals( scissor ) === false ) {
  16122. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  16123. currentScissor.copy( scissor );
  16124. }
  16125. }
  16126. function viewport( viewport ) {
  16127. if ( currentViewport.equals( viewport ) === false ) {
  16128. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  16129. currentViewport.copy( viewport );
  16130. }
  16131. }
  16132. //
  16133. function reset() {
  16134. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  16135. if ( enabledAttributes[ i ] === 1 ) {
  16136. gl.disableVertexAttribArray( i );
  16137. enabledAttributes[ i ] = 0;
  16138. }
  16139. }
  16140. capabilities = {};
  16141. compressedTextureFormats = null;
  16142. currentTextureSlot = null;
  16143. currentBoundTextures = {};
  16144. currentProgram = null;
  16145. currentBlending = null;
  16146. currentFlipSided = null;
  16147. currentCullFace = null;
  16148. colorBuffer.reset();
  16149. depthBuffer.reset();
  16150. stencilBuffer.reset();
  16151. }
  16152. return {
  16153. buffers: {
  16154. color: colorBuffer,
  16155. depth: depthBuffer,
  16156. stencil: stencilBuffer
  16157. },
  16158. initAttributes: initAttributes,
  16159. enableAttribute: enableAttribute,
  16160. enableAttributeAndDivisor: enableAttributeAndDivisor,
  16161. disableUnusedAttributes: disableUnusedAttributes,
  16162. enable: enable,
  16163. disable: disable,
  16164. getCompressedTextureFormats: getCompressedTextureFormats,
  16165. useProgram: useProgram,
  16166. setBlending: setBlending,
  16167. setMaterial: setMaterial,
  16168. setFlipSided: setFlipSided,
  16169. setCullFace: setCullFace,
  16170. setLineWidth: setLineWidth,
  16171. setPolygonOffset: setPolygonOffset,
  16172. setScissorTest: setScissorTest,
  16173. activeTexture: activeTexture,
  16174. bindTexture: bindTexture,
  16175. compressedTexImage2D: compressedTexImage2D,
  16176. texImage2D: texImage2D,
  16177. scissor: scissor,
  16178. viewport: viewport,
  16179. reset: reset
  16180. };
  16181. }
  16182. /**
  16183. * @author mrdoob / http://mrdoob.com/
  16184. */
  16185. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  16186. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); /* global WebGL2RenderingContext */
  16187. var _videoTextures = {};
  16188. var _canvas;
  16189. //
  16190. function clampToMaxSize( image, maxSize ) {
  16191. if ( image.width > maxSize || image.height > maxSize ) {
  16192. if ( 'data' in image ) {
  16193. console.warn( 'THREE.WebGLRenderer: image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  16194. return;
  16195. }
  16196. // Warning: Scaling through the canvas will only work with images that use
  16197. // premultiplied alpha.
  16198. var scale = maxSize / Math.max( image.width, image.height );
  16199. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  16200. canvas.width = Math.floor( image.width * scale );
  16201. canvas.height = Math.floor( image.height * scale );
  16202. var context = canvas.getContext( '2d' );
  16203. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  16204. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16205. return canvas;
  16206. }
  16207. return image;
  16208. }
  16209. function isPowerOfTwo( image ) {
  16210. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  16211. }
  16212. function makePowerOfTwo( image ) {
  16213. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof ImageBitmap ) {
  16214. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  16215. _canvas.width = _Math.floorPowerOfTwo( image.width );
  16216. _canvas.height = _Math.floorPowerOfTwo( image.height );
  16217. var context = _canvas.getContext( '2d' );
  16218. context.drawImage( image, 0, 0, _canvas.width, _canvas.height );
  16219. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + _canvas.width + 'x' + _canvas.height, image );
  16220. return _canvas;
  16221. }
  16222. return image;
  16223. }
  16224. function textureNeedsPowerOfTwo( texture ) {
  16225. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  16226. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  16227. }
  16228. function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) {
  16229. return texture.generateMipmaps && isPowerOfTwo &&
  16230. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  16231. }
  16232. function generateMipmap( target, texture, width, height ) {
  16233. _gl.generateMipmap( target );
  16234. var textureProperties = properties.get( texture );
  16235. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  16236. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  16237. }
  16238. // Fallback filters for non-power-of-2 textures
  16239. function filterFallback( f ) {
  16240. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  16241. return _gl.NEAREST;
  16242. }
  16243. return _gl.LINEAR;
  16244. }
  16245. //
  16246. function onTextureDispose( event ) {
  16247. var texture = event.target;
  16248. texture.removeEventListener( 'dispose', onTextureDispose );
  16249. deallocateTexture( texture );
  16250. if ( texture.isVideoTexture ) {
  16251. delete _videoTextures[ texture.id ];
  16252. }
  16253. info.memory.textures --;
  16254. }
  16255. function onRenderTargetDispose( event ) {
  16256. var renderTarget = event.target;
  16257. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  16258. deallocateRenderTarget( renderTarget );
  16259. info.memory.textures --;
  16260. }
  16261. //
  16262. function deallocateTexture( texture ) {
  16263. var textureProperties = properties.get( texture );
  16264. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  16265. // cube texture
  16266. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  16267. } else {
  16268. // 2D texture
  16269. if ( textureProperties.__webglInit === undefined ) return;
  16270. _gl.deleteTexture( textureProperties.__webglTexture );
  16271. }
  16272. // remove all webgl properties
  16273. properties.remove( texture );
  16274. }
  16275. function deallocateRenderTarget( renderTarget ) {
  16276. var renderTargetProperties = properties.get( renderTarget );
  16277. var textureProperties = properties.get( renderTarget.texture );
  16278. if ( ! renderTarget ) return;
  16279. if ( textureProperties.__webglTexture !== undefined ) {
  16280. _gl.deleteTexture( textureProperties.__webglTexture );
  16281. }
  16282. if ( renderTarget.depthTexture ) {
  16283. renderTarget.depthTexture.dispose();
  16284. }
  16285. if ( renderTarget.isWebGLRenderTargetCube ) {
  16286. for ( var i = 0; i < 6; i ++ ) {
  16287. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  16288. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  16289. }
  16290. } else {
  16291. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  16292. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  16293. }
  16294. properties.remove( renderTarget.texture );
  16295. properties.remove( renderTarget );
  16296. }
  16297. //
  16298. function setTexture2D( texture, slot ) {
  16299. var textureProperties = properties.get( texture );
  16300. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  16301. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16302. var image = texture.image;
  16303. if ( image === undefined ) {
  16304. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  16305. } else if ( image.complete === false ) {
  16306. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  16307. } else {
  16308. uploadTexture( textureProperties, texture, slot );
  16309. return;
  16310. }
  16311. }
  16312. state.activeTexture( _gl.TEXTURE0 + slot );
  16313. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16314. }
  16315. function setTextureCube( texture, slot ) {
  16316. var textureProperties = properties.get( texture );
  16317. if ( texture.image.length === 6 ) {
  16318. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16319. if ( ! textureProperties.__image__webglTextureCube ) {
  16320. texture.addEventListener( 'dispose', onTextureDispose );
  16321. textureProperties.__image__webglTextureCube = _gl.createTexture();
  16322. info.memory.textures ++;
  16323. }
  16324. state.activeTexture( _gl.TEXTURE0 + slot );
  16325. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16326. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16327. var isCompressed = ( texture && texture.isCompressedTexture );
  16328. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  16329. var cubeImage = [];
  16330. for ( var i = 0; i < 6; i ++ ) {
  16331. if ( ! isCompressed && ! isDataTexture ) {
  16332. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  16333. } else {
  16334. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  16335. }
  16336. }
  16337. var image = cubeImage[ 0 ],
  16338. isPowerOfTwoImage = isPowerOfTwo( image ),
  16339. glFormat = utils.convert( texture.format ),
  16340. glType = utils.convert( texture.type );
  16341. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  16342. for ( var i = 0; i < 6; i ++ ) {
  16343. if ( ! isCompressed ) {
  16344. if ( isDataTexture ) {
  16345. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  16346. } else {
  16347. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  16348. }
  16349. } else {
  16350. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  16351. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  16352. mipmap = mipmaps[ j ];
  16353. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  16354. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16355. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16356. } else {
  16357. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  16358. }
  16359. } else {
  16360. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16361. }
  16362. }
  16363. }
  16364. }
  16365. if ( ! isCompressed ) {
  16366. textureProperties.__maxMipLevel = 0;
  16367. } else {
  16368. textureProperties.__maxMipLevel = mipmaps.length - 1;
  16369. }
  16370. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  16371. // We assume images for cube map have the same size.
  16372. generateMipmap( _gl.TEXTURE_CUBE_MAP, texture, image.width, image.height );
  16373. }
  16374. textureProperties.__version = texture.version;
  16375. if ( texture.onUpdate ) texture.onUpdate( texture );
  16376. } else {
  16377. state.activeTexture( _gl.TEXTURE0 + slot );
  16378. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16379. }
  16380. }
  16381. }
  16382. function setTextureCubeDynamic( texture, slot ) {
  16383. state.activeTexture( _gl.TEXTURE0 + slot );
  16384. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  16385. }
  16386. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  16387. var extension;
  16388. if ( isPowerOfTwoImage ) {
  16389. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, utils.convert( texture.wrapS ) );
  16390. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, utils.convert( texture.wrapT ) );
  16391. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, utils.convert( texture.magFilter ) );
  16392. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, utils.convert( texture.minFilter ) );
  16393. } else {
  16394. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  16395. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  16396. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  16397. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  16398. }
  16399. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  16400. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  16401. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  16402. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  16403. }
  16404. }
  16405. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  16406. if ( extension ) {
  16407. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  16408. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  16409. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  16410. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  16411. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  16412. }
  16413. }
  16414. }
  16415. function uploadTexture( textureProperties, texture, slot ) {
  16416. if ( textureProperties.__webglInit === undefined ) {
  16417. textureProperties.__webglInit = true;
  16418. texture.addEventListener( 'dispose', onTextureDispose );
  16419. textureProperties.__webglTexture = _gl.createTexture();
  16420. info.memory.textures ++;
  16421. }
  16422. state.activeTexture( _gl.TEXTURE0 + slot );
  16423. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16424. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16425. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  16426. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  16427. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  16428. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  16429. image = makePowerOfTwo( image );
  16430. }
  16431. var isPowerOfTwoImage = isPowerOfTwo( image ),
  16432. glFormat = utils.convert( texture.format ),
  16433. glType = utils.convert( texture.type );
  16434. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  16435. var mipmap, mipmaps = texture.mipmaps;
  16436. if ( texture.isDepthTexture ) {
  16437. // populate depth texture with dummy data
  16438. var internalFormat = _gl.DEPTH_COMPONENT;
  16439. if ( texture.type === FloatType ) {
  16440. if ( ! _isWebGL2 ) throw new Error( 'Float Depth Texture only supported in WebGL2.0' );
  16441. internalFormat = _gl.DEPTH_COMPONENT32F;
  16442. } else if ( _isWebGL2 ) {
  16443. // WebGL 2.0 requires signed internalformat for glTexImage2D
  16444. internalFormat = _gl.DEPTH_COMPONENT16;
  16445. }
  16446. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  16447. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  16448. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  16449. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  16450. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  16451. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  16452. texture.type = UnsignedShortType;
  16453. glType = utils.convert( texture.type );
  16454. }
  16455. }
  16456. // Depth stencil textures need the DEPTH_STENCIL internal format
  16457. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  16458. if ( texture.format === DepthStencilFormat ) {
  16459. internalFormat = _gl.DEPTH_STENCIL;
  16460. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  16461. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  16462. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  16463. if ( texture.type !== UnsignedInt248Type ) {
  16464. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  16465. texture.type = UnsignedInt248Type;
  16466. glType = utils.convert( texture.type );
  16467. }
  16468. }
  16469. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  16470. } else if ( texture.isDataTexture ) {
  16471. // use manually created mipmaps if available
  16472. // if there are no manual mipmaps
  16473. // set 0 level mipmap and then use GL to generate other mipmap levels
  16474. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  16475. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16476. mipmap = mipmaps[ i ];
  16477. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16478. }
  16479. texture.generateMipmaps = false;
  16480. textureProperties.__maxMipLevel = mipmaps.length - 1;
  16481. } else {
  16482. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  16483. textureProperties.__maxMipLevel = 0;
  16484. }
  16485. } else if ( texture.isCompressedTexture ) {
  16486. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16487. mipmap = mipmaps[ i ];
  16488. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  16489. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16490. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16491. } else {
  16492. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  16493. }
  16494. } else {
  16495. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16496. }
  16497. }
  16498. textureProperties.__maxMipLevel = mipmaps.length - 1;
  16499. } else {
  16500. // regular Texture (image, video, canvas)
  16501. // use manually created mipmaps if available
  16502. // if there are no manual mipmaps
  16503. // set 0 level mipmap and then use GL to generate other mipmap levels
  16504. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  16505. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16506. mipmap = mipmaps[ i ];
  16507. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  16508. }
  16509. texture.generateMipmaps = false;
  16510. textureProperties.__maxMipLevel = mipmaps.length - 1;
  16511. } else {
  16512. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  16513. textureProperties.__maxMipLevel = 0;
  16514. }
  16515. }
  16516. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  16517. generateMipmap( _gl.TEXTURE_2D, texture, image.width, image.height );
  16518. }
  16519. textureProperties.__version = texture.version;
  16520. if ( texture.onUpdate ) texture.onUpdate( texture );
  16521. }
  16522. // Render targets
  16523. // Setup storage for target texture and bind it to correct framebuffer
  16524. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  16525. var glFormat = utils.convert( renderTarget.texture.format );
  16526. var glType = utils.convert( renderTarget.texture.type );
  16527. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16528. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16529. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  16530. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16531. }
  16532. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  16533. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  16534. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  16535. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16536. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  16537. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16538. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16539. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  16540. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16541. } else {
  16542. // FIXME: We don't support !depth !stencil
  16543. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  16544. }
  16545. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  16546. }
  16547. // Setup resources for a Depth Texture for a FBO (needs an extension)
  16548. function setupDepthTexture( framebuffer, renderTarget ) {
  16549. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  16550. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  16551. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16552. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  16553. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  16554. }
  16555. // upload an empty depth texture with framebuffer size
  16556. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  16557. renderTarget.depthTexture.image.width !== renderTarget.width ||
  16558. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  16559. renderTarget.depthTexture.image.width = renderTarget.width;
  16560. renderTarget.depthTexture.image.height = renderTarget.height;
  16561. renderTarget.depthTexture.needsUpdate = true;
  16562. }
  16563. setTexture2D( renderTarget.depthTexture, 0 );
  16564. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  16565. if ( renderTarget.depthTexture.format === DepthFormat ) {
  16566. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  16567. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  16568. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  16569. } else {
  16570. throw new Error( 'Unknown depthTexture format' );
  16571. }
  16572. }
  16573. // Setup GL resources for a non-texture depth buffer
  16574. function setupDepthRenderbuffer( renderTarget ) {
  16575. var renderTargetProperties = properties.get( renderTarget );
  16576. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  16577. if ( renderTarget.depthTexture ) {
  16578. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  16579. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  16580. } else {
  16581. if ( isCube ) {
  16582. renderTargetProperties.__webglDepthbuffer = [];
  16583. for ( var i = 0; i < 6; i ++ ) {
  16584. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  16585. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  16586. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  16587. }
  16588. } else {
  16589. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  16590. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  16591. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  16592. }
  16593. }
  16594. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16595. }
  16596. // Set up GL resources for the render target
  16597. function setupRenderTarget( renderTarget ) {
  16598. var renderTargetProperties = properties.get( renderTarget );
  16599. var textureProperties = properties.get( renderTarget.texture );
  16600. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  16601. textureProperties.__webglTexture = _gl.createTexture();
  16602. info.memory.textures ++;
  16603. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  16604. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  16605. // Setup framebuffer
  16606. if ( isCube ) {
  16607. renderTargetProperties.__webglFramebuffer = [];
  16608. for ( var i = 0; i < 6; i ++ ) {
  16609. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  16610. }
  16611. } else {
  16612. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  16613. }
  16614. // Setup color buffer
  16615. if ( isCube ) {
  16616. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  16617. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  16618. for ( var i = 0; i < 6; i ++ ) {
  16619. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  16620. }
  16621. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) {
  16622. generateMipmap( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, renderTarget.width, renderTarget.height );
  16623. }
  16624. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  16625. } else {
  16626. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16627. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  16628. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  16629. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) {
  16630. generateMipmap( _gl.TEXTURE_2D, renderTarget.texture, renderTarget.width, renderTarget.height );
  16631. }
  16632. state.bindTexture( _gl.TEXTURE_2D, null );
  16633. }
  16634. // Setup depth and stencil buffers
  16635. if ( renderTarget.depthBuffer ) {
  16636. setupDepthRenderbuffer( renderTarget );
  16637. }
  16638. }
  16639. function updateRenderTargetMipmap( renderTarget ) {
  16640. var texture = renderTarget.texture;
  16641. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  16642. if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) {
  16643. var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  16644. var webglTexture = properties.get( texture ).__webglTexture;
  16645. state.bindTexture( target, webglTexture );
  16646. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  16647. state.bindTexture( target, null );
  16648. }
  16649. }
  16650. function updateVideoTexture( texture ) {
  16651. var id = texture.id;
  16652. var frame = info.render.frame;
  16653. // Check the last frame we updated the VideoTexture
  16654. if ( _videoTextures[ id ] !== frame ) {
  16655. _videoTextures[ id ] = frame;
  16656. texture.update();
  16657. }
  16658. }
  16659. this.setTexture2D = setTexture2D;
  16660. this.setTextureCube = setTextureCube;
  16661. this.setTextureCubeDynamic = setTextureCubeDynamic;
  16662. this.setupRenderTarget = setupRenderTarget;
  16663. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  16664. }
  16665. /**
  16666. * @author thespite / http://www.twitter.com/thespite
  16667. */
  16668. function WebGLUtils( gl, extensions ) {
  16669. function convert( p ) {
  16670. var extension;
  16671. if ( p === RepeatWrapping ) return gl.REPEAT;
  16672. if ( p === ClampToEdgeWrapping ) return gl.CLAMP_TO_EDGE;
  16673. if ( p === MirroredRepeatWrapping ) return gl.MIRRORED_REPEAT;
  16674. if ( p === NearestFilter ) return gl.NEAREST;
  16675. if ( p === NearestMipMapNearestFilter ) return gl.NEAREST_MIPMAP_NEAREST;
  16676. if ( p === NearestMipMapLinearFilter ) return gl.NEAREST_MIPMAP_LINEAR;
  16677. if ( p === LinearFilter ) return gl.LINEAR;
  16678. if ( p === LinearMipMapNearestFilter ) return gl.LINEAR_MIPMAP_NEAREST;
  16679. if ( p === LinearMipMapLinearFilter ) return gl.LINEAR_MIPMAP_LINEAR;
  16680. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  16681. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  16682. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  16683. if ( p === UnsignedShort565Type ) return gl.UNSIGNED_SHORT_5_6_5;
  16684. if ( p === ByteType ) return gl.BYTE;
  16685. if ( p === ShortType ) return gl.SHORT;
  16686. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  16687. if ( p === IntType ) return gl.INT;
  16688. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  16689. if ( p === FloatType ) return gl.FLOAT;
  16690. if ( p === HalfFloatType ) {
  16691. extension = extensions.get( 'OES_texture_half_float' );
  16692. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  16693. }
  16694. if ( p === AlphaFormat ) return gl.ALPHA;
  16695. if ( p === RGBFormat ) return gl.RGB;
  16696. if ( p === RGBAFormat ) return gl.RGBA;
  16697. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  16698. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  16699. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  16700. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  16701. if ( p === AddEquation ) return gl.FUNC_ADD;
  16702. if ( p === SubtractEquation ) return gl.FUNC_SUBTRACT;
  16703. if ( p === ReverseSubtractEquation ) return gl.FUNC_REVERSE_SUBTRACT;
  16704. if ( p === ZeroFactor ) return gl.ZERO;
  16705. if ( p === OneFactor ) return gl.ONE;
  16706. if ( p === SrcColorFactor ) return gl.SRC_COLOR;
  16707. if ( p === OneMinusSrcColorFactor ) return gl.ONE_MINUS_SRC_COLOR;
  16708. if ( p === SrcAlphaFactor ) return gl.SRC_ALPHA;
  16709. if ( p === OneMinusSrcAlphaFactor ) return gl.ONE_MINUS_SRC_ALPHA;
  16710. if ( p === DstAlphaFactor ) return gl.DST_ALPHA;
  16711. if ( p === OneMinusDstAlphaFactor ) return gl.ONE_MINUS_DST_ALPHA;
  16712. if ( p === DstColorFactor ) return gl.DST_COLOR;
  16713. if ( p === OneMinusDstColorFactor ) return gl.ONE_MINUS_DST_COLOR;
  16714. if ( p === SrcAlphaSaturateFactor ) return gl.SRC_ALPHA_SATURATE;
  16715. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  16716. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  16717. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  16718. if ( extension !== null ) {
  16719. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16720. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16721. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16722. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16723. }
  16724. }
  16725. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  16726. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  16727. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  16728. if ( extension !== null ) {
  16729. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  16730. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  16731. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  16732. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  16733. }
  16734. }
  16735. if ( p === RGB_ETC1_Format ) {
  16736. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  16737. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  16738. }
  16739. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  16740. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  16741. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  16742. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  16743. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  16744. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  16745. if ( extension !== null ) {
  16746. return p;
  16747. }
  16748. }
  16749. if ( p === MinEquation || p === MaxEquation ) {
  16750. extension = extensions.get( 'EXT_blend_minmax' );
  16751. if ( extension !== null ) {
  16752. if ( p === MinEquation ) return extension.MIN_EXT;
  16753. if ( p === MaxEquation ) return extension.MAX_EXT;
  16754. }
  16755. }
  16756. if ( p === UnsignedInt248Type ) {
  16757. extension = extensions.get( 'WEBGL_depth_texture' );
  16758. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  16759. }
  16760. return 0;
  16761. }
  16762. return { convert: convert };
  16763. }
  16764. /**
  16765. * @author mrdoob / http://mrdoob.com/
  16766. * @author greggman / http://games.greggman.com/
  16767. * @author zz85 / http://www.lab4games.net/zz85/blog
  16768. * @author tschw
  16769. */
  16770. function PerspectiveCamera( fov, aspect, near, far ) {
  16771. Camera.call( this );
  16772. this.type = 'PerspectiveCamera';
  16773. this.fov = fov !== undefined ? fov : 50;
  16774. this.zoom = 1;
  16775. this.near = near !== undefined ? near : 0.1;
  16776. this.far = far !== undefined ? far : 2000;
  16777. this.focus = 10;
  16778. this.aspect = aspect !== undefined ? aspect : 1;
  16779. this.view = null;
  16780. this.filmGauge = 35; // width of the film (default in millimeters)
  16781. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  16782. this.updateProjectionMatrix();
  16783. }
  16784. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  16785. constructor: PerspectiveCamera,
  16786. isPerspectiveCamera: true,
  16787. copy: function ( source, recursive ) {
  16788. Camera.prototype.copy.call( this, source, recursive );
  16789. this.fov = source.fov;
  16790. this.zoom = source.zoom;
  16791. this.near = source.near;
  16792. this.far = source.far;
  16793. this.focus = source.focus;
  16794. this.aspect = source.aspect;
  16795. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16796. this.filmGauge = source.filmGauge;
  16797. this.filmOffset = source.filmOffset;
  16798. return this;
  16799. },
  16800. /**
  16801. * Sets the FOV by focal length in respect to the current .filmGauge.
  16802. *
  16803. * The default film gauge is 35, so that the focal length can be specified for
  16804. * a 35mm (full frame) camera.
  16805. *
  16806. * Values for focal length and film gauge must have the same unit.
  16807. */
  16808. setFocalLength: function ( focalLength ) {
  16809. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  16810. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16811. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  16812. this.updateProjectionMatrix();
  16813. },
  16814. /**
  16815. * Calculates the focal length from the current .fov and .filmGauge.
  16816. */
  16817. getFocalLength: function () {
  16818. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  16819. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16820. },
  16821. getEffectiveFOV: function () {
  16822. return _Math.RAD2DEG * 2 * Math.atan(
  16823. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16824. },
  16825. getFilmWidth: function () {
  16826. // film not completely covered in portrait format (aspect < 1)
  16827. return this.filmGauge * Math.min( this.aspect, 1 );
  16828. },
  16829. getFilmHeight: function () {
  16830. // film not completely covered in landscape format (aspect > 1)
  16831. return this.filmGauge / Math.max( this.aspect, 1 );
  16832. },
  16833. /**
  16834. * Sets an offset in a larger frustum. This is useful for multi-window or
  16835. * multi-monitor/multi-machine setups.
  16836. *
  16837. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16838. * the monitors are in grid like this
  16839. *
  16840. * +---+---+---+
  16841. * | A | B | C |
  16842. * +---+---+---+
  16843. * | D | E | F |
  16844. * +---+---+---+
  16845. *
  16846. * then for each monitor you would call it like this
  16847. *
  16848. * var w = 1920;
  16849. * var h = 1080;
  16850. * var fullWidth = w * 3;
  16851. * var fullHeight = h * 2;
  16852. *
  16853. * --A--
  16854. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16855. * --B--
  16856. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16857. * --C--
  16858. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16859. * --D--
  16860. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16861. * --E--
  16862. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16863. * --F--
  16864. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16865. *
  16866. * Note there is no reason monitors have to be the same size or in a grid.
  16867. */
  16868. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  16869. this.aspect = fullWidth / fullHeight;
  16870. if ( this.view === null ) {
  16871. this.view = {
  16872. enabled: true,
  16873. fullWidth: 1,
  16874. fullHeight: 1,
  16875. offsetX: 0,
  16876. offsetY: 0,
  16877. width: 1,
  16878. height: 1
  16879. };
  16880. }
  16881. this.view.enabled = true;
  16882. this.view.fullWidth = fullWidth;
  16883. this.view.fullHeight = fullHeight;
  16884. this.view.offsetX = x;
  16885. this.view.offsetY = y;
  16886. this.view.width = width;
  16887. this.view.height = height;
  16888. this.updateProjectionMatrix();
  16889. },
  16890. clearViewOffset: function () {
  16891. if ( this.view !== null ) {
  16892. this.view.enabled = false;
  16893. }
  16894. this.updateProjectionMatrix();
  16895. },
  16896. updateProjectionMatrix: function () {
  16897. var near = this.near,
  16898. top = near * Math.tan(
  16899. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  16900. height = 2 * top,
  16901. width = this.aspect * height,
  16902. left = - 0.5 * width,
  16903. view = this.view;
  16904. if ( this.view !== null && this.view.enabled ) {
  16905. var fullWidth = view.fullWidth,
  16906. fullHeight = view.fullHeight;
  16907. left += view.offsetX * width / fullWidth;
  16908. top -= view.offsetY * height / fullHeight;
  16909. width *= view.width / fullWidth;
  16910. height *= view.height / fullHeight;
  16911. }
  16912. var skew = this.filmOffset;
  16913. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16914. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  16915. },
  16916. toJSON: function ( meta ) {
  16917. var data = Object3D.prototype.toJSON.call( this, meta );
  16918. data.object.fov = this.fov;
  16919. data.object.zoom = this.zoom;
  16920. data.object.near = this.near;
  16921. data.object.far = this.far;
  16922. data.object.focus = this.focus;
  16923. data.object.aspect = this.aspect;
  16924. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16925. data.object.filmGauge = this.filmGauge;
  16926. data.object.filmOffset = this.filmOffset;
  16927. return data;
  16928. }
  16929. } );
  16930. /**
  16931. * @author mrdoob / http://mrdoob.com/
  16932. */
  16933. function ArrayCamera( array ) {
  16934. PerspectiveCamera.call( this );
  16935. this.cameras = array || [];
  16936. }
  16937. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  16938. constructor: ArrayCamera,
  16939. isArrayCamera: true
  16940. } );
  16941. /**
  16942. * @author mrdoob / http://mrdoob.com/
  16943. */
  16944. function WebVRManager( renderer ) {
  16945. var scope = this;
  16946. var device = null;
  16947. var frameData = null;
  16948. var poseTarget = null;
  16949. var standingMatrix = new Matrix4();
  16950. var standingMatrixInverse = new Matrix4();
  16951. if ( typeof window !== 'undefined' && 'VRFrameData' in window ) {
  16952. frameData = new window.VRFrameData();
  16953. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  16954. }
  16955. var matrixWorldInverse = new Matrix4();
  16956. var tempQuaternion = new Quaternion();
  16957. var tempPosition = new Vector3();
  16958. var cameraL = new PerspectiveCamera();
  16959. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  16960. cameraL.layers.enable( 1 );
  16961. var cameraR = new PerspectiveCamera();
  16962. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  16963. cameraR.layers.enable( 2 );
  16964. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  16965. cameraVR.layers.enable( 1 );
  16966. cameraVR.layers.enable( 2 );
  16967. //
  16968. function isPresenting() {
  16969. return device !== null && device.isPresenting === true;
  16970. }
  16971. var currentSize, currentPixelRatio;
  16972. function onVRDisplayPresentChange() {
  16973. if ( isPresenting() ) {
  16974. var eyeParameters = device.getEyeParameters( 'left' );
  16975. var renderWidth = eyeParameters.renderWidth;
  16976. var renderHeight = eyeParameters.renderHeight;
  16977. currentPixelRatio = renderer.getPixelRatio();
  16978. currentSize = renderer.getSize();
  16979. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  16980. } else if ( scope.enabled ) {
  16981. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  16982. }
  16983. }
  16984. //
  16985. this.enabled = false;
  16986. this.userHeight = 1.6;
  16987. this.getDevice = function () {
  16988. return device;
  16989. };
  16990. this.setDevice = function ( value ) {
  16991. if ( value !== undefined ) device = value;
  16992. };
  16993. this.setPoseTarget = function ( object ) {
  16994. if ( object !== undefined ) poseTarget = object;
  16995. };
  16996. this.getCamera = function ( camera ) {
  16997. if ( device === null ) return camera;
  16998. device.depthNear = camera.near;
  16999. device.depthFar = camera.far;
  17000. device.getFrameData( frameData );
  17001. //
  17002. var stageParameters = device.stageParameters;
  17003. if ( stageParameters ) {
  17004. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  17005. } else {
  17006. standingMatrix.makeTranslation( 0, scope.userHeight, 0 );
  17007. }
  17008. var pose = frameData.pose;
  17009. var poseObject = poseTarget !== null ? poseTarget : camera;
  17010. // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  17011. poseObject.matrix.copy( standingMatrix );
  17012. poseObject.matrix.decompose( poseObject.position, poseObject.quaternion, poseObject.scale );
  17013. if ( pose.orientation !== null ) {
  17014. tempQuaternion.fromArray( pose.orientation );
  17015. poseObject.quaternion.multiply( tempQuaternion );
  17016. }
  17017. if ( pose.position !== null ) {
  17018. tempQuaternion.setFromRotationMatrix( standingMatrix );
  17019. tempPosition.fromArray( pose.position );
  17020. tempPosition.applyQuaternion( tempQuaternion );
  17021. poseObject.position.add( tempPosition );
  17022. }
  17023. poseObject.updateMatrixWorld();
  17024. if ( device.isPresenting === false ) return camera;
  17025. //
  17026. cameraL.near = camera.near;
  17027. cameraR.near = camera.near;
  17028. cameraL.far = camera.far;
  17029. cameraR.far = camera.far;
  17030. cameraVR.matrixWorld.copy( camera.matrixWorld );
  17031. cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse );
  17032. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  17033. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  17034. // TODO (mrdoob) Double check this code
  17035. standingMatrixInverse.getInverse( standingMatrix );
  17036. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  17037. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  17038. var parent = poseObject.parent;
  17039. if ( parent !== null ) {
  17040. matrixWorldInverse.getInverse( parent.matrixWorld );
  17041. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  17042. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  17043. }
  17044. // envMap and Mirror needs camera.matrixWorld
  17045. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  17046. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  17047. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  17048. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  17049. // HACK (mrdoob)
  17050. // https://github.com/w3c/webvr/issues/203
  17051. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  17052. //
  17053. var layers = device.getLayers();
  17054. if ( layers.length ) {
  17055. var layer = layers[ 0 ];
  17056. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  17057. cameraL.bounds.fromArray( layer.leftBounds );
  17058. }
  17059. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  17060. cameraR.bounds.fromArray( layer.rightBounds );
  17061. }
  17062. }
  17063. return cameraVR;
  17064. };
  17065. this.getStandingMatrix = function () {
  17066. return standingMatrix;
  17067. };
  17068. this.submitFrame = function () {
  17069. if ( isPresenting() ) device.submitFrame();
  17070. };
  17071. this.dispose = function () {
  17072. if ( typeof window !== 'undefined' ) {
  17073. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  17074. }
  17075. };
  17076. }
  17077. /**
  17078. * @author supereggbert / http://www.paulbrunt.co.uk/
  17079. * @author mrdoob / http://mrdoob.com/
  17080. * @author alteredq / http://alteredqualia.com/
  17081. * @author szimek / https://github.com/szimek/
  17082. * @author tschw
  17083. */
  17084. function WebGLRenderer( parameters ) {
  17085. console.log( 'THREE.WebGLRenderer', REVISION );
  17086. parameters = parameters || {};
  17087. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  17088. _context = parameters.context !== undefined ? parameters.context : null,
  17089. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  17090. _depth = parameters.depth !== undefined ? parameters.depth : true,
  17091. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  17092. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  17093. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  17094. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  17095. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default';
  17096. var currentRenderList = null;
  17097. var currentRenderState = null;
  17098. // public properties
  17099. this.domElement = _canvas;
  17100. this.context = null;
  17101. // clearing
  17102. this.autoClear = true;
  17103. this.autoClearColor = true;
  17104. this.autoClearDepth = true;
  17105. this.autoClearStencil = true;
  17106. // scene graph
  17107. this.sortObjects = true;
  17108. // user-defined clipping
  17109. this.clippingPlanes = [];
  17110. this.localClippingEnabled = false;
  17111. // physically based shading
  17112. this.gammaFactor = 2.0; // for backwards compatibility
  17113. this.gammaInput = false;
  17114. this.gammaOutput = false;
  17115. // physical lights
  17116. this.physicallyCorrectLights = false;
  17117. // tone mapping
  17118. this.toneMapping = LinearToneMapping;
  17119. this.toneMappingExposure = 1.0;
  17120. this.toneMappingWhitePoint = 1.0;
  17121. // morphs
  17122. this.maxMorphTargets = 8;
  17123. this.maxMorphNormals = 4;
  17124. // internal properties
  17125. var _this = this,
  17126. _isContextLost = false,
  17127. // internal state cache
  17128. _currentRenderTarget = null,
  17129. _currentFramebuffer = null,
  17130. _currentMaterialId = - 1,
  17131. _currentGeometryProgram = '',
  17132. _currentCamera = null,
  17133. _currentArrayCamera = null,
  17134. _currentViewport = new Vector4(),
  17135. _currentScissor = new Vector4(),
  17136. _currentScissorTest = null,
  17137. //
  17138. _usedTextureUnits = 0,
  17139. //
  17140. _width = _canvas.width,
  17141. _height = _canvas.height,
  17142. _pixelRatio = 1,
  17143. _viewport = new Vector4( 0, 0, _width, _height ),
  17144. _scissor = new Vector4( 0, 0, _width, _height ),
  17145. _scissorTest = false,
  17146. // frustum
  17147. _frustum = new Frustum(),
  17148. // clipping
  17149. _clipping = new WebGLClipping(),
  17150. _clippingEnabled = false,
  17151. _localClippingEnabled = false,
  17152. // camera matrices cache
  17153. _projScreenMatrix = new Matrix4(),
  17154. _vector3 = new Vector3();
  17155. function getTargetPixelRatio() {
  17156. return _currentRenderTarget === null ? _pixelRatio : 1;
  17157. }
  17158. // initialize
  17159. var _gl;
  17160. try {
  17161. var contextAttributes = {
  17162. alpha: _alpha,
  17163. depth: _depth,
  17164. stencil: _stencil,
  17165. antialias: _antialias,
  17166. premultipliedAlpha: _premultipliedAlpha,
  17167. preserveDrawingBuffer: _preserveDrawingBuffer,
  17168. powerPreference: _powerPreference
  17169. };
  17170. // event listeners must be registered before WebGL context is created, see #12753
  17171. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  17172. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  17173. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  17174. if ( _gl === null ) {
  17175. if ( _canvas.getContext( 'webgl' ) !== null ) {
  17176. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  17177. } else {
  17178. throw new Error( 'Error creating WebGL context.' );
  17179. }
  17180. }
  17181. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  17182. if ( _gl.getShaderPrecisionFormat === undefined ) {
  17183. _gl.getShaderPrecisionFormat = function () {
  17184. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  17185. };
  17186. }
  17187. } catch ( error ) {
  17188. console.error( 'THREE.WebGLRenderer: ' + error.message );
  17189. }
  17190. var extensions, capabilities, state, info;
  17191. var properties, textures, attributes, geometries, objects;
  17192. var programCache, renderLists, renderStates;
  17193. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  17194. var spriteRenderer;
  17195. var utils;
  17196. function initGLContext() {
  17197. extensions = new WebGLExtensions( _gl );
  17198. extensions.get( 'WEBGL_depth_texture' );
  17199. extensions.get( 'OES_texture_float' );
  17200. extensions.get( 'OES_texture_float_linear' );
  17201. extensions.get( 'OES_texture_half_float' );
  17202. extensions.get( 'OES_texture_half_float_linear' );
  17203. extensions.get( 'OES_standard_derivatives' );
  17204. extensions.get( 'OES_element_index_uint' );
  17205. extensions.get( 'ANGLE_instanced_arrays' );
  17206. utils = new WebGLUtils( _gl, extensions );
  17207. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  17208. state = new WebGLState( _gl, extensions, utils );
  17209. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  17210. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  17211. info = new WebGLInfo( _gl );
  17212. properties = new WebGLProperties();
  17213. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  17214. attributes = new WebGLAttributes( _gl );
  17215. geometries = new WebGLGeometries( _gl, attributes, info );
  17216. objects = new WebGLObjects( geometries, info );
  17217. morphtargets = new WebGLMorphtargets( _gl );
  17218. programCache = new WebGLPrograms( _this, extensions, capabilities );
  17219. renderLists = new WebGLRenderLists();
  17220. renderStates = new WebGLRenderStates();
  17221. background = new WebGLBackground( _this, state, geometries, _premultipliedAlpha );
  17222. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  17223. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  17224. spriteRenderer = new WebGLSpriteRenderer( _this, _gl, state, textures, capabilities );
  17225. info.programs = programCache.programs;
  17226. _this.context = _gl;
  17227. _this.capabilities = capabilities;
  17228. _this.extensions = extensions;
  17229. _this.properties = properties;
  17230. _this.renderLists = renderLists;
  17231. _this.state = state;
  17232. _this.info = info;
  17233. }
  17234. initGLContext();
  17235. // vr
  17236. var vr = new WebVRManager( _this );
  17237. this.vr = vr;
  17238. // shadow map
  17239. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  17240. this.shadowMap = shadowMap;
  17241. // API
  17242. this.getContext = function () {
  17243. return _gl;
  17244. };
  17245. this.getContextAttributes = function () {
  17246. return _gl.getContextAttributes();
  17247. };
  17248. this.forceContextLoss = function () {
  17249. var extension = extensions.get( 'WEBGL_lose_context' );
  17250. if ( extension ) extension.loseContext();
  17251. };
  17252. this.forceContextRestore = function () {
  17253. var extension = extensions.get( 'WEBGL_lose_context' );
  17254. if ( extension ) extension.restoreContext();
  17255. };
  17256. this.getPixelRatio = function () {
  17257. return _pixelRatio;
  17258. };
  17259. this.setPixelRatio = function ( value ) {
  17260. if ( value === undefined ) return;
  17261. _pixelRatio = value;
  17262. this.setSize( _width, _height, false );
  17263. };
  17264. this.getSize = function () {
  17265. return {
  17266. width: _width,
  17267. height: _height
  17268. };
  17269. };
  17270. this.setSize = function ( width, height, updateStyle ) {
  17271. var device = vr.getDevice();
  17272. if ( device && device.isPresenting ) {
  17273. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17274. return;
  17275. }
  17276. _width = width;
  17277. _height = height;
  17278. _canvas.width = width * _pixelRatio;
  17279. _canvas.height = height * _pixelRatio;
  17280. if ( updateStyle !== false ) {
  17281. _canvas.style.width = width + 'px';
  17282. _canvas.style.height = height + 'px';
  17283. }
  17284. this.setViewport( 0, 0, width, height );
  17285. };
  17286. this.getDrawingBufferSize = function () {
  17287. return {
  17288. width: _width * _pixelRatio,
  17289. height: _height * _pixelRatio
  17290. };
  17291. };
  17292. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17293. _width = width;
  17294. _height = height;
  17295. _pixelRatio = pixelRatio;
  17296. _canvas.width = width * pixelRatio;
  17297. _canvas.height = height * pixelRatio;
  17298. this.setViewport( 0, 0, width, height );
  17299. };
  17300. this.getCurrentViewport = function () {
  17301. return _currentViewport;
  17302. };
  17303. this.setViewport = function ( x, y, width, height ) {
  17304. _viewport.set( x, _height - y - height, width, height );
  17305. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  17306. };
  17307. this.setScissor = function ( x, y, width, height ) {
  17308. _scissor.set( x, _height - y - height, width, height );
  17309. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  17310. };
  17311. this.setScissorTest = function ( boolean ) {
  17312. state.setScissorTest( _scissorTest = boolean );
  17313. };
  17314. // Clearing
  17315. this.getClearColor = function () {
  17316. return background.getClearColor();
  17317. };
  17318. this.setClearColor = function () {
  17319. background.setClearColor.apply( background, arguments );
  17320. };
  17321. this.getClearAlpha = function () {
  17322. return background.getClearAlpha();
  17323. };
  17324. this.setClearAlpha = function () {
  17325. background.setClearAlpha.apply( background, arguments );
  17326. };
  17327. this.clear = function ( color, depth, stencil ) {
  17328. var bits = 0;
  17329. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  17330. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17331. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  17332. _gl.clear( bits );
  17333. };
  17334. this.clearColor = function () {
  17335. this.clear( true, false, false );
  17336. };
  17337. this.clearDepth = function () {
  17338. this.clear( false, true, false );
  17339. };
  17340. this.clearStencil = function () {
  17341. this.clear( false, false, true );
  17342. };
  17343. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  17344. this.setRenderTarget( renderTarget );
  17345. this.clear( color, depth, stencil );
  17346. };
  17347. //
  17348. this.dispose = function () {
  17349. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17350. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17351. renderLists.dispose();
  17352. renderStates.dispose();
  17353. properties.dispose();
  17354. objects.dispose();
  17355. vr.dispose();
  17356. stopAnimation();
  17357. };
  17358. // Events
  17359. function onContextLost( event ) {
  17360. event.preventDefault();
  17361. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17362. _isContextLost = true;
  17363. }
  17364. function onContextRestore( /* event */ ) {
  17365. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17366. _isContextLost = false;
  17367. initGLContext();
  17368. }
  17369. function onMaterialDispose( event ) {
  17370. var material = event.target;
  17371. material.removeEventListener( 'dispose', onMaterialDispose );
  17372. deallocateMaterial( material );
  17373. }
  17374. // Buffer deallocation
  17375. function deallocateMaterial( material ) {
  17376. releaseMaterialProgramReference( material );
  17377. properties.remove( material );
  17378. }
  17379. function releaseMaterialProgramReference( material ) {
  17380. var programInfo = properties.get( material ).program;
  17381. material.program = undefined;
  17382. if ( programInfo !== undefined ) {
  17383. programCache.releaseProgram( programInfo );
  17384. }
  17385. }
  17386. // Buffer rendering
  17387. function renderObjectImmediate( object, program, material ) {
  17388. object.render( function ( object ) {
  17389. _this.renderBufferImmediate( object, program, material );
  17390. } );
  17391. }
  17392. this.renderBufferImmediate = function ( object, program, material ) {
  17393. state.initAttributes();
  17394. var buffers = properties.get( object );
  17395. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  17396. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  17397. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  17398. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  17399. var programAttributes = program.getAttributes();
  17400. if ( object.hasPositions ) {
  17401. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  17402. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  17403. state.enableAttribute( programAttributes.position );
  17404. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  17405. }
  17406. if ( object.hasNormals ) {
  17407. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  17408. if ( ! material.isMeshPhongMaterial &&
  17409. ! material.isMeshStandardMaterial &&
  17410. ! material.isMeshNormalMaterial &&
  17411. material.flatShading === true ) {
  17412. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  17413. var array = object.normalArray;
  17414. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  17415. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  17416. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  17417. array[ i + 0 ] = nx;
  17418. array[ i + 1 ] = ny;
  17419. array[ i + 2 ] = nz;
  17420. array[ i + 3 ] = nx;
  17421. array[ i + 4 ] = ny;
  17422. array[ i + 5 ] = nz;
  17423. array[ i + 6 ] = nx;
  17424. array[ i + 7 ] = ny;
  17425. array[ i + 8 ] = nz;
  17426. }
  17427. }
  17428. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  17429. state.enableAttribute( programAttributes.normal );
  17430. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  17431. }
  17432. if ( object.hasUvs && material.map ) {
  17433. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  17434. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  17435. state.enableAttribute( programAttributes.uv );
  17436. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  17437. }
  17438. if ( object.hasColors && material.vertexColors !== NoColors ) {
  17439. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  17440. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  17441. state.enableAttribute( programAttributes.color );
  17442. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  17443. }
  17444. state.disableUnusedAttributes();
  17445. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  17446. object.count = 0;
  17447. };
  17448. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  17449. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17450. state.setMaterial( material, frontFaceCW );
  17451. var program = setProgram( camera, fog, material, object );
  17452. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  17453. var updateBuffers = false;
  17454. if ( geometryProgram !== _currentGeometryProgram ) {
  17455. _currentGeometryProgram = geometryProgram;
  17456. updateBuffers = true;
  17457. }
  17458. if ( object.morphTargetInfluences ) {
  17459. morphtargets.update( object, geometry, material, program );
  17460. updateBuffers = true;
  17461. }
  17462. //
  17463. var index = geometry.index;
  17464. var position = geometry.attributes.position;
  17465. var rangeFactor = 1;
  17466. if ( material.wireframe === true ) {
  17467. index = geometries.getWireframeAttribute( geometry );
  17468. rangeFactor = 2;
  17469. }
  17470. var attribute;
  17471. var renderer = bufferRenderer;
  17472. if ( index !== null ) {
  17473. attribute = attributes.get( index );
  17474. renderer = indexedBufferRenderer;
  17475. renderer.setIndex( attribute );
  17476. }
  17477. if ( updateBuffers ) {
  17478. setupVertexAttributes( material, program, geometry );
  17479. if ( index !== null ) {
  17480. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  17481. }
  17482. }
  17483. //
  17484. var dataCount = Infinity;
  17485. if ( index !== null ) {
  17486. dataCount = index.count;
  17487. } else if ( position !== undefined ) {
  17488. dataCount = position.count;
  17489. }
  17490. var rangeStart = geometry.drawRange.start * rangeFactor;
  17491. var rangeCount = geometry.drawRange.count * rangeFactor;
  17492. var groupStart = group !== null ? group.start * rangeFactor : 0;
  17493. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  17494. var drawStart = Math.max( rangeStart, groupStart );
  17495. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  17496. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  17497. if ( drawCount === 0 ) return;
  17498. //
  17499. if ( object.isMesh ) {
  17500. if ( material.wireframe === true ) {
  17501. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17502. renderer.setMode( _gl.LINES );
  17503. } else {
  17504. switch ( object.drawMode ) {
  17505. case TrianglesDrawMode:
  17506. renderer.setMode( _gl.TRIANGLES );
  17507. break;
  17508. case TriangleStripDrawMode:
  17509. renderer.setMode( _gl.TRIANGLE_STRIP );
  17510. break;
  17511. case TriangleFanDrawMode:
  17512. renderer.setMode( _gl.TRIANGLE_FAN );
  17513. break;
  17514. }
  17515. }
  17516. } else if ( object.isLine ) {
  17517. var lineWidth = material.linewidth;
  17518. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17519. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17520. if ( object.isLineSegments ) {
  17521. renderer.setMode( _gl.LINES );
  17522. } else if ( object.isLineLoop ) {
  17523. renderer.setMode( _gl.LINE_LOOP );
  17524. } else {
  17525. renderer.setMode( _gl.LINE_STRIP );
  17526. }
  17527. } else if ( object.isPoints ) {
  17528. renderer.setMode( _gl.POINTS );
  17529. }
  17530. if ( geometry && geometry.isInstancedBufferGeometry ) {
  17531. if ( geometry.maxInstancedCount > 0 ) {
  17532. renderer.renderInstances( geometry, drawStart, drawCount );
  17533. }
  17534. } else {
  17535. renderer.render( drawStart, drawCount );
  17536. }
  17537. };
  17538. function setupVertexAttributes( material, program, geometry ) {
  17539. if ( geometry && geometry.isInstancedBufferGeometry ) {
  17540. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  17541. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  17542. return;
  17543. }
  17544. }
  17545. state.initAttributes();
  17546. var geometryAttributes = geometry.attributes;
  17547. var programAttributes = program.getAttributes();
  17548. var materialDefaultAttributeValues = material.defaultAttributeValues;
  17549. for ( var name in programAttributes ) {
  17550. var programAttribute = programAttributes[ name ];
  17551. if ( programAttribute >= 0 ) {
  17552. var geometryAttribute = geometryAttributes[ name ];
  17553. if ( geometryAttribute !== undefined ) {
  17554. var normalized = geometryAttribute.normalized;
  17555. var size = geometryAttribute.itemSize;
  17556. var attribute = attributes.get( geometryAttribute );
  17557. // TODO Attribute may not be available on context restore
  17558. if ( attribute === undefined ) continue;
  17559. var buffer = attribute.buffer;
  17560. var type = attribute.type;
  17561. var bytesPerElement = attribute.bytesPerElement;
  17562. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  17563. var data = geometryAttribute.data;
  17564. var stride = data.stride;
  17565. var offset = geometryAttribute.offset;
  17566. if ( data && data.isInstancedInterleavedBuffer ) {
  17567. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  17568. if ( geometry.maxInstancedCount === undefined ) {
  17569. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  17570. }
  17571. } else {
  17572. state.enableAttribute( programAttribute );
  17573. }
  17574. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  17575. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  17576. } else {
  17577. if ( geometryAttribute.isInstancedBufferAttribute ) {
  17578. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  17579. if ( geometry.maxInstancedCount === undefined ) {
  17580. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  17581. }
  17582. } else {
  17583. state.enableAttribute( programAttribute );
  17584. }
  17585. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  17586. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  17587. }
  17588. } else if ( materialDefaultAttributeValues !== undefined ) {
  17589. var value = materialDefaultAttributeValues[ name ];
  17590. if ( value !== undefined ) {
  17591. switch ( value.length ) {
  17592. case 2:
  17593. _gl.vertexAttrib2fv( programAttribute, value );
  17594. break;
  17595. case 3:
  17596. _gl.vertexAttrib3fv( programAttribute, value );
  17597. break;
  17598. case 4:
  17599. _gl.vertexAttrib4fv( programAttribute, value );
  17600. break;
  17601. default:
  17602. _gl.vertexAttrib1fv( programAttribute, value );
  17603. }
  17604. }
  17605. }
  17606. }
  17607. }
  17608. state.disableUnusedAttributes();
  17609. }
  17610. // Compile
  17611. this.compile = function ( scene, camera ) {
  17612. currentRenderState = renderStates.get( scene, camera );
  17613. currentRenderState.init();
  17614. scene.traverse( function ( object ) {
  17615. if ( object.isLight ) {
  17616. currentRenderState.pushLight( object );
  17617. if ( object.castShadow ) {
  17618. currentRenderState.pushShadow( object );
  17619. }
  17620. }
  17621. } );
  17622. currentRenderState.setupLights( camera );
  17623. scene.traverse( function ( object ) {
  17624. if ( object.material ) {
  17625. if ( Array.isArray( object.material ) ) {
  17626. for ( var i = 0; i < object.material.length; i ++ ) {
  17627. initMaterial( object.material[ i ], scene.fog, object );
  17628. }
  17629. } else {
  17630. initMaterial( object.material, scene.fog, object );
  17631. }
  17632. }
  17633. } );
  17634. };
  17635. // Animation Loop
  17636. var isAnimating = false;
  17637. var onAnimationFrame = null;
  17638. function startAnimation() {
  17639. if ( isAnimating ) return;
  17640. requestAnimationLoopFrame();
  17641. isAnimating = true;
  17642. }
  17643. function stopAnimation() {
  17644. isAnimating = false;
  17645. }
  17646. function requestAnimationLoopFrame() {
  17647. var device = vr.getDevice();
  17648. if ( device && device.isPresenting ) {
  17649. device.requestAnimationFrame( animationLoop );
  17650. } else {
  17651. window.requestAnimationFrame( animationLoop );
  17652. }
  17653. }
  17654. function animationLoop( time ) {
  17655. if ( isAnimating === false ) return;
  17656. onAnimationFrame( time );
  17657. requestAnimationLoopFrame();
  17658. }
  17659. this.animate = function ( callback ) {
  17660. onAnimationFrame = callback;
  17661. onAnimationFrame !== null ? startAnimation() : stopAnimation();
  17662. };
  17663. // Rendering
  17664. this.render = function ( scene, camera, renderTarget, forceClear ) {
  17665. if ( ! ( camera && camera.isCamera ) ) {
  17666. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17667. return;
  17668. }
  17669. if ( _isContextLost ) return;
  17670. // reset caching for this frame
  17671. _currentGeometryProgram = '';
  17672. _currentMaterialId = - 1;
  17673. _currentCamera = null;
  17674. // update scene graph
  17675. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  17676. // update camera matrices and frustum
  17677. if ( camera.parent === null ) camera.updateMatrixWorld();
  17678. if ( vr.enabled ) {
  17679. camera = vr.getCamera( camera );
  17680. }
  17681. //
  17682. currentRenderState = renderStates.get( scene, camera );
  17683. currentRenderState.init();
  17684. scene.onBeforeRender( _this, scene, camera, renderTarget );
  17685. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17686. _frustum.setFromMatrix( _projScreenMatrix );
  17687. _localClippingEnabled = this.localClippingEnabled;
  17688. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  17689. currentRenderList = renderLists.get( scene, camera );
  17690. currentRenderList.init();
  17691. projectObject( scene, camera, _this.sortObjects );
  17692. if ( _this.sortObjects === true ) {
  17693. currentRenderList.sort();
  17694. }
  17695. //
  17696. if ( _clippingEnabled ) _clipping.beginShadows();
  17697. var shadowsArray = currentRenderState.state.shadowsArray;
  17698. shadowMap.render( shadowsArray, scene, camera );
  17699. currentRenderState.setupLights( camera );
  17700. if ( _clippingEnabled ) _clipping.endShadows();
  17701. //
  17702. if ( this.info.autoReset ) this.info.reset();
  17703. if ( renderTarget === undefined ) {
  17704. renderTarget = null;
  17705. }
  17706. this.setRenderTarget( renderTarget );
  17707. //
  17708. background.render( currentRenderList, scene, camera, forceClear );
  17709. // render scene
  17710. var opaqueObjects = currentRenderList.opaque;
  17711. var transparentObjects = currentRenderList.transparent;
  17712. if ( scene.overrideMaterial ) {
  17713. var overrideMaterial = scene.overrideMaterial;
  17714. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  17715. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  17716. } else {
  17717. // opaque pass (front-to-back order)
  17718. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  17719. // transparent pass (back-to-front order)
  17720. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  17721. }
  17722. // custom renderers
  17723. var spritesArray = currentRenderState.state.spritesArray;
  17724. spriteRenderer.render( spritesArray, scene, camera );
  17725. // Generate mipmap if we're using any kind of mipmap filtering
  17726. if ( renderTarget ) {
  17727. textures.updateRenderTargetMipmap( renderTarget );
  17728. }
  17729. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17730. state.buffers.depth.setTest( true );
  17731. state.buffers.depth.setMask( true );
  17732. state.buffers.color.setMask( true );
  17733. state.setPolygonOffset( false );
  17734. scene.onAfterRender( _this, scene, camera );
  17735. if ( vr.enabled ) {
  17736. vr.submitFrame();
  17737. }
  17738. // _gl.finish();
  17739. currentRenderList = null;
  17740. currentRenderState = null;
  17741. };
  17742. /*
  17743. // TODO Duplicated code (Frustum)
  17744. var _sphere = new Sphere();
  17745. function isObjectViewable( object ) {
  17746. var geometry = object.geometry;
  17747. if ( geometry.boundingSphere === null )
  17748. geometry.computeBoundingSphere();
  17749. _sphere.copy( geometry.boundingSphere ).
  17750. applyMatrix4( object.matrixWorld );
  17751. return isSphereViewable( _sphere );
  17752. }
  17753. function isSpriteViewable( sprite ) {
  17754. _sphere.center.set( 0, 0, 0 );
  17755. _sphere.radius = 0.7071067811865476;
  17756. _sphere.applyMatrix4( sprite.matrixWorld );
  17757. return isSphereViewable( _sphere );
  17758. }
  17759. function isSphereViewable( sphere ) {
  17760. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  17761. var numPlanes = _clipping.numPlanes;
  17762. if ( numPlanes === 0 ) return true;
  17763. var planes = _this.clippingPlanes,
  17764. center = sphere.center,
  17765. negRad = - sphere.radius,
  17766. i = 0;
  17767. do {
  17768. // out when deeper than radius in the negative halfspace
  17769. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  17770. } while ( ++ i !== numPlanes );
  17771. return true;
  17772. }
  17773. */
  17774. function projectObject( object, camera, sortObjects ) {
  17775. if ( object.visible === false ) return;
  17776. var visible = object.layers.test( camera.layers );
  17777. if ( visible ) {
  17778. if ( object.isLight ) {
  17779. currentRenderState.pushLight( object );
  17780. if ( object.castShadow ) {
  17781. currentRenderState.pushShadow( object );
  17782. }
  17783. } else if ( object.isSprite ) {
  17784. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17785. currentRenderState.pushSprite( object );
  17786. }
  17787. } else if ( object.isImmediateRenderObject ) {
  17788. if ( sortObjects ) {
  17789. _vector3.setFromMatrixPosition( object.matrixWorld )
  17790. .applyMatrix4( _projScreenMatrix );
  17791. }
  17792. currentRenderList.push( object, null, object.material, _vector3.z, null );
  17793. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17794. if ( object.isSkinnedMesh ) {
  17795. object.skeleton.update();
  17796. }
  17797. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17798. if ( sortObjects ) {
  17799. _vector3.setFromMatrixPosition( object.matrixWorld )
  17800. .applyMatrix4( _projScreenMatrix );
  17801. }
  17802. var geometry = objects.update( object );
  17803. var material = object.material;
  17804. if ( Array.isArray( material ) ) {
  17805. var groups = geometry.groups;
  17806. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  17807. var group = groups[ i ];
  17808. var groupMaterial = material[ group.materialIndex ];
  17809. if ( groupMaterial && groupMaterial.visible ) {
  17810. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  17811. }
  17812. }
  17813. } else if ( material.visible ) {
  17814. currentRenderList.push( object, geometry, material, _vector3.z, null );
  17815. }
  17816. }
  17817. }
  17818. }
  17819. var children = object.children;
  17820. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17821. projectObject( children[ i ], camera, sortObjects );
  17822. }
  17823. }
  17824. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  17825. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  17826. var renderItem = renderList[ i ];
  17827. var object = renderItem.object;
  17828. var geometry = renderItem.geometry;
  17829. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  17830. var group = renderItem.group;
  17831. if ( camera.isArrayCamera ) {
  17832. _currentArrayCamera = camera;
  17833. var cameras = camera.cameras;
  17834. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  17835. var camera2 = cameras[ j ];
  17836. if ( object.layers.test( camera2.layers ) ) {
  17837. var bounds = camera2.bounds;
  17838. var x = bounds.x * _width;
  17839. var y = bounds.y * _height;
  17840. var width = bounds.z * _width;
  17841. var height = bounds.w * _height;
  17842. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  17843. renderObject( object, scene, camera2, geometry, material, group );
  17844. }
  17845. }
  17846. } else {
  17847. _currentArrayCamera = null;
  17848. renderObject( object, scene, camera, geometry, material, group );
  17849. }
  17850. }
  17851. }
  17852. function renderObject( object, scene, camera, geometry, material, group ) {
  17853. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17854. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  17855. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17856. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17857. if ( object.isImmediateRenderObject ) {
  17858. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17859. state.setMaterial( material, frontFaceCW );
  17860. var program = setProgram( camera, scene.fog, material, object );
  17861. _currentGeometryProgram = '';
  17862. renderObjectImmediate( object, program, material );
  17863. } else {
  17864. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  17865. }
  17866. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17867. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  17868. }
  17869. function initMaterial( material, fog, object ) {
  17870. var materialProperties = properties.get( material );
  17871. var lights = currentRenderState.state.lights;
  17872. var shadowsArray = currentRenderState.state.shadowsArray;
  17873. var parameters = programCache.getParameters(
  17874. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  17875. var code = programCache.getProgramCode( material, parameters );
  17876. var program = materialProperties.program;
  17877. var programChange = true;
  17878. if ( program === undefined ) {
  17879. // new material
  17880. material.addEventListener( 'dispose', onMaterialDispose );
  17881. } else if ( program.code !== code ) {
  17882. // changed glsl or parameters
  17883. releaseMaterialProgramReference( material );
  17884. } else if ( materialProperties.lightsHash !== lights.state.hash ) {
  17885. properties.update( material, 'lightsHash', lights.state.hash );
  17886. programChange = false;
  17887. } else if ( parameters.shaderID !== undefined ) {
  17888. // same glsl and uniform list
  17889. return;
  17890. } else {
  17891. // only rebuild uniform list
  17892. programChange = false;
  17893. }
  17894. if ( programChange ) {
  17895. if ( parameters.shaderID ) {
  17896. var shader = ShaderLib[ parameters.shaderID ];
  17897. materialProperties.shader = {
  17898. name: material.type,
  17899. uniforms: UniformsUtils.clone( shader.uniforms ),
  17900. vertexShader: shader.vertexShader,
  17901. fragmentShader: shader.fragmentShader
  17902. };
  17903. } else {
  17904. materialProperties.shader = {
  17905. name: material.type,
  17906. uniforms: material.uniforms,
  17907. vertexShader: material.vertexShader,
  17908. fragmentShader: material.fragmentShader
  17909. };
  17910. }
  17911. material.onBeforeCompile( materialProperties.shader, _this );
  17912. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  17913. materialProperties.program = program;
  17914. material.program = program;
  17915. }
  17916. var programAttributes = program.getAttributes();
  17917. if ( material.morphTargets ) {
  17918. material.numSupportedMorphTargets = 0;
  17919. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  17920. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  17921. material.numSupportedMorphTargets ++;
  17922. }
  17923. }
  17924. }
  17925. if ( material.morphNormals ) {
  17926. material.numSupportedMorphNormals = 0;
  17927. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  17928. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  17929. material.numSupportedMorphNormals ++;
  17930. }
  17931. }
  17932. }
  17933. var uniforms = materialProperties.shader.uniforms;
  17934. if ( ! material.isShaderMaterial &&
  17935. ! material.isRawShaderMaterial ||
  17936. material.clipping === true ) {
  17937. materialProperties.numClippingPlanes = _clipping.numPlanes;
  17938. materialProperties.numIntersection = _clipping.numIntersection;
  17939. uniforms.clippingPlanes = _clipping.uniform;
  17940. }
  17941. materialProperties.fog = fog;
  17942. // store the light setup it was created for
  17943. materialProperties.lightsHash = lights.state.hash;
  17944. if ( material.lights ) {
  17945. // wire up the material to this renderer's lighting state
  17946. uniforms.ambientLightColor.value = lights.state.ambient;
  17947. uniforms.directionalLights.value = lights.state.directional;
  17948. uniforms.spotLights.value = lights.state.spot;
  17949. uniforms.rectAreaLights.value = lights.state.rectArea;
  17950. uniforms.pointLights.value = lights.state.point;
  17951. uniforms.hemisphereLights.value = lights.state.hemi;
  17952. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17953. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17954. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17955. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  17956. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17957. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17958. // TODO (abelnation): add area lights shadow info to uniforms
  17959. }
  17960. var progUniforms = materialProperties.program.getUniforms(),
  17961. uniformsList =
  17962. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17963. materialProperties.uniformsList = uniformsList;
  17964. }
  17965. function setProgram( camera, fog, material, object ) {
  17966. _usedTextureUnits = 0;
  17967. var materialProperties = properties.get( material );
  17968. var lights = currentRenderState.state.lights;
  17969. if ( _clippingEnabled ) {
  17970. if ( _localClippingEnabled || camera !== _currentCamera ) {
  17971. var useCache =
  17972. camera === _currentCamera &&
  17973. material.id === _currentMaterialId;
  17974. // we might want to call this function with some ClippingGroup
  17975. // object instead of the material, once it becomes feasible
  17976. // (#8465, #8379)
  17977. _clipping.setState(
  17978. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  17979. camera, materialProperties, useCache );
  17980. }
  17981. }
  17982. if ( material.needsUpdate === false ) {
  17983. if ( materialProperties.program === undefined ) {
  17984. material.needsUpdate = true;
  17985. } else if ( material.fog && materialProperties.fog !== fog ) {
  17986. material.needsUpdate = true;
  17987. } else if ( material.lights && materialProperties.lightsHash !== lights.state.hash ) {
  17988. material.needsUpdate = true;
  17989. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17990. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  17991. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  17992. material.needsUpdate = true;
  17993. }
  17994. }
  17995. if ( material.needsUpdate ) {
  17996. initMaterial( material, fog, object );
  17997. material.needsUpdate = false;
  17998. }
  17999. var refreshProgram = false;
  18000. var refreshMaterial = false;
  18001. var refreshLights = false;
  18002. var program = materialProperties.program,
  18003. p_uniforms = program.getUniforms(),
  18004. m_uniforms = materialProperties.shader.uniforms;
  18005. if ( state.useProgram( program.program ) ) {
  18006. refreshProgram = true;
  18007. refreshMaterial = true;
  18008. refreshLights = true;
  18009. }
  18010. if ( material.id !== _currentMaterialId ) {
  18011. _currentMaterialId = material.id;
  18012. refreshMaterial = true;
  18013. }
  18014. if ( refreshProgram || camera !== _currentCamera ) {
  18015. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  18016. if ( capabilities.logarithmicDepthBuffer ) {
  18017. p_uniforms.setValue( _gl, 'logDepthBufFC',
  18018. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  18019. }
  18020. // Avoid unneeded uniform updates per ArrayCamera's sub-camera
  18021. if ( _currentCamera !== ( _currentArrayCamera || camera ) ) {
  18022. _currentCamera = ( _currentArrayCamera || camera );
  18023. // lighting uniforms depend on the camera so enforce an update
  18024. // now, in case this material supports lights - or later, when
  18025. // the next material that does gets activated:
  18026. refreshMaterial = true; // set to true on material change
  18027. refreshLights = true; // remains set until update done
  18028. }
  18029. // load material specific uniforms
  18030. // (shader material also gets them for the sake of genericity)
  18031. if ( material.isShaderMaterial ||
  18032. material.isMeshPhongMaterial ||
  18033. material.isMeshStandardMaterial ||
  18034. material.envMap ) {
  18035. var uCamPos = p_uniforms.map.cameraPosition;
  18036. if ( uCamPos !== undefined ) {
  18037. uCamPos.setValue( _gl,
  18038. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  18039. }
  18040. }
  18041. if ( material.isMeshPhongMaterial ||
  18042. material.isMeshLambertMaterial ||
  18043. material.isMeshBasicMaterial ||
  18044. material.isMeshStandardMaterial ||
  18045. material.isShaderMaterial ||
  18046. material.skinning ) {
  18047. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  18048. }
  18049. }
  18050. // skinning uniforms must be set even if material didn't change
  18051. // auto-setting of texture unit for bone texture must go before other textures
  18052. // not sure why, but otherwise weird things happen
  18053. if ( material.skinning ) {
  18054. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  18055. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  18056. var skeleton = object.skeleton;
  18057. if ( skeleton ) {
  18058. var bones = skeleton.bones;
  18059. if ( capabilities.floatVertexTextures ) {
  18060. if ( skeleton.boneTexture === undefined ) {
  18061. // layout (1 matrix = 4 pixels)
  18062. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18063. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18064. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18065. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18066. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18067. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  18068. size = _Math.ceilPowerOfTwo( size );
  18069. size = Math.max( size, 4 );
  18070. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18071. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  18072. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18073. boneTexture.needsUpdate = true;
  18074. skeleton.boneMatrices = boneMatrices;
  18075. skeleton.boneTexture = boneTexture;
  18076. skeleton.boneTextureSize = size;
  18077. }
  18078. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  18079. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  18080. } else {
  18081. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  18082. }
  18083. }
  18084. }
  18085. if ( refreshMaterial ) {
  18086. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  18087. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  18088. if ( material.lights ) {
  18089. // the current material requires lighting info
  18090. // note: all lighting uniforms are always set correctly
  18091. // they simply reference the renderer's state for their
  18092. // values
  18093. //
  18094. // use the current material's .needsUpdate flags to set
  18095. // the GL state when required
  18096. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  18097. }
  18098. // refresh uniforms common to several materials
  18099. if ( fog && material.fog ) {
  18100. refreshUniformsFog( m_uniforms, fog );
  18101. }
  18102. if ( material.isMeshBasicMaterial ) {
  18103. refreshUniformsCommon( m_uniforms, material );
  18104. } else if ( material.isMeshLambertMaterial ) {
  18105. refreshUniformsCommon( m_uniforms, material );
  18106. refreshUniformsLambert( m_uniforms, material );
  18107. } else if ( material.isMeshPhongMaterial ) {
  18108. refreshUniformsCommon( m_uniforms, material );
  18109. if ( material.isMeshToonMaterial ) {
  18110. refreshUniformsToon( m_uniforms, material );
  18111. } else {
  18112. refreshUniformsPhong( m_uniforms, material );
  18113. }
  18114. } else if ( material.isMeshStandardMaterial ) {
  18115. refreshUniformsCommon( m_uniforms, material );
  18116. if ( material.isMeshPhysicalMaterial ) {
  18117. refreshUniformsPhysical( m_uniforms, material );
  18118. } else {
  18119. refreshUniformsStandard( m_uniforms, material );
  18120. }
  18121. } else if ( material.isMeshDepthMaterial ) {
  18122. refreshUniformsCommon( m_uniforms, material );
  18123. refreshUniformsDepth( m_uniforms, material );
  18124. } else if ( material.isMeshDistanceMaterial ) {
  18125. refreshUniformsCommon( m_uniforms, material );
  18126. refreshUniformsDistance( m_uniforms, material );
  18127. } else if ( material.isMeshNormalMaterial ) {
  18128. refreshUniformsCommon( m_uniforms, material );
  18129. refreshUniformsNormal( m_uniforms, material );
  18130. } else if ( material.isLineBasicMaterial ) {
  18131. refreshUniformsLine( m_uniforms, material );
  18132. if ( material.isLineDashedMaterial ) {
  18133. refreshUniformsDash( m_uniforms, material );
  18134. }
  18135. } else if ( material.isPointsMaterial ) {
  18136. refreshUniformsPoints( m_uniforms, material );
  18137. } else if ( material.isShadowMaterial ) {
  18138. m_uniforms.color.value = material.color;
  18139. m_uniforms.opacity.value = material.opacity;
  18140. }
  18141. // RectAreaLight Texture
  18142. // TODO (mrdoob): Find a nicer implementation
  18143. if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  18144. if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  18145. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  18146. }
  18147. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  18148. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  18149. material.uniformsNeedUpdate = false;
  18150. }
  18151. // common matrices
  18152. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  18153. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  18154. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  18155. return program;
  18156. }
  18157. // Uniforms (refresh uniforms objects)
  18158. function refreshUniformsCommon( uniforms, material ) {
  18159. uniforms.opacity.value = material.opacity;
  18160. if ( material.color ) {
  18161. uniforms.diffuse.value = material.color;
  18162. }
  18163. if ( material.emissive ) {
  18164. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  18165. }
  18166. if ( material.map ) {
  18167. uniforms.map.value = material.map;
  18168. }
  18169. if ( material.alphaMap ) {
  18170. uniforms.alphaMap.value = material.alphaMap;
  18171. }
  18172. if ( material.specularMap ) {
  18173. uniforms.specularMap.value = material.specularMap;
  18174. }
  18175. if ( material.envMap ) {
  18176. uniforms.envMap.value = material.envMap;
  18177. // don't flip CubeTexture envMaps, flip everything else:
  18178. // WebGLRenderTargetCube will be flipped for backwards compatibility
  18179. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  18180. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  18181. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  18182. uniforms.reflectivity.value = material.reflectivity;
  18183. uniforms.refractionRatio.value = material.refractionRatio;
  18184. uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel;
  18185. }
  18186. if ( material.lightMap ) {
  18187. uniforms.lightMap.value = material.lightMap;
  18188. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  18189. }
  18190. if ( material.aoMap ) {
  18191. uniforms.aoMap.value = material.aoMap;
  18192. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  18193. }
  18194. // uv repeat and offset setting priorities
  18195. // 1. color map
  18196. // 2. specular map
  18197. // 3. normal map
  18198. // 4. bump map
  18199. // 5. alpha map
  18200. // 6. emissive map
  18201. var uvScaleMap;
  18202. if ( material.map ) {
  18203. uvScaleMap = material.map;
  18204. } else if ( material.specularMap ) {
  18205. uvScaleMap = material.specularMap;
  18206. } else if ( material.displacementMap ) {
  18207. uvScaleMap = material.displacementMap;
  18208. } else if ( material.normalMap ) {
  18209. uvScaleMap = material.normalMap;
  18210. } else if ( material.bumpMap ) {
  18211. uvScaleMap = material.bumpMap;
  18212. } else if ( material.roughnessMap ) {
  18213. uvScaleMap = material.roughnessMap;
  18214. } else if ( material.metalnessMap ) {
  18215. uvScaleMap = material.metalnessMap;
  18216. } else if ( material.alphaMap ) {
  18217. uvScaleMap = material.alphaMap;
  18218. } else if ( material.emissiveMap ) {
  18219. uvScaleMap = material.emissiveMap;
  18220. }
  18221. if ( uvScaleMap !== undefined ) {
  18222. // backwards compatibility
  18223. if ( uvScaleMap.isWebGLRenderTarget ) {
  18224. uvScaleMap = uvScaleMap.texture;
  18225. }
  18226. if ( uvScaleMap.matrixAutoUpdate === true ) {
  18227. uvScaleMap.updateMatrix();
  18228. }
  18229. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  18230. }
  18231. }
  18232. function refreshUniformsLine( uniforms, material ) {
  18233. uniforms.diffuse.value = material.color;
  18234. uniforms.opacity.value = material.opacity;
  18235. }
  18236. function refreshUniformsDash( uniforms, material ) {
  18237. uniforms.dashSize.value = material.dashSize;
  18238. uniforms.totalSize.value = material.dashSize + material.gapSize;
  18239. uniforms.scale.value = material.scale;
  18240. }
  18241. function refreshUniformsPoints( uniforms, material ) {
  18242. uniforms.diffuse.value = material.color;
  18243. uniforms.opacity.value = material.opacity;
  18244. uniforms.size.value = material.size * _pixelRatio;
  18245. uniforms.scale.value = _height * 0.5;
  18246. uniforms.map.value = material.map;
  18247. if ( material.map !== null ) {
  18248. if ( material.map.matrixAutoUpdate === true ) {
  18249. material.map.updateMatrix();
  18250. }
  18251. uniforms.uvTransform.value.copy( material.map.matrix );
  18252. }
  18253. }
  18254. function refreshUniformsFog( uniforms, fog ) {
  18255. uniforms.fogColor.value = fog.color;
  18256. if ( fog.isFog ) {
  18257. uniforms.fogNear.value = fog.near;
  18258. uniforms.fogFar.value = fog.far;
  18259. } else if ( fog.isFogExp2 ) {
  18260. uniforms.fogDensity.value = fog.density;
  18261. }
  18262. }
  18263. function refreshUniformsLambert( uniforms, material ) {
  18264. if ( material.emissiveMap ) {
  18265. uniforms.emissiveMap.value = material.emissiveMap;
  18266. }
  18267. }
  18268. function refreshUniformsPhong( uniforms, material ) {
  18269. uniforms.specular.value = material.specular;
  18270. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  18271. if ( material.emissiveMap ) {
  18272. uniforms.emissiveMap.value = material.emissiveMap;
  18273. }
  18274. if ( material.bumpMap ) {
  18275. uniforms.bumpMap.value = material.bumpMap;
  18276. uniforms.bumpScale.value = material.bumpScale;
  18277. }
  18278. if ( material.normalMap ) {
  18279. uniforms.normalMap.value = material.normalMap;
  18280. uniforms.normalScale.value.copy( material.normalScale );
  18281. }
  18282. if ( material.displacementMap ) {
  18283. uniforms.displacementMap.value = material.displacementMap;
  18284. uniforms.displacementScale.value = material.displacementScale;
  18285. uniforms.displacementBias.value = material.displacementBias;
  18286. }
  18287. }
  18288. function refreshUniformsToon( uniforms, material ) {
  18289. refreshUniformsPhong( uniforms, material );
  18290. if ( material.gradientMap ) {
  18291. uniforms.gradientMap.value = material.gradientMap;
  18292. }
  18293. }
  18294. function refreshUniformsStandard( uniforms, material ) {
  18295. uniforms.roughness.value = material.roughness;
  18296. uniforms.metalness.value = material.metalness;
  18297. if ( material.roughnessMap ) {
  18298. uniforms.roughnessMap.value = material.roughnessMap;
  18299. }
  18300. if ( material.metalnessMap ) {
  18301. uniforms.metalnessMap.value = material.metalnessMap;
  18302. }
  18303. if ( material.emissiveMap ) {
  18304. uniforms.emissiveMap.value = material.emissiveMap;
  18305. }
  18306. if ( material.bumpMap ) {
  18307. uniforms.bumpMap.value = material.bumpMap;
  18308. uniforms.bumpScale.value = material.bumpScale;
  18309. }
  18310. if ( material.normalMap ) {
  18311. uniforms.normalMap.value = material.normalMap;
  18312. uniforms.normalScale.value.copy( material.normalScale );
  18313. }
  18314. if ( material.displacementMap ) {
  18315. uniforms.displacementMap.value = material.displacementMap;
  18316. uniforms.displacementScale.value = material.displacementScale;
  18317. uniforms.displacementBias.value = material.displacementBias;
  18318. }
  18319. if ( material.envMap ) {
  18320. //uniforms.envMap.value = material.envMap; // part of uniforms common
  18321. uniforms.envMapIntensity.value = material.envMapIntensity;
  18322. }
  18323. }
  18324. function refreshUniformsPhysical( uniforms, material ) {
  18325. uniforms.clearCoat.value = material.clearCoat;
  18326. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  18327. refreshUniformsStandard( uniforms, material );
  18328. }
  18329. function refreshUniformsDepth( uniforms, material ) {
  18330. if ( material.displacementMap ) {
  18331. uniforms.displacementMap.value = material.displacementMap;
  18332. uniforms.displacementScale.value = material.displacementScale;
  18333. uniforms.displacementBias.value = material.displacementBias;
  18334. }
  18335. }
  18336. function refreshUniformsDistance( uniforms, material ) {
  18337. if ( material.displacementMap ) {
  18338. uniforms.displacementMap.value = material.displacementMap;
  18339. uniforms.displacementScale.value = material.displacementScale;
  18340. uniforms.displacementBias.value = material.displacementBias;
  18341. }
  18342. uniforms.referencePosition.value.copy( material.referencePosition );
  18343. uniforms.nearDistance.value = material.nearDistance;
  18344. uniforms.farDistance.value = material.farDistance;
  18345. }
  18346. function refreshUniformsNormal( uniforms, material ) {
  18347. if ( material.bumpMap ) {
  18348. uniforms.bumpMap.value = material.bumpMap;
  18349. uniforms.bumpScale.value = material.bumpScale;
  18350. }
  18351. if ( material.normalMap ) {
  18352. uniforms.normalMap.value = material.normalMap;
  18353. uniforms.normalScale.value.copy( material.normalScale );
  18354. }
  18355. if ( material.displacementMap ) {
  18356. uniforms.displacementMap.value = material.displacementMap;
  18357. uniforms.displacementScale.value = material.displacementScale;
  18358. uniforms.displacementBias.value = material.displacementBias;
  18359. }
  18360. }
  18361. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  18362. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  18363. uniforms.ambientLightColor.needsUpdate = value;
  18364. uniforms.directionalLights.needsUpdate = value;
  18365. uniforms.pointLights.needsUpdate = value;
  18366. uniforms.spotLights.needsUpdate = value;
  18367. uniforms.rectAreaLights.needsUpdate = value;
  18368. uniforms.hemisphereLights.needsUpdate = value;
  18369. }
  18370. // Textures
  18371. function allocTextureUnit() {
  18372. var textureUnit = _usedTextureUnits;
  18373. if ( textureUnit >= capabilities.maxTextures ) {
  18374. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  18375. }
  18376. _usedTextureUnits += 1;
  18377. return textureUnit;
  18378. }
  18379. this.allocTextureUnit = allocTextureUnit;
  18380. // this.setTexture2D = setTexture2D;
  18381. this.setTexture2D = ( function () {
  18382. var warned = false;
  18383. // backwards compatibility: peel texture.texture
  18384. return function setTexture2D( texture, slot ) {
  18385. if ( texture && texture.isWebGLRenderTarget ) {
  18386. if ( ! warned ) {
  18387. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  18388. warned = true;
  18389. }
  18390. texture = texture.texture;
  18391. }
  18392. textures.setTexture2D( texture, slot );
  18393. };
  18394. }() );
  18395. this.setTexture = ( function () {
  18396. var warned = false;
  18397. return function setTexture( texture, slot ) {
  18398. if ( ! warned ) {
  18399. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  18400. warned = true;
  18401. }
  18402. textures.setTexture2D( texture, slot );
  18403. };
  18404. }() );
  18405. this.setTextureCube = ( function () {
  18406. var warned = false;
  18407. return function setTextureCube( texture, slot ) {
  18408. // backwards compatibility: peel texture.texture
  18409. if ( texture && texture.isWebGLRenderTargetCube ) {
  18410. if ( ! warned ) {
  18411. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  18412. warned = true;
  18413. }
  18414. texture = texture.texture;
  18415. }
  18416. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  18417. // TODO: unify these code paths
  18418. if ( ( texture && texture.isCubeTexture ) ||
  18419. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  18420. // CompressedTexture can have Array in image :/
  18421. // this function alone should take care of cube textures
  18422. textures.setTextureCube( texture, slot );
  18423. } else {
  18424. // assumed: texture property of THREE.WebGLRenderTargetCube
  18425. textures.setTextureCubeDynamic( texture, slot );
  18426. }
  18427. };
  18428. }() );
  18429. this.getRenderTarget = function () {
  18430. return _currentRenderTarget;
  18431. };
  18432. this.setRenderTarget = function ( renderTarget ) {
  18433. _currentRenderTarget = renderTarget;
  18434. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  18435. textures.setupRenderTarget( renderTarget );
  18436. }
  18437. var framebuffer = null;
  18438. var isCube = false;
  18439. if ( renderTarget ) {
  18440. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18441. if ( renderTarget.isWebGLRenderTargetCube ) {
  18442. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  18443. isCube = true;
  18444. } else {
  18445. framebuffer = __webglFramebuffer;
  18446. }
  18447. _currentViewport.copy( renderTarget.viewport );
  18448. _currentScissor.copy( renderTarget.scissor );
  18449. _currentScissorTest = renderTarget.scissorTest;
  18450. } else {
  18451. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  18452. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  18453. _currentScissorTest = _scissorTest;
  18454. }
  18455. if ( _currentFramebuffer !== framebuffer ) {
  18456. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18457. _currentFramebuffer = framebuffer;
  18458. }
  18459. state.viewport( _currentViewport );
  18460. state.scissor( _currentScissor );
  18461. state.setScissorTest( _currentScissorTest );
  18462. if ( isCube ) {
  18463. var textureProperties = properties.get( renderTarget.texture );
  18464. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  18465. }
  18466. };
  18467. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  18468. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18469. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18470. return;
  18471. }
  18472. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18473. if ( framebuffer ) {
  18474. var restore = false;
  18475. if ( framebuffer !== _currentFramebuffer ) {
  18476. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18477. restore = true;
  18478. }
  18479. try {
  18480. var texture = renderTarget.texture;
  18481. var textureFormat = texture.format;
  18482. var textureType = texture.type;
  18483. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  18484. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18485. return;
  18486. }
  18487. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  18488. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  18489. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  18490. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18491. return;
  18492. }
  18493. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  18494. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18495. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18496. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18497. }
  18498. } else {
  18499. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  18500. }
  18501. } finally {
  18502. if ( restore ) {
  18503. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  18504. }
  18505. }
  18506. }
  18507. };
  18508. this.copyFramebufferToTexture = function ( position, texture, level ) {
  18509. var width = texture.image.width;
  18510. var height = texture.image.height;
  18511. var glFormat = utils.convert( texture.format );
  18512. this.setTexture2D( texture, 0 );
  18513. _gl.copyTexImage2D( _gl.TEXTURE_2D, level || 0, glFormat, position.x, position.y, width, height, 0 );
  18514. };
  18515. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  18516. var width = srcTexture.image.width;
  18517. var height = srcTexture.image.height;
  18518. var glFormat = utils.convert( dstTexture.format );
  18519. var glType = utils.convert( dstTexture.type );
  18520. var pixels = srcTexture.isDataTexture ? srcTexture.image.data : srcTexture.image;
  18521. this.setTexture2D( dstTexture, 0 );
  18522. _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, width, height, glFormat, glType, pixels );
  18523. };
  18524. }
  18525. /**
  18526. * @author mrdoob / http://mrdoob.com/
  18527. * @author alteredq / http://alteredqualia.com/
  18528. */
  18529. function FogExp2( color, density ) {
  18530. this.name = '';
  18531. this.color = new Color( color );
  18532. this.density = ( density !== undefined ) ? density : 0.00025;
  18533. }
  18534. FogExp2.prototype.isFogExp2 = true;
  18535. FogExp2.prototype.clone = function () {
  18536. return new FogExp2( this.color.getHex(), this.density );
  18537. };
  18538. FogExp2.prototype.toJSON = function ( /* meta */ ) {
  18539. return {
  18540. type: 'FogExp2',
  18541. color: this.color.getHex(),
  18542. density: this.density
  18543. };
  18544. };
  18545. /**
  18546. * @author mrdoob / http://mrdoob.com/
  18547. * @author alteredq / http://alteredqualia.com/
  18548. */
  18549. function Fog( color, near, far ) {
  18550. this.name = '';
  18551. this.color = new Color( color );
  18552. this.near = ( near !== undefined ) ? near : 1;
  18553. this.far = ( far !== undefined ) ? far : 1000;
  18554. }
  18555. Fog.prototype.isFog = true;
  18556. Fog.prototype.clone = function () {
  18557. return new Fog( this.color.getHex(), this.near, this.far );
  18558. };
  18559. Fog.prototype.toJSON = function ( /* meta */ ) {
  18560. return {
  18561. type: 'Fog',
  18562. color: this.color.getHex(),
  18563. near: this.near,
  18564. far: this.far
  18565. };
  18566. };
  18567. /**
  18568. * @author mrdoob / http://mrdoob.com/
  18569. */
  18570. function Scene() {
  18571. Object3D.call( this );
  18572. this.type = 'Scene';
  18573. this.background = null;
  18574. this.fog = null;
  18575. this.overrideMaterial = null;
  18576. this.autoUpdate = true; // checked by the renderer
  18577. }
  18578. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18579. constructor: Scene,
  18580. copy: function ( source, recursive ) {
  18581. Object3D.prototype.copy.call( this, source, recursive );
  18582. if ( source.background !== null ) this.background = source.background.clone();
  18583. if ( source.fog !== null ) this.fog = source.fog.clone();
  18584. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18585. this.autoUpdate = source.autoUpdate;
  18586. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18587. return this;
  18588. },
  18589. toJSON: function ( meta ) {
  18590. var data = Object3D.prototype.toJSON.call( this, meta );
  18591. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  18592. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18593. return data;
  18594. }
  18595. } );
  18596. /**
  18597. * @author alteredq / http://alteredqualia.com/
  18598. *
  18599. * parameters = {
  18600. * color: <hex>,
  18601. * opacity: <float>,
  18602. * map: new THREE.Texture( <Image> ),
  18603. *
  18604. * uvOffset: new THREE.Vector2(),
  18605. * uvScale: new THREE.Vector2()
  18606. * }
  18607. */
  18608. function SpriteMaterial( parameters ) {
  18609. Material.call( this );
  18610. this.type = 'SpriteMaterial';
  18611. this.color = new Color( 0xffffff );
  18612. this.map = null;
  18613. this.rotation = 0;
  18614. this.fog = false;
  18615. this.lights = false;
  18616. this.setValues( parameters );
  18617. }
  18618. SpriteMaterial.prototype = Object.create( Material.prototype );
  18619. SpriteMaterial.prototype.constructor = SpriteMaterial;
  18620. SpriteMaterial.prototype.isSpriteMaterial = true;
  18621. SpriteMaterial.prototype.copy = function ( source ) {
  18622. Material.prototype.copy.call( this, source );
  18623. this.color.copy( source.color );
  18624. this.map = source.map;
  18625. this.rotation = source.rotation;
  18626. return this;
  18627. };
  18628. /**
  18629. * @author mikael emtinger / http://gomo.se/
  18630. * @author alteredq / http://alteredqualia.com/
  18631. */
  18632. function Sprite( material ) {
  18633. Object3D.call( this );
  18634. this.type = 'Sprite';
  18635. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18636. this.center = new Vector2( 0.5, 0.5 );
  18637. }
  18638. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18639. constructor: Sprite,
  18640. isSprite: true,
  18641. raycast: ( function () {
  18642. var intersectPoint = new Vector3();
  18643. var worldPosition = new Vector3();
  18644. var worldScale = new Vector3();
  18645. return function raycast( raycaster, intersects ) {
  18646. worldPosition.setFromMatrixPosition( this.matrixWorld );
  18647. raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
  18648. worldScale.setFromMatrixScale( this.matrixWorld );
  18649. var guessSizeSq = worldScale.x * worldScale.y / 4;
  18650. if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;
  18651. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18652. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18653. intersects.push( {
  18654. distance: distance,
  18655. point: intersectPoint.clone(),
  18656. face: null,
  18657. object: this
  18658. } );
  18659. };
  18660. }() ),
  18661. clone: function () {
  18662. return new this.constructor( this.material ).copy( this );
  18663. },
  18664. copy: function ( source ) {
  18665. Object3D.prototype.copy.call( this, source );
  18666. if ( source.center !== undefined ) this.center.copy( source.center );
  18667. return this;
  18668. }
  18669. } );
  18670. /**
  18671. * @author mikael emtinger / http://gomo.se/
  18672. * @author alteredq / http://alteredqualia.com/
  18673. * @author mrdoob / http://mrdoob.com/
  18674. */
  18675. function LOD() {
  18676. Object3D.call( this );
  18677. this.type = 'LOD';
  18678. Object.defineProperties( this, {
  18679. levels: {
  18680. enumerable: true,
  18681. value: []
  18682. }
  18683. } );
  18684. }
  18685. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18686. constructor: LOD,
  18687. copy: function ( source ) {
  18688. Object3D.prototype.copy.call( this, source, false );
  18689. var levels = source.levels;
  18690. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18691. var level = levels[ i ];
  18692. this.addLevel( level.object.clone(), level.distance );
  18693. }
  18694. return this;
  18695. },
  18696. addLevel: function ( object, distance ) {
  18697. if ( distance === undefined ) distance = 0;
  18698. distance = Math.abs( distance );
  18699. var levels = this.levels;
  18700. for ( var l = 0; l < levels.length; l ++ ) {
  18701. if ( distance < levels[ l ].distance ) {
  18702. break;
  18703. }
  18704. }
  18705. levels.splice( l, 0, { distance: distance, object: object } );
  18706. this.add( object );
  18707. },
  18708. getObjectForDistance: function ( distance ) {
  18709. var levels = this.levels;
  18710. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18711. if ( distance < levels[ i ].distance ) {
  18712. break;
  18713. }
  18714. }
  18715. return levels[ i - 1 ].object;
  18716. },
  18717. raycast: ( function () {
  18718. var matrixPosition = new Vector3();
  18719. return function raycast( raycaster, intersects ) {
  18720. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  18721. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  18722. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18723. };
  18724. }() ),
  18725. update: function () {
  18726. var v1 = new Vector3();
  18727. var v2 = new Vector3();
  18728. return function update( camera ) {
  18729. var levels = this.levels;
  18730. if ( levels.length > 1 ) {
  18731. v1.setFromMatrixPosition( camera.matrixWorld );
  18732. v2.setFromMatrixPosition( this.matrixWorld );
  18733. var distance = v1.distanceTo( v2 );
  18734. levels[ 0 ].object.visible = true;
  18735. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18736. if ( distance >= levels[ i ].distance ) {
  18737. levels[ i - 1 ].object.visible = false;
  18738. levels[ i ].object.visible = true;
  18739. } else {
  18740. break;
  18741. }
  18742. }
  18743. for ( ; i < l; i ++ ) {
  18744. levels[ i ].object.visible = false;
  18745. }
  18746. }
  18747. };
  18748. }(),
  18749. toJSON: function ( meta ) {
  18750. var data = Object3D.prototype.toJSON.call( this, meta );
  18751. data.object.levels = [];
  18752. var levels = this.levels;
  18753. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18754. var level = levels[ i ];
  18755. data.object.levels.push( {
  18756. object: level.object.uuid,
  18757. distance: level.distance
  18758. } );
  18759. }
  18760. return data;
  18761. }
  18762. } );
  18763. /**
  18764. * @author mikael emtinger / http://gomo.se/
  18765. * @author alteredq / http://alteredqualia.com/
  18766. * @author michael guerrero / http://realitymeltdown.com
  18767. * @author ikerr / http://verold.com
  18768. */
  18769. function Skeleton( bones, boneInverses ) {
  18770. // copy the bone array
  18771. bones = bones || [];
  18772. this.bones = bones.slice( 0 );
  18773. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  18774. // use the supplied bone inverses or calculate the inverses
  18775. if ( boneInverses === undefined ) {
  18776. this.calculateInverses();
  18777. } else {
  18778. if ( this.bones.length === boneInverses.length ) {
  18779. this.boneInverses = boneInverses.slice( 0 );
  18780. } else {
  18781. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  18782. this.boneInverses = [];
  18783. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18784. this.boneInverses.push( new Matrix4() );
  18785. }
  18786. }
  18787. }
  18788. }
  18789. Object.assign( Skeleton.prototype, {
  18790. calculateInverses: function () {
  18791. this.boneInverses = [];
  18792. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18793. var inverse = new Matrix4();
  18794. if ( this.bones[ i ] ) {
  18795. inverse.getInverse( this.bones[ i ].matrixWorld );
  18796. }
  18797. this.boneInverses.push( inverse );
  18798. }
  18799. },
  18800. pose: function () {
  18801. var bone, i, il;
  18802. // recover the bind-time world matrices
  18803. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  18804. bone = this.bones[ i ];
  18805. if ( bone ) {
  18806. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  18807. }
  18808. }
  18809. // compute the local matrices, positions, rotations and scales
  18810. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  18811. bone = this.bones[ i ];
  18812. if ( bone ) {
  18813. if ( bone.parent && bone.parent.isBone ) {
  18814. bone.matrix.getInverse( bone.parent.matrixWorld );
  18815. bone.matrix.multiply( bone.matrixWorld );
  18816. } else {
  18817. bone.matrix.copy( bone.matrixWorld );
  18818. }
  18819. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18820. }
  18821. }
  18822. },
  18823. update: ( function () {
  18824. var offsetMatrix = new Matrix4();
  18825. var identityMatrix = new Matrix4();
  18826. return function update() {
  18827. var bones = this.bones;
  18828. var boneInverses = this.boneInverses;
  18829. var boneMatrices = this.boneMatrices;
  18830. var boneTexture = this.boneTexture;
  18831. // flatten bone matrices to array
  18832. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  18833. // compute the offset between the current and the original transform
  18834. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  18835. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18836. offsetMatrix.toArray( boneMatrices, i * 16 );
  18837. }
  18838. if ( boneTexture !== undefined ) {
  18839. boneTexture.needsUpdate = true;
  18840. }
  18841. };
  18842. } )(),
  18843. clone: function () {
  18844. return new Skeleton( this.bones, this.boneInverses );
  18845. },
  18846. getBoneByName: function ( name ) {
  18847. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18848. var bone = this.bones[ i ];
  18849. if ( bone.name === name ) {
  18850. return bone;
  18851. }
  18852. }
  18853. return undefined;
  18854. }
  18855. } );
  18856. /**
  18857. * @author mikael emtinger / http://gomo.se/
  18858. * @author alteredq / http://alteredqualia.com/
  18859. * @author ikerr / http://verold.com
  18860. */
  18861. function Bone() {
  18862. Object3D.call( this );
  18863. this.type = 'Bone';
  18864. }
  18865. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18866. constructor: Bone,
  18867. isBone: true
  18868. } );
  18869. /**
  18870. * @author mikael emtinger / http://gomo.se/
  18871. * @author alteredq / http://alteredqualia.com/
  18872. * @author ikerr / http://verold.com
  18873. */
  18874. function SkinnedMesh( geometry, material ) {
  18875. Mesh.call( this, geometry, material );
  18876. this.type = 'SkinnedMesh';
  18877. this.bindMode = 'attached';
  18878. this.bindMatrix = new Matrix4();
  18879. this.bindMatrixInverse = new Matrix4();
  18880. var bones = this.initBones();
  18881. var skeleton = new Skeleton( bones );
  18882. this.bind( skeleton, this.matrixWorld );
  18883. this.normalizeSkinWeights();
  18884. }
  18885. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  18886. constructor: SkinnedMesh,
  18887. isSkinnedMesh: true,
  18888. initBones: function () {
  18889. var bones = [], bone, gbone;
  18890. var i, il;
  18891. if ( this.geometry && this.geometry.bones !== undefined ) {
  18892. // first, create array of 'Bone' objects from geometry data
  18893. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  18894. gbone = this.geometry.bones[ i ];
  18895. // create new 'Bone' object
  18896. bone = new Bone();
  18897. bones.push( bone );
  18898. // apply values
  18899. bone.name = gbone.name;
  18900. bone.position.fromArray( gbone.pos );
  18901. bone.quaternion.fromArray( gbone.rotq );
  18902. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  18903. }
  18904. // second, create bone hierarchy
  18905. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  18906. gbone = this.geometry.bones[ i ];
  18907. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  18908. // subsequent bones in the hierarchy
  18909. bones[ gbone.parent ].add( bones[ i ] );
  18910. } else {
  18911. // topmost bone, immediate child of the skinned mesh
  18912. this.add( bones[ i ] );
  18913. }
  18914. }
  18915. }
  18916. // now the bones are part of the scene graph and children of the skinned mesh.
  18917. // let's update the corresponding matrices
  18918. this.updateMatrixWorld( true );
  18919. return bones;
  18920. },
  18921. bind: function ( skeleton, bindMatrix ) {
  18922. this.skeleton = skeleton;
  18923. if ( bindMatrix === undefined ) {
  18924. this.updateMatrixWorld( true );
  18925. this.skeleton.calculateInverses();
  18926. bindMatrix = this.matrixWorld;
  18927. }
  18928. this.bindMatrix.copy( bindMatrix );
  18929. this.bindMatrixInverse.getInverse( bindMatrix );
  18930. },
  18931. pose: function () {
  18932. this.skeleton.pose();
  18933. },
  18934. normalizeSkinWeights: function () {
  18935. var scale, i;
  18936. if ( this.geometry && this.geometry.isGeometry ) {
  18937. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  18938. var sw = this.geometry.skinWeights[ i ];
  18939. scale = 1.0 / sw.manhattanLength();
  18940. if ( scale !== Infinity ) {
  18941. sw.multiplyScalar( scale );
  18942. } else {
  18943. sw.set( 1, 0, 0, 0 ); // do something reasonable
  18944. }
  18945. }
  18946. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  18947. var vec = new Vector4();
  18948. var skinWeight = this.geometry.attributes.skinWeight;
  18949. for ( i = 0; i < skinWeight.count; i ++ ) {
  18950. vec.x = skinWeight.getX( i );
  18951. vec.y = skinWeight.getY( i );
  18952. vec.z = skinWeight.getZ( i );
  18953. vec.w = skinWeight.getW( i );
  18954. scale = 1.0 / vec.manhattanLength();
  18955. if ( scale !== Infinity ) {
  18956. vec.multiplyScalar( scale );
  18957. } else {
  18958. vec.set( 1, 0, 0, 0 ); // do something reasonable
  18959. }
  18960. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  18961. }
  18962. }
  18963. },
  18964. updateMatrixWorld: function ( force ) {
  18965. Mesh.prototype.updateMatrixWorld.call( this, force );
  18966. if ( this.bindMode === 'attached' ) {
  18967. this.bindMatrixInverse.getInverse( this.matrixWorld );
  18968. } else if ( this.bindMode === 'detached' ) {
  18969. this.bindMatrixInverse.getInverse( this.bindMatrix );
  18970. } else {
  18971. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18972. }
  18973. },
  18974. clone: function () {
  18975. return new this.constructor( this.geometry, this.material ).copy( this );
  18976. }
  18977. } );
  18978. /**
  18979. * @author mrdoob / http://mrdoob.com/
  18980. * @author alteredq / http://alteredqualia.com/
  18981. *
  18982. * parameters = {
  18983. * color: <hex>,
  18984. * opacity: <float>,
  18985. *
  18986. * linewidth: <float>,
  18987. * linecap: "round",
  18988. * linejoin: "round"
  18989. * }
  18990. */
  18991. function LineBasicMaterial( parameters ) {
  18992. Material.call( this );
  18993. this.type = 'LineBasicMaterial';
  18994. this.color = new Color( 0xffffff );
  18995. this.linewidth = 1;
  18996. this.linecap = 'round';
  18997. this.linejoin = 'round';
  18998. this.lights = false;
  18999. this.setValues( parameters );
  19000. }
  19001. LineBasicMaterial.prototype = Object.create( Material.prototype );
  19002. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  19003. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  19004. LineBasicMaterial.prototype.copy = function ( source ) {
  19005. Material.prototype.copy.call( this, source );
  19006. this.color.copy( source.color );
  19007. this.linewidth = source.linewidth;
  19008. this.linecap = source.linecap;
  19009. this.linejoin = source.linejoin;
  19010. return this;
  19011. };
  19012. /**
  19013. * @author mrdoob / http://mrdoob.com/
  19014. */
  19015. function Line( geometry, material, mode ) {
  19016. if ( mode === 1 ) {
  19017. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  19018. return new LineSegments( geometry, material );
  19019. }
  19020. Object3D.call( this );
  19021. this.type = 'Line';
  19022. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  19023. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  19024. }
  19025. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19026. constructor: Line,
  19027. isLine: true,
  19028. computeLineDistances: ( function () {
  19029. var start = new Vector3();
  19030. var end = new Vector3();
  19031. return function computeLineDistances() {
  19032. var geometry = this.geometry;
  19033. if ( geometry.isBufferGeometry ) {
  19034. // we assume non-indexed geometry
  19035. if ( geometry.index === null ) {
  19036. var positionAttribute = geometry.attributes.position;
  19037. var lineDistances = [ 0 ];
  19038. for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) {
  19039. start.fromBufferAttribute( positionAttribute, i - 1 );
  19040. end.fromBufferAttribute( positionAttribute, i );
  19041. lineDistances[ i ] = lineDistances[ i - 1 ];
  19042. lineDistances[ i ] += start.distanceTo( end );
  19043. }
  19044. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19045. } else {
  19046. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19047. }
  19048. } else if ( geometry.isGeometry ) {
  19049. var vertices = geometry.vertices;
  19050. var lineDistances = geometry.lineDistances;
  19051. lineDistances[ 0 ] = 0;
  19052. for ( var i = 1, l = vertices.length; i < l; i ++ ) {
  19053. lineDistances[ i ] = lineDistances[ i - 1 ];
  19054. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  19055. }
  19056. }
  19057. return this;
  19058. };
  19059. }() ),
  19060. raycast: ( function () {
  19061. var inverseMatrix = new Matrix4();
  19062. var ray = new Ray();
  19063. var sphere = new Sphere();
  19064. return function raycast( raycaster, intersects ) {
  19065. var precision = raycaster.linePrecision;
  19066. var precisionSq = precision * precision;
  19067. var geometry = this.geometry;
  19068. var matrixWorld = this.matrixWorld;
  19069. // Checking boundingSphere distance to ray
  19070. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19071. sphere.copy( geometry.boundingSphere );
  19072. sphere.applyMatrix4( matrixWorld );
  19073. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  19074. //
  19075. inverseMatrix.getInverse( matrixWorld );
  19076. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  19077. var vStart = new Vector3();
  19078. var vEnd = new Vector3();
  19079. var interSegment = new Vector3();
  19080. var interRay = new Vector3();
  19081. var step = ( this && this.isLineSegments ) ? 2 : 1;
  19082. if ( geometry.isBufferGeometry ) {
  19083. var index = geometry.index;
  19084. var attributes = geometry.attributes;
  19085. var positions = attributes.position.array;
  19086. if ( index !== null ) {
  19087. var indices = index.array;
  19088. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  19089. var a = indices[ i ];
  19090. var b = indices[ i + 1 ];
  19091. vStart.fromArray( positions, a * 3 );
  19092. vEnd.fromArray( positions, b * 3 );
  19093. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19094. if ( distSq > precisionSq ) continue;
  19095. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19096. var distance = raycaster.ray.origin.distanceTo( interRay );
  19097. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19098. intersects.push( {
  19099. distance: distance,
  19100. // What do we want? intersection point on the ray or on the segment??
  19101. // point: raycaster.ray.at( distance ),
  19102. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19103. index: i,
  19104. face: null,
  19105. faceIndex: null,
  19106. object: this
  19107. } );
  19108. }
  19109. } else {
  19110. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  19111. vStart.fromArray( positions, 3 * i );
  19112. vEnd.fromArray( positions, 3 * i + 3 );
  19113. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19114. if ( distSq > precisionSq ) continue;
  19115. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19116. var distance = raycaster.ray.origin.distanceTo( interRay );
  19117. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19118. intersects.push( {
  19119. distance: distance,
  19120. // What do we want? intersection point on the ray or on the segment??
  19121. // point: raycaster.ray.at( distance ),
  19122. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19123. index: i,
  19124. face: null,
  19125. faceIndex: null,
  19126. object: this
  19127. } );
  19128. }
  19129. }
  19130. } else if ( geometry.isGeometry ) {
  19131. var vertices = geometry.vertices;
  19132. var nbVertices = vertices.length;
  19133. for ( var i = 0; i < nbVertices - 1; i += step ) {
  19134. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  19135. if ( distSq > precisionSq ) continue;
  19136. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19137. var distance = raycaster.ray.origin.distanceTo( interRay );
  19138. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19139. intersects.push( {
  19140. distance: distance,
  19141. // What do we want? intersection point on the ray or on the segment??
  19142. // point: raycaster.ray.at( distance ),
  19143. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19144. index: i,
  19145. face: null,
  19146. faceIndex: null,
  19147. object: this
  19148. } );
  19149. }
  19150. }
  19151. };
  19152. }() ),
  19153. clone: function () {
  19154. return new this.constructor( this.geometry, this.material ).copy( this );
  19155. }
  19156. } );
  19157. /**
  19158. * @author mrdoob / http://mrdoob.com/
  19159. */
  19160. function LineSegments( geometry, material ) {
  19161. Line.call( this, geometry, material );
  19162. this.type = 'LineSegments';
  19163. }
  19164. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  19165. constructor: LineSegments,
  19166. isLineSegments: true,
  19167. computeLineDistances: ( function () {
  19168. var start = new Vector3();
  19169. var end = new Vector3();
  19170. return function computeLineDistances() {
  19171. var geometry = this.geometry;
  19172. if ( geometry.isBufferGeometry ) {
  19173. // we assume non-indexed geometry
  19174. if ( geometry.index === null ) {
  19175. var positionAttribute = geometry.attributes.position;
  19176. var lineDistances = [];
  19177. for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  19178. start.fromBufferAttribute( positionAttribute, i );
  19179. end.fromBufferAttribute( positionAttribute, i + 1 );
  19180. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  19181. lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end );
  19182. }
  19183. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19184. } else {
  19185. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19186. }
  19187. } else if ( geometry.isGeometry ) {
  19188. var vertices = geometry.vertices;
  19189. var lineDistances = geometry.lineDistances;
  19190. for ( var i = 0, l = vertices.length; i < l; i += 2 ) {
  19191. start.copy( vertices[ i ] );
  19192. end.copy( vertices[ i + 1 ] );
  19193. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  19194. lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end );
  19195. }
  19196. }
  19197. return this;
  19198. };
  19199. }() )
  19200. } );
  19201. /**
  19202. * @author mgreter / http://github.com/mgreter
  19203. */
  19204. function LineLoop( geometry, material ) {
  19205. Line.call( this, geometry, material );
  19206. this.type = 'LineLoop';
  19207. }
  19208. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  19209. constructor: LineLoop,
  19210. isLineLoop: true,
  19211. } );
  19212. /**
  19213. * @author mrdoob / http://mrdoob.com/
  19214. * @author alteredq / http://alteredqualia.com/
  19215. *
  19216. * parameters = {
  19217. * color: <hex>,
  19218. * opacity: <float>,
  19219. * map: new THREE.Texture( <Image> ),
  19220. *
  19221. * size: <float>,
  19222. * sizeAttenuation: <bool>
  19223. * }
  19224. */
  19225. function PointsMaterial( parameters ) {
  19226. Material.call( this );
  19227. this.type = 'PointsMaterial';
  19228. this.color = new Color( 0xffffff );
  19229. this.map = null;
  19230. this.size = 1;
  19231. this.sizeAttenuation = true;
  19232. this.lights = false;
  19233. this.setValues( parameters );
  19234. }
  19235. PointsMaterial.prototype = Object.create( Material.prototype );
  19236. PointsMaterial.prototype.constructor = PointsMaterial;
  19237. PointsMaterial.prototype.isPointsMaterial = true;
  19238. PointsMaterial.prototype.copy = function ( source ) {
  19239. Material.prototype.copy.call( this, source );
  19240. this.color.copy( source.color );
  19241. this.map = source.map;
  19242. this.size = source.size;
  19243. this.sizeAttenuation = source.sizeAttenuation;
  19244. return this;
  19245. };
  19246. /**
  19247. * @author alteredq / http://alteredqualia.com/
  19248. */
  19249. function Points( geometry, material ) {
  19250. Object3D.call( this );
  19251. this.type = 'Points';
  19252. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  19253. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  19254. }
  19255. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19256. constructor: Points,
  19257. isPoints: true,
  19258. raycast: ( function () {
  19259. var inverseMatrix = new Matrix4();
  19260. var ray = new Ray();
  19261. var sphere = new Sphere();
  19262. return function raycast( raycaster, intersects ) {
  19263. var object = this;
  19264. var geometry = this.geometry;
  19265. var matrixWorld = this.matrixWorld;
  19266. var threshold = raycaster.params.Points.threshold;
  19267. // Checking boundingSphere distance to ray
  19268. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19269. sphere.copy( geometry.boundingSphere );
  19270. sphere.applyMatrix4( matrixWorld );
  19271. sphere.radius += threshold;
  19272. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  19273. //
  19274. inverseMatrix.getInverse( matrixWorld );
  19275. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  19276. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19277. var localThresholdSq = localThreshold * localThreshold;
  19278. var position = new Vector3();
  19279. var intersectPoint = new Vector3();
  19280. function testPoint( point, index ) {
  19281. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  19282. if ( rayPointDistanceSq < localThresholdSq ) {
  19283. ray.closestPointToPoint( point, intersectPoint );
  19284. intersectPoint.applyMatrix4( matrixWorld );
  19285. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  19286. if ( distance < raycaster.near || distance > raycaster.far ) return;
  19287. intersects.push( {
  19288. distance: distance,
  19289. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  19290. point: intersectPoint.clone(),
  19291. index: index,
  19292. face: null,
  19293. object: object
  19294. } );
  19295. }
  19296. }
  19297. if ( geometry.isBufferGeometry ) {
  19298. var index = geometry.index;
  19299. var attributes = geometry.attributes;
  19300. var positions = attributes.position.array;
  19301. if ( index !== null ) {
  19302. var indices = index.array;
  19303. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  19304. var a = indices[ i ];
  19305. position.fromArray( positions, a * 3 );
  19306. testPoint( position, a );
  19307. }
  19308. } else {
  19309. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  19310. position.fromArray( positions, i * 3 );
  19311. testPoint( position, i );
  19312. }
  19313. }
  19314. } else {
  19315. var vertices = geometry.vertices;
  19316. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19317. testPoint( vertices[ i ], i );
  19318. }
  19319. }
  19320. };
  19321. }() ),
  19322. clone: function () {
  19323. return new this.constructor( this.geometry, this.material ).copy( this );
  19324. }
  19325. } );
  19326. /**
  19327. * @author mrdoob / http://mrdoob.com/
  19328. */
  19329. function Group() {
  19330. Object3D.call( this );
  19331. this.type = 'Group';
  19332. }
  19333. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19334. constructor: Group,
  19335. isGroup: true
  19336. } );
  19337. /**
  19338. * @author mrdoob / http://mrdoob.com/
  19339. */
  19340. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19341. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19342. this.generateMipmaps = false;
  19343. }
  19344. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  19345. constructor: VideoTexture,
  19346. isVideoTexture: true,
  19347. update: function () {
  19348. var video = this.image;
  19349. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  19350. this.needsUpdate = true;
  19351. }
  19352. }
  19353. } );
  19354. /**
  19355. * @author alteredq / http://alteredqualia.com/
  19356. */
  19357. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  19358. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  19359. this.image = { width: width, height: height };
  19360. this.mipmaps = mipmaps;
  19361. // no flipping for cube textures
  19362. // (also flipping doesn't work for compressed textures )
  19363. this.flipY = false;
  19364. // can't generate mipmaps for compressed textures
  19365. // mips must be embedded in DDS files
  19366. this.generateMipmaps = false;
  19367. }
  19368. CompressedTexture.prototype = Object.create( Texture.prototype );
  19369. CompressedTexture.prototype.constructor = CompressedTexture;
  19370. CompressedTexture.prototype.isCompressedTexture = true;
  19371. /**
  19372. * @author Matt DesLauriers / @mattdesl
  19373. * @author atix / arthursilber.de
  19374. */
  19375. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  19376. format = format !== undefined ? format : DepthFormat;
  19377. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  19378. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  19379. }
  19380. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  19381. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  19382. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19383. this.image = { width: width, height: height };
  19384. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  19385. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  19386. this.flipY = false;
  19387. this.generateMipmaps = false;
  19388. }
  19389. DepthTexture.prototype = Object.create( Texture.prototype );
  19390. DepthTexture.prototype.constructor = DepthTexture;
  19391. DepthTexture.prototype.isDepthTexture = true;
  19392. /**
  19393. * @author mrdoob / http://mrdoob.com/
  19394. * @author Mugen87 / https://github.com/Mugen87
  19395. */
  19396. function WireframeGeometry( geometry ) {
  19397. BufferGeometry.call( this );
  19398. this.type = 'WireframeGeometry';
  19399. // buffer
  19400. var vertices = [];
  19401. // helper variables
  19402. var i, j, l, o, ol;
  19403. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  19404. var key, keys = [ 'a', 'b', 'c' ];
  19405. var vertex;
  19406. // different logic for Geometry and BufferGeometry
  19407. if ( geometry && geometry.isGeometry ) {
  19408. // create a data structure that contains all edges without duplicates
  19409. var faces = geometry.faces;
  19410. for ( i = 0, l = faces.length; i < l; i ++ ) {
  19411. var face = faces[ i ];
  19412. for ( j = 0; j < 3; j ++ ) {
  19413. edge1 = face[ keys[ j ] ];
  19414. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  19415. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19416. edge[ 1 ] = Math.max( edge1, edge2 );
  19417. key = edge[ 0 ] + ',' + edge[ 1 ];
  19418. if ( edges[ key ] === undefined ) {
  19419. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19420. }
  19421. }
  19422. }
  19423. // generate vertices
  19424. for ( key in edges ) {
  19425. e = edges[ key ];
  19426. vertex = geometry.vertices[ e.index1 ];
  19427. vertices.push( vertex.x, vertex.y, vertex.z );
  19428. vertex = geometry.vertices[ e.index2 ];
  19429. vertices.push( vertex.x, vertex.y, vertex.z );
  19430. }
  19431. } else if ( geometry && geometry.isBufferGeometry ) {
  19432. var position, indices, groups;
  19433. var group, start, count;
  19434. var index1, index2;
  19435. vertex = new Vector3();
  19436. if ( geometry.index !== null ) {
  19437. // indexed BufferGeometry
  19438. position = geometry.attributes.position;
  19439. indices = geometry.index;
  19440. groups = geometry.groups;
  19441. if ( groups.length === 0 ) {
  19442. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  19443. }
  19444. // create a data structure that contains all eges without duplicates
  19445. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  19446. group = groups[ o ];
  19447. start = group.start;
  19448. count = group.count;
  19449. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  19450. for ( j = 0; j < 3; j ++ ) {
  19451. edge1 = indices.getX( i + j );
  19452. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  19453. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19454. edge[ 1 ] = Math.max( edge1, edge2 );
  19455. key = edge[ 0 ] + ',' + edge[ 1 ];
  19456. if ( edges[ key ] === undefined ) {
  19457. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19458. }
  19459. }
  19460. }
  19461. }
  19462. // generate vertices
  19463. for ( key in edges ) {
  19464. e = edges[ key ];
  19465. vertex.fromBufferAttribute( position, e.index1 );
  19466. vertices.push( vertex.x, vertex.y, vertex.z );
  19467. vertex.fromBufferAttribute( position, e.index2 );
  19468. vertices.push( vertex.x, vertex.y, vertex.z );
  19469. }
  19470. } else {
  19471. // non-indexed BufferGeometry
  19472. position = geometry.attributes.position;
  19473. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  19474. for ( j = 0; j < 3; j ++ ) {
  19475. // three edges per triangle, an edge is represented as (index1, index2)
  19476. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  19477. index1 = 3 * i + j;
  19478. vertex.fromBufferAttribute( position, index1 );
  19479. vertices.push( vertex.x, vertex.y, vertex.z );
  19480. index2 = 3 * i + ( ( j + 1 ) % 3 );
  19481. vertex.fromBufferAttribute( position, index2 );
  19482. vertices.push( vertex.x, vertex.y, vertex.z );
  19483. }
  19484. }
  19485. }
  19486. }
  19487. // build geometry
  19488. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19489. }
  19490. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  19491. WireframeGeometry.prototype.constructor = WireframeGeometry;
  19492. /**
  19493. * @author zz85 / https://github.com/zz85
  19494. * @author Mugen87 / https://github.com/Mugen87
  19495. *
  19496. * Parametric Surfaces Geometry
  19497. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19498. */
  19499. // ParametricGeometry
  19500. function ParametricGeometry( func, slices, stacks ) {
  19501. Geometry.call( this );
  19502. this.type = 'ParametricGeometry';
  19503. this.parameters = {
  19504. func: func,
  19505. slices: slices,
  19506. stacks: stacks
  19507. };
  19508. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  19509. this.mergeVertices();
  19510. }
  19511. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  19512. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19513. // ParametricBufferGeometry
  19514. function ParametricBufferGeometry( func, slices, stacks ) {
  19515. BufferGeometry.call( this );
  19516. this.type = 'ParametricBufferGeometry';
  19517. this.parameters = {
  19518. func: func,
  19519. slices: slices,
  19520. stacks: stacks
  19521. };
  19522. // buffers
  19523. var indices = [];
  19524. var vertices = [];
  19525. var normals = [];
  19526. var uvs = [];
  19527. var EPS = 0.00001;
  19528. var normal = new Vector3();
  19529. var p0 = new Vector3(), p1 = new Vector3();
  19530. var pu = new Vector3(), pv = new Vector3();
  19531. var i, j;
  19532. // generate vertices, normals and uvs
  19533. var sliceCount = slices + 1;
  19534. for ( i = 0; i <= stacks; i ++ ) {
  19535. var v = i / stacks;
  19536. for ( j = 0; j <= slices; j ++ ) {
  19537. var u = j / slices;
  19538. // vertex
  19539. func( u, v, p0 );
  19540. vertices.push( p0.x, p0.y, p0.z );
  19541. // normal
  19542. // approximate tangent vectors via finite differences
  19543. if ( u - EPS >= 0 ) {
  19544. func( u - EPS, v, p1 );
  19545. pu.subVectors( p0, p1 );
  19546. } else {
  19547. func( u + EPS, v, p1 );
  19548. pu.subVectors( p1, p0 );
  19549. }
  19550. if ( v - EPS >= 0 ) {
  19551. func( u, v - EPS, p1 );
  19552. pv.subVectors( p0, p1 );
  19553. } else {
  19554. func( u, v + EPS, p1 );
  19555. pv.subVectors( p1, p0 );
  19556. }
  19557. // cross product of tangent vectors returns surface normal
  19558. normal.crossVectors( pu, pv ).normalize();
  19559. normals.push( normal.x, normal.y, normal.z );
  19560. // uv
  19561. uvs.push( u, v );
  19562. }
  19563. }
  19564. // generate indices
  19565. for ( i = 0; i < stacks; i ++ ) {
  19566. for ( j = 0; j < slices; j ++ ) {
  19567. var a = i * sliceCount + j;
  19568. var b = i * sliceCount + j + 1;
  19569. var c = ( i + 1 ) * sliceCount + j + 1;
  19570. var d = ( i + 1 ) * sliceCount + j;
  19571. // faces one and two
  19572. indices.push( a, b, d );
  19573. indices.push( b, c, d );
  19574. }
  19575. }
  19576. // build geometry
  19577. this.setIndex( indices );
  19578. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19579. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19580. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19581. }
  19582. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19583. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19584. /**
  19585. * @author clockworkgeek / https://github.com/clockworkgeek
  19586. * @author timothypratley / https://github.com/timothypratley
  19587. * @author WestLangley / http://github.com/WestLangley
  19588. * @author Mugen87 / https://github.com/Mugen87
  19589. */
  19590. // PolyhedronGeometry
  19591. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  19592. Geometry.call( this );
  19593. this.type = 'PolyhedronGeometry';
  19594. this.parameters = {
  19595. vertices: vertices,
  19596. indices: indices,
  19597. radius: radius,
  19598. detail: detail
  19599. };
  19600. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  19601. this.mergeVertices();
  19602. }
  19603. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  19604. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  19605. // PolyhedronBufferGeometry
  19606. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  19607. BufferGeometry.call( this );
  19608. this.type = 'PolyhedronBufferGeometry';
  19609. this.parameters = {
  19610. vertices: vertices,
  19611. indices: indices,
  19612. radius: radius,
  19613. detail: detail
  19614. };
  19615. radius = radius || 1;
  19616. detail = detail || 0;
  19617. // default buffer data
  19618. var vertexBuffer = [];
  19619. var uvBuffer = [];
  19620. // the subdivision creates the vertex buffer data
  19621. subdivide( detail );
  19622. // all vertices should lie on a conceptual sphere with a given radius
  19623. appplyRadius( radius );
  19624. // finally, create the uv data
  19625. generateUVs();
  19626. // build non-indexed geometry
  19627. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19628. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19629. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19630. if ( detail === 0 ) {
  19631. this.computeVertexNormals(); // flat normals
  19632. } else {
  19633. this.normalizeNormals(); // smooth normals
  19634. }
  19635. // helper functions
  19636. function subdivide( detail ) {
  19637. var a = new Vector3();
  19638. var b = new Vector3();
  19639. var c = new Vector3();
  19640. // iterate over all faces and apply a subdivison with the given detail value
  19641. for ( var i = 0; i < indices.length; i += 3 ) {
  19642. // get the vertices of the face
  19643. getVertexByIndex( indices[ i + 0 ], a );
  19644. getVertexByIndex( indices[ i + 1 ], b );
  19645. getVertexByIndex( indices[ i + 2 ], c );
  19646. // perform subdivision
  19647. subdivideFace( a, b, c, detail );
  19648. }
  19649. }
  19650. function subdivideFace( a, b, c, detail ) {
  19651. var cols = Math.pow( 2, detail );
  19652. // we use this multidimensional array as a data structure for creating the subdivision
  19653. var v = [];
  19654. var i, j;
  19655. // construct all of the vertices for this subdivision
  19656. for ( i = 0; i <= cols; i ++ ) {
  19657. v[ i ] = [];
  19658. var aj = a.clone().lerp( c, i / cols );
  19659. var bj = b.clone().lerp( c, i / cols );
  19660. var rows = cols - i;
  19661. for ( j = 0; j <= rows; j ++ ) {
  19662. if ( j === 0 && i === cols ) {
  19663. v[ i ][ j ] = aj;
  19664. } else {
  19665. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19666. }
  19667. }
  19668. }
  19669. // construct all of the faces
  19670. for ( i = 0; i < cols; i ++ ) {
  19671. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19672. var k = Math.floor( j / 2 );
  19673. if ( j % 2 === 0 ) {
  19674. pushVertex( v[ i ][ k + 1 ] );
  19675. pushVertex( v[ i + 1 ][ k ] );
  19676. pushVertex( v[ i ][ k ] );
  19677. } else {
  19678. pushVertex( v[ i ][ k + 1 ] );
  19679. pushVertex( v[ i + 1 ][ k + 1 ] );
  19680. pushVertex( v[ i + 1 ][ k ] );
  19681. }
  19682. }
  19683. }
  19684. }
  19685. function appplyRadius( radius ) {
  19686. var vertex = new Vector3();
  19687. // iterate over the entire buffer and apply the radius to each vertex
  19688. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19689. vertex.x = vertexBuffer[ i + 0 ];
  19690. vertex.y = vertexBuffer[ i + 1 ];
  19691. vertex.z = vertexBuffer[ i + 2 ];
  19692. vertex.normalize().multiplyScalar( radius );
  19693. vertexBuffer[ i + 0 ] = vertex.x;
  19694. vertexBuffer[ i + 1 ] = vertex.y;
  19695. vertexBuffer[ i + 2 ] = vertex.z;
  19696. }
  19697. }
  19698. function generateUVs() {
  19699. var vertex = new Vector3();
  19700. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19701. vertex.x = vertexBuffer[ i + 0 ];
  19702. vertex.y = vertexBuffer[ i + 1 ];
  19703. vertex.z = vertexBuffer[ i + 2 ];
  19704. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19705. var v = inclination( vertex ) / Math.PI + 0.5;
  19706. uvBuffer.push( u, 1 - v );
  19707. }
  19708. correctUVs();
  19709. correctSeam();
  19710. }
  19711. function correctSeam() {
  19712. // handle case when face straddles the seam, see #3269
  19713. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  19714. // uv data of a single face
  19715. var x0 = uvBuffer[ i + 0 ];
  19716. var x1 = uvBuffer[ i + 2 ];
  19717. var x2 = uvBuffer[ i + 4 ];
  19718. var max = Math.max( x0, x1, x2 );
  19719. var min = Math.min( x0, x1, x2 );
  19720. // 0.9 is somewhat arbitrary
  19721. if ( max > 0.9 && min < 0.1 ) {
  19722. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  19723. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  19724. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  19725. }
  19726. }
  19727. }
  19728. function pushVertex( vertex ) {
  19729. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  19730. }
  19731. function getVertexByIndex( index, vertex ) {
  19732. var stride = index * 3;
  19733. vertex.x = vertices[ stride + 0 ];
  19734. vertex.y = vertices[ stride + 1 ];
  19735. vertex.z = vertices[ stride + 2 ];
  19736. }
  19737. function correctUVs() {
  19738. var a = new Vector3();
  19739. var b = new Vector3();
  19740. var c = new Vector3();
  19741. var centroid = new Vector3();
  19742. var uvA = new Vector2();
  19743. var uvB = new Vector2();
  19744. var uvC = new Vector2();
  19745. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  19746. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  19747. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  19748. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  19749. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  19750. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  19751. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  19752. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  19753. var azi = azimuth( centroid );
  19754. correctUV( uvA, j + 0, a, azi );
  19755. correctUV( uvB, j + 2, b, azi );
  19756. correctUV( uvC, j + 4, c, azi );
  19757. }
  19758. }
  19759. function correctUV( uv, stride, vector, azimuth ) {
  19760. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  19761. uvBuffer[ stride ] = uv.x - 1;
  19762. }
  19763. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  19764. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  19765. }
  19766. }
  19767. // Angle around the Y axis, counter-clockwise when looking from above.
  19768. function azimuth( vector ) {
  19769. return Math.atan2( vector.z, - vector.x );
  19770. }
  19771. // Angle above the XZ plane.
  19772. function inclination( vector ) {
  19773. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19774. }
  19775. }
  19776. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19777. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  19778. /**
  19779. * @author timothypratley / https://github.com/timothypratley
  19780. * @author Mugen87 / https://github.com/Mugen87
  19781. */
  19782. // TetrahedronGeometry
  19783. function TetrahedronGeometry( radius, detail ) {
  19784. Geometry.call( this );
  19785. this.type = 'TetrahedronGeometry';
  19786. this.parameters = {
  19787. radius: radius,
  19788. detail: detail
  19789. };
  19790. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  19791. this.mergeVertices();
  19792. }
  19793. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  19794. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  19795. // TetrahedronBufferGeometry
  19796. function TetrahedronBufferGeometry( radius, detail ) {
  19797. var vertices = [
  19798. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  19799. ];
  19800. var indices = [
  19801. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19802. ];
  19803. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19804. this.type = 'TetrahedronBufferGeometry';
  19805. this.parameters = {
  19806. radius: radius,
  19807. detail: detail
  19808. };
  19809. }
  19810. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19811. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  19812. /**
  19813. * @author timothypratley / https://github.com/timothypratley
  19814. * @author Mugen87 / https://github.com/Mugen87
  19815. */
  19816. // OctahedronGeometry
  19817. function OctahedronGeometry( radius, detail ) {
  19818. Geometry.call( this );
  19819. this.type = 'OctahedronGeometry';
  19820. this.parameters = {
  19821. radius: radius,
  19822. detail: detail
  19823. };
  19824. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  19825. this.mergeVertices();
  19826. }
  19827. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  19828. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  19829. // OctahedronBufferGeometry
  19830. function OctahedronBufferGeometry( radius, detail ) {
  19831. var vertices = [
  19832. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  19833. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  19834. ];
  19835. var indices = [
  19836. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  19837. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  19838. 1, 3, 4, 1, 4, 2
  19839. ];
  19840. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19841. this.type = 'OctahedronBufferGeometry';
  19842. this.parameters = {
  19843. radius: radius,
  19844. detail: detail
  19845. };
  19846. }
  19847. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19848. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  19849. /**
  19850. * @author timothypratley / https://github.com/timothypratley
  19851. * @author Mugen87 / https://github.com/Mugen87
  19852. */
  19853. // IcosahedronGeometry
  19854. function IcosahedronGeometry( radius, detail ) {
  19855. Geometry.call( this );
  19856. this.type = 'IcosahedronGeometry';
  19857. this.parameters = {
  19858. radius: radius,
  19859. detail: detail
  19860. };
  19861. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  19862. this.mergeVertices();
  19863. }
  19864. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  19865. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  19866. // IcosahedronBufferGeometry
  19867. function IcosahedronBufferGeometry( radius, detail ) {
  19868. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19869. var vertices = [
  19870. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19871. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19872. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19873. ];
  19874. var indices = [
  19875. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19876. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19877. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19878. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19879. ];
  19880. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19881. this.type = 'IcosahedronBufferGeometry';
  19882. this.parameters = {
  19883. radius: radius,
  19884. detail: detail
  19885. };
  19886. }
  19887. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19888. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  19889. /**
  19890. * @author Abe Pazos / https://hamoid.com
  19891. * @author Mugen87 / https://github.com/Mugen87
  19892. */
  19893. // DodecahedronGeometry
  19894. function DodecahedronGeometry( radius, detail ) {
  19895. Geometry.call( this );
  19896. this.type = 'DodecahedronGeometry';
  19897. this.parameters = {
  19898. radius: radius,
  19899. detail: detail
  19900. };
  19901. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  19902. this.mergeVertices();
  19903. }
  19904. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  19905. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  19906. // DodecahedronBufferGeometry
  19907. function DodecahedronBufferGeometry( radius, detail ) {
  19908. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19909. var r = 1 / t;
  19910. var vertices = [
  19911. // (±1, ±1, ±1)
  19912. - 1, - 1, - 1, - 1, - 1, 1,
  19913. - 1, 1, - 1, - 1, 1, 1,
  19914. 1, - 1, - 1, 1, - 1, 1,
  19915. 1, 1, - 1, 1, 1, 1,
  19916. // (0, ±1/φ, ±φ)
  19917. 0, - r, - t, 0, - r, t,
  19918. 0, r, - t, 0, r, t,
  19919. // (±1/φ, ±φ, 0)
  19920. - r, - t, 0, - r, t, 0,
  19921. r, - t, 0, r, t, 0,
  19922. // (±φ, 0, ±1/φ)
  19923. - t, 0, - r, t, 0, - r,
  19924. - t, 0, r, t, 0, r
  19925. ];
  19926. var indices = [
  19927. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19928. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19929. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19930. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19931. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19932. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19933. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19934. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19935. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19936. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19937. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19938. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19939. ];
  19940. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19941. this.type = 'DodecahedronBufferGeometry';
  19942. this.parameters = {
  19943. radius: radius,
  19944. detail: detail
  19945. };
  19946. }
  19947. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19948. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  19949. /**
  19950. * @author oosmoxiecode / https://github.com/oosmoxiecode
  19951. * @author WestLangley / https://github.com/WestLangley
  19952. * @author zz85 / https://github.com/zz85
  19953. * @author miningold / https://github.com/miningold
  19954. * @author jonobr1 / https://github.com/jonobr1
  19955. * @author Mugen87 / https://github.com/Mugen87
  19956. *
  19957. */
  19958. // TubeGeometry
  19959. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  19960. Geometry.call( this );
  19961. this.type = 'TubeGeometry';
  19962. this.parameters = {
  19963. path: path,
  19964. tubularSegments: tubularSegments,
  19965. radius: radius,
  19966. radialSegments: radialSegments,
  19967. closed: closed
  19968. };
  19969. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  19970. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  19971. // expose internals
  19972. this.tangents = bufferGeometry.tangents;
  19973. this.normals = bufferGeometry.normals;
  19974. this.binormals = bufferGeometry.binormals;
  19975. // create geometry
  19976. this.fromBufferGeometry( bufferGeometry );
  19977. this.mergeVertices();
  19978. }
  19979. TubeGeometry.prototype = Object.create( Geometry.prototype );
  19980. TubeGeometry.prototype.constructor = TubeGeometry;
  19981. // TubeBufferGeometry
  19982. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  19983. BufferGeometry.call( this );
  19984. this.type = 'TubeBufferGeometry';
  19985. this.parameters = {
  19986. path: path,
  19987. tubularSegments: tubularSegments,
  19988. radius: radius,
  19989. radialSegments: radialSegments,
  19990. closed: closed
  19991. };
  19992. tubularSegments = tubularSegments || 64;
  19993. radius = radius || 1;
  19994. radialSegments = radialSegments || 8;
  19995. closed = closed || false;
  19996. var frames = path.computeFrenetFrames( tubularSegments, closed );
  19997. // expose internals
  19998. this.tangents = frames.tangents;
  19999. this.normals = frames.normals;
  20000. this.binormals = frames.binormals;
  20001. // helper variables
  20002. var vertex = new Vector3();
  20003. var normal = new Vector3();
  20004. var uv = new Vector2();
  20005. var P = new Vector3();
  20006. var i, j;
  20007. // buffer
  20008. var vertices = [];
  20009. var normals = [];
  20010. var uvs = [];
  20011. var indices = [];
  20012. // create buffer data
  20013. generateBufferData();
  20014. // build geometry
  20015. this.setIndex( indices );
  20016. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20017. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20018. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20019. // functions
  20020. function generateBufferData() {
  20021. for ( i = 0; i < tubularSegments; i ++ ) {
  20022. generateSegment( i );
  20023. }
  20024. // if the geometry is not closed, generate the last row of vertices and normals
  20025. // at the regular position on the given path
  20026. //
  20027. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20028. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  20029. // uvs are generated in a separate function.
  20030. // this makes it easy compute correct values for closed geometries
  20031. generateUVs();
  20032. // finally create faces
  20033. generateIndices();
  20034. }
  20035. function generateSegment( i ) {
  20036. // we use getPointAt to sample evenly distributed points from the given path
  20037. P = path.getPointAt( i / tubularSegments, P );
  20038. // retrieve corresponding normal and binormal
  20039. var N = frames.normals[ i ];
  20040. var B = frames.binormals[ i ];
  20041. // generate normals and vertices for the current segment
  20042. for ( j = 0; j <= radialSegments; j ++ ) {
  20043. var v = j / radialSegments * Math.PI * 2;
  20044. var sin = Math.sin( v );
  20045. var cos = - Math.cos( v );
  20046. // normal
  20047. normal.x = ( cos * N.x + sin * B.x );
  20048. normal.y = ( cos * N.y + sin * B.y );
  20049. normal.z = ( cos * N.z + sin * B.z );
  20050. normal.normalize();
  20051. normals.push( normal.x, normal.y, normal.z );
  20052. // vertex
  20053. vertex.x = P.x + radius * normal.x;
  20054. vertex.y = P.y + radius * normal.y;
  20055. vertex.z = P.z + radius * normal.z;
  20056. vertices.push( vertex.x, vertex.y, vertex.z );
  20057. }
  20058. }
  20059. function generateIndices() {
  20060. for ( j = 1; j <= tubularSegments; j ++ ) {
  20061. for ( i = 1; i <= radialSegments; i ++ ) {
  20062. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20063. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  20064. var c = ( radialSegments + 1 ) * j + i;
  20065. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20066. // faces
  20067. indices.push( a, b, d );
  20068. indices.push( b, c, d );
  20069. }
  20070. }
  20071. }
  20072. function generateUVs() {
  20073. for ( i = 0; i <= tubularSegments; i ++ ) {
  20074. for ( j = 0; j <= radialSegments; j ++ ) {
  20075. uv.x = i / tubularSegments;
  20076. uv.y = j / radialSegments;
  20077. uvs.push( uv.x, uv.y );
  20078. }
  20079. }
  20080. }
  20081. }
  20082. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20083. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  20084. /**
  20085. * @author oosmoxiecode
  20086. * @author Mugen87 / https://github.com/Mugen87
  20087. *
  20088. * based on http://www.blackpawn.com/texts/pqtorus/
  20089. */
  20090. // TorusKnotGeometry
  20091. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  20092. Geometry.call( this );
  20093. this.type = 'TorusKnotGeometry';
  20094. this.parameters = {
  20095. radius: radius,
  20096. tube: tube,
  20097. tubularSegments: tubularSegments,
  20098. radialSegments: radialSegments,
  20099. p: p,
  20100. q: q
  20101. };
  20102. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  20103. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  20104. this.mergeVertices();
  20105. }
  20106. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  20107. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  20108. // TorusKnotBufferGeometry
  20109. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  20110. BufferGeometry.call( this );
  20111. this.type = 'TorusKnotBufferGeometry';
  20112. this.parameters = {
  20113. radius: radius,
  20114. tube: tube,
  20115. tubularSegments: tubularSegments,
  20116. radialSegments: radialSegments,
  20117. p: p,
  20118. q: q
  20119. };
  20120. radius = radius || 1;
  20121. tube = tube || 0.4;
  20122. tubularSegments = Math.floor( tubularSegments ) || 64;
  20123. radialSegments = Math.floor( radialSegments ) || 8;
  20124. p = p || 2;
  20125. q = q || 3;
  20126. // buffers
  20127. var indices = [];
  20128. var vertices = [];
  20129. var normals = [];
  20130. var uvs = [];
  20131. // helper variables
  20132. var i, j;
  20133. var vertex = new Vector3();
  20134. var normal = new Vector3();
  20135. var P1 = new Vector3();
  20136. var P2 = new Vector3();
  20137. var B = new Vector3();
  20138. var T = new Vector3();
  20139. var N = new Vector3();
  20140. // generate vertices, normals and uvs
  20141. for ( i = 0; i <= tubularSegments; ++ i ) {
  20142. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20143. var u = i / tubularSegments * p * Math.PI * 2;
  20144. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20145. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20146. calculatePositionOnCurve( u, p, q, radius, P1 );
  20147. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20148. // calculate orthonormal basis
  20149. T.subVectors( P2, P1 );
  20150. N.addVectors( P2, P1 );
  20151. B.crossVectors( T, N );
  20152. N.crossVectors( B, T );
  20153. // normalize B, N. T can be ignored, we don't use it
  20154. B.normalize();
  20155. N.normalize();
  20156. for ( j = 0; j <= radialSegments; ++ j ) {
  20157. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20158. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20159. var v = j / radialSegments * Math.PI * 2;
  20160. var cx = - tube * Math.cos( v );
  20161. var cy = tube * Math.sin( v );
  20162. // now calculate the final vertex position.
  20163. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20164. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20165. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20166. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20167. vertices.push( vertex.x, vertex.y, vertex.z );
  20168. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20169. normal.subVectors( vertex, P1 ).normalize();
  20170. normals.push( normal.x, normal.y, normal.z );
  20171. // uv
  20172. uvs.push( i / tubularSegments );
  20173. uvs.push( j / radialSegments );
  20174. }
  20175. }
  20176. // generate indices
  20177. for ( j = 1; j <= tubularSegments; j ++ ) {
  20178. for ( i = 1; i <= radialSegments; i ++ ) {
  20179. // indices
  20180. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20181. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  20182. var c = ( radialSegments + 1 ) * j + i;
  20183. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20184. // faces
  20185. indices.push( a, b, d );
  20186. indices.push( b, c, d );
  20187. }
  20188. }
  20189. // build geometry
  20190. this.setIndex( indices );
  20191. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20192. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20193. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20194. // this function calculates the current position on the torus curve
  20195. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20196. var cu = Math.cos( u );
  20197. var su = Math.sin( u );
  20198. var quOverP = q / p * u;
  20199. var cs = Math.cos( quOverP );
  20200. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20201. position.y = radius * ( 2 + cs ) * su * 0.5;
  20202. position.z = radius * Math.sin( quOverP ) * 0.5;
  20203. }
  20204. }
  20205. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20206. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  20207. /**
  20208. * @author oosmoxiecode
  20209. * @author mrdoob / http://mrdoob.com/
  20210. * @author Mugen87 / https://github.com/Mugen87
  20211. */
  20212. // TorusGeometry
  20213. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  20214. Geometry.call( this );
  20215. this.type = 'TorusGeometry';
  20216. this.parameters = {
  20217. radius: radius,
  20218. tube: tube,
  20219. radialSegments: radialSegments,
  20220. tubularSegments: tubularSegments,
  20221. arc: arc
  20222. };
  20223. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  20224. this.mergeVertices();
  20225. }
  20226. TorusGeometry.prototype = Object.create( Geometry.prototype );
  20227. TorusGeometry.prototype.constructor = TorusGeometry;
  20228. // TorusBufferGeometry
  20229. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  20230. BufferGeometry.call( this );
  20231. this.type = 'TorusBufferGeometry';
  20232. this.parameters = {
  20233. radius: radius,
  20234. tube: tube,
  20235. radialSegments: radialSegments,
  20236. tubularSegments: tubularSegments,
  20237. arc: arc
  20238. };
  20239. radius = radius || 1;
  20240. tube = tube || 0.4;
  20241. radialSegments = Math.floor( radialSegments ) || 8;
  20242. tubularSegments = Math.floor( tubularSegments ) || 6;
  20243. arc = arc || Math.PI * 2;
  20244. // buffers
  20245. var indices = [];
  20246. var vertices = [];
  20247. var normals = [];
  20248. var uvs = [];
  20249. // helper variables
  20250. var center = new Vector3();
  20251. var vertex = new Vector3();
  20252. var normal = new Vector3();
  20253. var j, i;
  20254. // generate vertices, normals and uvs
  20255. for ( j = 0; j <= radialSegments; j ++ ) {
  20256. for ( i = 0; i <= tubularSegments; i ++ ) {
  20257. var u = i / tubularSegments * arc;
  20258. var v = j / radialSegments * Math.PI * 2;
  20259. // vertex
  20260. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20261. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20262. vertex.z = tube * Math.sin( v );
  20263. vertices.push( vertex.x, vertex.y, vertex.z );
  20264. // normal
  20265. center.x = radius * Math.cos( u );
  20266. center.y = radius * Math.sin( u );
  20267. normal.subVectors( vertex, center ).normalize();
  20268. normals.push( normal.x, normal.y, normal.z );
  20269. // uv
  20270. uvs.push( i / tubularSegments );
  20271. uvs.push( j / radialSegments );
  20272. }
  20273. }
  20274. // generate indices
  20275. for ( j = 1; j <= radialSegments; j ++ ) {
  20276. for ( i = 1; i <= tubularSegments; i ++ ) {
  20277. // indices
  20278. var a = ( tubularSegments + 1 ) * j + i - 1;
  20279. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20280. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20281. var d = ( tubularSegments + 1 ) * j + i;
  20282. // faces
  20283. indices.push( a, b, d );
  20284. indices.push( b, c, d );
  20285. }
  20286. }
  20287. // build geometry
  20288. this.setIndex( indices );
  20289. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20290. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20291. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20292. }
  20293. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20294. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  20295. /**
  20296. * @author Mugen87 / https://github.com/Mugen87
  20297. * Port from https://github.com/mapbox/earcut (v2.1.2)
  20298. */
  20299. var Earcut = {
  20300. triangulate: function ( data, holeIndices, dim ) {
  20301. dim = dim || 2;
  20302. var hasHoles = holeIndices && holeIndices.length,
  20303. outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
  20304. outerNode = linkedList( data, 0, outerLen, dim, true ),
  20305. triangles = [];
  20306. if ( ! outerNode ) return triangles;
  20307. var minX, minY, maxX, maxY, x, y, invSize;
  20308. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20309. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20310. if ( data.length > 80 * dim ) {
  20311. minX = maxX = data[ 0 ];
  20312. minY = maxY = data[ 1 ];
  20313. for ( var i = dim; i < outerLen; i += dim ) {
  20314. x = data[ i ];
  20315. y = data[ i + 1 ];
  20316. if ( x < minX ) minX = x;
  20317. if ( y < minY ) minY = y;
  20318. if ( x > maxX ) maxX = x;
  20319. if ( y > maxY ) maxY = y;
  20320. }
  20321. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20322. invSize = Math.max( maxX - minX, maxY - minY );
  20323. invSize = invSize !== 0 ? 1 / invSize : 0;
  20324. }
  20325. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  20326. return triangles;
  20327. }
  20328. };
  20329. // create a circular doubly linked list from polygon points in the specified winding order
  20330. function linkedList( data, start, end, dim, clockwise ) {
  20331. var i, last;
  20332. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20333. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20334. } else {
  20335. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20336. }
  20337. if ( last && equals( last, last.next ) ) {
  20338. removeNode( last );
  20339. last = last.next;
  20340. }
  20341. return last;
  20342. }
  20343. // eliminate colinear or duplicate points
  20344. function filterPoints( start, end ) {
  20345. if ( ! start ) return start;
  20346. if ( ! end ) end = start;
  20347. var p = start, again;
  20348. do {
  20349. again = false;
  20350. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20351. removeNode( p );
  20352. p = end = p.prev;
  20353. if ( p === p.next ) break;
  20354. again = true;
  20355. } else {
  20356. p = p.next;
  20357. }
  20358. } while ( again || p !== end );
  20359. return end;
  20360. }
  20361. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20362. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20363. if ( ! ear ) return;
  20364. // interlink polygon nodes in z-order
  20365. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20366. var stop = ear, prev, next;
  20367. // iterate through ears, slicing them one by one
  20368. while ( ear.prev !== ear.next ) {
  20369. prev = ear.prev;
  20370. next = ear.next;
  20371. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20372. // cut off the triangle
  20373. triangles.push( prev.i / dim );
  20374. triangles.push( ear.i / dim );
  20375. triangles.push( next.i / dim );
  20376. removeNode( ear );
  20377. // skipping the next vertice leads to less sliver triangles
  20378. ear = next.next;
  20379. stop = next.next;
  20380. continue;
  20381. }
  20382. ear = next;
  20383. // if we looped through the whole remaining polygon and can't find any more ears
  20384. if ( ear === stop ) {
  20385. // try filtering points and slicing again
  20386. if ( ! pass ) {
  20387. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20388. // if this didn't work, try curing all small self-intersections locally
  20389. } else if ( pass === 1 ) {
  20390. ear = cureLocalIntersections( ear, triangles, dim );
  20391. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20392. // as a last resort, try splitting the remaining polygon into two
  20393. } else if ( pass === 2 ) {
  20394. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20395. }
  20396. break;
  20397. }
  20398. }
  20399. }
  20400. // check whether a polygon node forms a valid ear with adjacent nodes
  20401. function isEar( ear ) {
  20402. var a = ear.prev,
  20403. b = ear,
  20404. c = ear.next;
  20405. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20406. // now make sure we don't have other points inside the potential ear
  20407. var p = ear.next.next;
  20408. while ( p !== ear.prev ) {
  20409. 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 ) {
  20410. return false;
  20411. }
  20412. p = p.next;
  20413. }
  20414. return true;
  20415. }
  20416. function isEarHashed( ear, minX, minY, invSize ) {
  20417. var a = ear.prev,
  20418. b = ear,
  20419. c = ear.next;
  20420. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20421. // triangle bbox; min & max are calculated like this for speed
  20422. var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  20423. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  20424. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  20425. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  20426. // z-order range for the current triangle bbox;
  20427. var minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  20428. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  20429. // first look for points inside the triangle in increasing z-order
  20430. var p = ear.nextZ;
  20431. while ( p && p.z <= maxZ ) {
  20432. if ( p !== ear.prev && p !== ear.next &&
  20433. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20434. area( p.prev, p, p.next ) >= 0 ) return false;
  20435. p = p.nextZ;
  20436. }
  20437. // then look for points in decreasing z-order
  20438. p = ear.prevZ;
  20439. while ( p && p.z >= minZ ) {
  20440. if ( p !== ear.prev && p !== ear.next &&
  20441. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20442. area( p.prev, p, p.next ) >= 0 ) return false;
  20443. p = p.prevZ;
  20444. }
  20445. return true;
  20446. }
  20447. // go through all polygon nodes and cure small local self-intersections
  20448. function cureLocalIntersections( start, triangles, dim ) {
  20449. var p = start;
  20450. do {
  20451. var a = p.prev, b = p.next.next;
  20452. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20453. triangles.push( a.i / dim );
  20454. triangles.push( p.i / dim );
  20455. triangles.push( b.i / dim );
  20456. // remove two nodes involved
  20457. removeNode( p );
  20458. removeNode( p.next );
  20459. p = start = b;
  20460. }
  20461. p = p.next;
  20462. } while ( p !== start );
  20463. return p;
  20464. }
  20465. // try splitting polygon into two and triangulate them independently
  20466. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20467. // look for a valid diagonal that divides the polygon into two
  20468. var a = start;
  20469. do {
  20470. var b = a.next.next;
  20471. while ( b !== a.prev ) {
  20472. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20473. // split the polygon in two by the diagonal
  20474. var c = splitPolygon( a, b );
  20475. // filter colinear points around the cuts
  20476. a = filterPoints( a, a.next );
  20477. c = filterPoints( c, c.next );
  20478. // run earcut on each half
  20479. earcutLinked( a, triangles, dim, minX, minY, invSize );
  20480. earcutLinked( c, triangles, dim, minX, minY, invSize );
  20481. return;
  20482. }
  20483. b = b.next;
  20484. }
  20485. a = a.next;
  20486. } while ( a !== start );
  20487. }
  20488. // link every hole into the outer loop, producing a single-ring polygon without holes
  20489. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20490. var queue = [], i, len, start, end, list;
  20491. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20492. start = holeIndices[ i ] * dim;
  20493. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20494. list = linkedList( data, start, end, dim, false );
  20495. if ( list === list.next ) list.steiner = true;
  20496. queue.push( getLeftmost( list ) );
  20497. }
  20498. queue.sort( compareX );
  20499. // process holes from left to right
  20500. for ( i = 0; i < queue.length; i ++ ) {
  20501. eliminateHole( queue[ i ], outerNode );
  20502. outerNode = filterPoints( outerNode, outerNode.next );
  20503. }
  20504. return outerNode;
  20505. }
  20506. function compareX( a, b ) {
  20507. return a.x - b.x;
  20508. }
  20509. // find a bridge between vertices that connects hole with an outer ring and and link it
  20510. function eliminateHole( hole, outerNode ) {
  20511. outerNode = findHoleBridge( hole, outerNode );
  20512. if ( outerNode ) {
  20513. var b = splitPolygon( outerNode, hole );
  20514. filterPoints( b, b.next );
  20515. }
  20516. }
  20517. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20518. function findHoleBridge( hole, outerNode ) {
  20519. var p = outerNode,
  20520. hx = hole.x,
  20521. hy = hole.y,
  20522. qx = - Infinity,
  20523. m;
  20524. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20525. // segment's endpoint with lesser x will be potential connection point
  20526. do {
  20527. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20528. var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20529. if ( x <= hx && x > qx ) {
  20530. qx = x;
  20531. if ( x === hx ) {
  20532. if ( hy === p.y ) return p;
  20533. if ( hy === p.next.y ) return p.next;
  20534. }
  20535. m = p.x < p.next.x ? p : p.next;
  20536. }
  20537. }
  20538. p = p.next;
  20539. } while ( p !== outerNode );
  20540. if ( ! m ) return null;
  20541. if ( hx === qx ) return m.prev; // hole touches outer segment; pick lower endpoint
  20542. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20543. // if there are no points found, we have a valid connection;
  20544. // otherwise choose the point of the minimum angle with the ray as connection point
  20545. var stop = m,
  20546. mx = m.x,
  20547. my = m.y,
  20548. tanMin = Infinity,
  20549. tan;
  20550. p = m.next;
  20551. while ( p !== stop ) {
  20552. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20553. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20554. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20555. if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) {
  20556. m = p;
  20557. tanMin = tan;
  20558. }
  20559. }
  20560. p = p.next;
  20561. }
  20562. return m;
  20563. }
  20564. // interlink polygon nodes in z-order
  20565. function indexCurve( start, minX, minY, invSize ) {
  20566. var p = start;
  20567. do {
  20568. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20569. p.prevZ = p.prev;
  20570. p.nextZ = p.next;
  20571. p = p.next;
  20572. } while ( p !== start );
  20573. p.prevZ.nextZ = null;
  20574. p.prevZ = null;
  20575. sortLinked( p );
  20576. }
  20577. // Simon Tatham's linked list merge sort algorithm
  20578. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20579. function sortLinked( list ) {
  20580. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  20581. do {
  20582. p = list;
  20583. list = null;
  20584. tail = null;
  20585. numMerges = 0;
  20586. while ( p ) {
  20587. numMerges ++;
  20588. q = p;
  20589. pSize = 0;
  20590. for ( i = 0; i < inSize; i ++ ) {
  20591. pSize ++;
  20592. q = q.nextZ;
  20593. if ( ! q ) break;
  20594. }
  20595. qSize = inSize;
  20596. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20597. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20598. e = p;
  20599. p = p.nextZ;
  20600. pSize --;
  20601. } else {
  20602. e = q;
  20603. q = q.nextZ;
  20604. qSize --;
  20605. }
  20606. if ( tail ) tail.nextZ = e;
  20607. else list = e;
  20608. e.prevZ = tail;
  20609. tail = e;
  20610. }
  20611. p = q;
  20612. }
  20613. tail.nextZ = null;
  20614. inSize *= 2;
  20615. } while ( numMerges > 1 );
  20616. return list;
  20617. }
  20618. // z-order of a point given coords and inverse of the longer side of data bbox
  20619. function zOrder( x, y, minX, minY, invSize ) {
  20620. // coords are transformed into non-negative 15-bit integer range
  20621. x = 32767 * ( x - minX ) * invSize;
  20622. y = 32767 * ( y - minY ) * invSize;
  20623. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20624. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20625. x = ( x | ( x << 2 ) ) & 0x33333333;
  20626. x = ( x | ( x << 1 ) ) & 0x55555555;
  20627. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20628. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20629. y = ( y | ( y << 2 ) ) & 0x33333333;
  20630. y = ( y | ( y << 1 ) ) & 0x55555555;
  20631. return x | ( y << 1 );
  20632. }
  20633. // find the leftmost node of a polygon ring
  20634. function getLeftmost( start ) {
  20635. var p = start, leftmost = start;
  20636. do {
  20637. if ( p.x < leftmost.x ) leftmost = p;
  20638. p = p.next;
  20639. } while ( p !== start );
  20640. return leftmost;
  20641. }
  20642. // check if a point lies within a convex triangle
  20643. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20644. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  20645. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  20646. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  20647. }
  20648. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20649. function isValidDiagonal( a, b ) {
  20650. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) &&
  20651. locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b );
  20652. }
  20653. // signed area of a triangle
  20654. function area( p, q, r ) {
  20655. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20656. }
  20657. // check if two points are equal
  20658. function equals( p1, p2 ) {
  20659. return p1.x === p2.x && p1.y === p2.y;
  20660. }
  20661. // check if two segments intersect
  20662. function intersects( p1, q1, p2, q2 ) {
  20663. if ( ( equals( p1, q1 ) && equals( p2, q2 ) ) ||
  20664. ( equals( p1, q2 ) && equals( p2, q1 ) ) ) return true;
  20665. return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 &&
  20666. area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0;
  20667. }
  20668. // check if a polygon diagonal intersects any polygon segments
  20669. function intersectsPolygon( a, b ) {
  20670. var p = a;
  20671. do {
  20672. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20673. intersects( p, p.next, a, b ) ) {
  20674. return true;
  20675. }
  20676. p = p.next;
  20677. } while ( p !== a );
  20678. return false;
  20679. }
  20680. // check if a polygon diagonal is locally inside the polygon
  20681. function locallyInside( a, b ) {
  20682. return area( a.prev, a, a.next ) < 0 ?
  20683. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20684. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20685. }
  20686. // check if the middle point of a polygon diagonal is inside the polygon
  20687. function middleInside( a, b ) {
  20688. var p = a,
  20689. inside = false,
  20690. px = ( a.x + b.x ) / 2,
  20691. py = ( a.y + b.y ) / 2;
  20692. do {
  20693. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20694. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) {
  20695. inside = ! inside;
  20696. }
  20697. p = p.next;
  20698. } while ( p !== a );
  20699. return inside;
  20700. }
  20701. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20702. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20703. function splitPolygon( a, b ) {
  20704. var a2 = new Node( a.i, a.x, a.y ),
  20705. b2 = new Node( b.i, b.x, b.y ),
  20706. an = a.next,
  20707. bp = b.prev;
  20708. a.next = b;
  20709. b.prev = a;
  20710. a2.next = an;
  20711. an.prev = a2;
  20712. b2.next = a2;
  20713. a2.prev = b2;
  20714. bp.next = b2;
  20715. b2.prev = bp;
  20716. return b2;
  20717. }
  20718. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20719. function insertNode( i, x, y, last ) {
  20720. var p = new Node( i, x, y );
  20721. if ( ! last ) {
  20722. p.prev = p;
  20723. p.next = p;
  20724. } else {
  20725. p.next = last.next;
  20726. p.prev = last;
  20727. last.next.prev = p;
  20728. last.next = p;
  20729. }
  20730. return p;
  20731. }
  20732. function removeNode( p ) {
  20733. p.next.prev = p.prev;
  20734. p.prev.next = p.next;
  20735. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20736. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20737. }
  20738. function Node( i, x, y ) {
  20739. // vertice index in coordinates array
  20740. this.i = i;
  20741. // vertex coordinates
  20742. this.x = x;
  20743. this.y = y;
  20744. // previous and next vertice nodes in a polygon ring
  20745. this.prev = null;
  20746. this.next = null;
  20747. // z-order curve value
  20748. this.z = null;
  20749. // previous and next nodes in z-order
  20750. this.prevZ = null;
  20751. this.nextZ = null;
  20752. // indicates whether this is a steiner point
  20753. this.steiner = false;
  20754. }
  20755. function signedArea( data, start, end, dim ) {
  20756. var sum = 0;
  20757. for ( var i = start, j = end - dim; i < end; i += dim ) {
  20758. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20759. j = i;
  20760. }
  20761. return sum;
  20762. }
  20763. /**
  20764. * @author zz85 / http://www.lab4games.net/zz85/blog
  20765. */
  20766. var ShapeUtils = {
  20767. // calculate area of the contour polygon
  20768. area: function ( contour ) {
  20769. var n = contour.length;
  20770. var a = 0.0;
  20771. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  20772. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20773. }
  20774. return a * 0.5;
  20775. },
  20776. isClockWise: function ( pts ) {
  20777. return ShapeUtils.area( pts ) < 0;
  20778. },
  20779. triangulateShape: function ( contour, holes ) {
  20780. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20781. var holeIndices = []; // array of hole indices
  20782. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20783. removeDupEndPts( contour );
  20784. addContour( vertices, contour );
  20785. //
  20786. var holeIndex = contour.length;
  20787. holes.forEach( removeDupEndPts );
  20788. for ( var i = 0; i < holes.length; i ++ ) {
  20789. holeIndices.push( holeIndex );
  20790. holeIndex += holes[ i ].length;
  20791. addContour( vertices, holes[ i ] );
  20792. }
  20793. //
  20794. var triangles = Earcut.triangulate( vertices, holeIndices );
  20795. //
  20796. for ( var i = 0; i < triangles.length; i += 3 ) {
  20797. faces.push( triangles.slice( i, i + 3 ) );
  20798. }
  20799. return faces;
  20800. }
  20801. };
  20802. function removeDupEndPts( points ) {
  20803. var l = points.length;
  20804. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20805. points.pop();
  20806. }
  20807. }
  20808. function addContour( vertices, contour ) {
  20809. for ( var i = 0; i < contour.length; i ++ ) {
  20810. vertices.push( contour[ i ].x );
  20811. vertices.push( contour[ i ].y );
  20812. }
  20813. }
  20814. /**
  20815. * @author zz85 / http://www.lab4games.net/zz85/blog
  20816. *
  20817. * Creates extruded geometry from a path shape.
  20818. *
  20819. * parameters = {
  20820. *
  20821. * curveSegments: <int>, // number of points on the curves
  20822. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20823. * amount: <int>, // Depth to extrude the shape
  20824. *
  20825. * bevelEnabled: <bool>, // turn on bevel
  20826. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20827. * bevelSize: <float>, // how far from shape outline is bevel
  20828. * bevelSegments: <int>, // number of bevel layers
  20829. *
  20830. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20831. *
  20832. * UVGenerator: <Object> // object that provides UV generator functions
  20833. *
  20834. * }
  20835. */
  20836. // ExtrudeGeometry
  20837. function ExtrudeGeometry( shapes, options ) {
  20838. Geometry.call( this );
  20839. this.type = 'ExtrudeGeometry';
  20840. this.parameters = {
  20841. shapes: shapes,
  20842. options: options
  20843. };
  20844. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  20845. this.mergeVertices();
  20846. }
  20847. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  20848. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  20849. // ExtrudeBufferGeometry
  20850. function ExtrudeBufferGeometry( shapes, options ) {
  20851. BufferGeometry.call( this );
  20852. this.type = 'ExtrudeBufferGeometry';
  20853. this.parameters = {
  20854. shapes: shapes,
  20855. options: options
  20856. };
  20857. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20858. var scope = this;
  20859. var verticesArray = [];
  20860. var uvArray = [];
  20861. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  20862. var shape = shapes[ i ];
  20863. addShape( shape, options );
  20864. }
  20865. // build geometry
  20866. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  20867. this.addAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  20868. this.computeVertexNormals();
  20869. // functions
  20870. function addShape( shape ) {
  20871. var placeholder = [];
  20872. // options
  20873. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20874. var steps = options.steps !== undefined ? options.steps : 1;
  20875. var amount = options.amount !== undefined ? options.amount : 100;
  20876. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20877. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  20878. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  20879. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20880. var extrudePath = options.extrudePath;
  20881. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  20882. //
  20883. var extrudePts, extrudeByPath = false;
  20884. var splineTube, binormal, normal, position2;
  20885. if ( extrudePath ) {
  20886. extrudePts = extrudePath.getSpacedPoints( steps );
  20887. extrudeByPath = true;
  20888. bevelEnabled = false; // bevels not supported for path extrusion
  20889. // SETUP TNB variables
  20890. // TODO1 - have a .isClosed in spline?
  20891. splineTube = extrudePath.computeFrenetFrames( steps, false );
  20892. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20893. binormal = new Vector3();
  20894. normal = new Vector3();
  20895. position2 = new Vector3();
  20896. }
  20897. // Safeguards if bevels are not enabled
  20898. if ( ! bevelEnabled ) {
  20899. bevelSegments = 0;
  20900. bevelThickness = 0;
  20901. bevelSize = 0;
  20902. }
  20903. // Variables initialization
  20904. var ahole, h, hl; // looping of holes
  20905. var shapePoints = shape.extractPoints( curveSegments );
  20906. var vertices = shapePoints.shape;
  20907. var holes = shapePoints.holes;
  20908. var reverse = ! ShapeUtils.isClockWise( vertices );
  20909. if ( reverse ) {
  20910. vertices = vertices.reverse();
  20911. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20912. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20913. ahole = holes[ h ];
  20914. if ( ShapeUtils.isClockWise( ahole ) ) {
  20915. holes[ h ] = ahole.reverse();
  20916. }
  20917. }
  20918. }
  20919. var faces = ShapeUtils.triangulateShape( vertices, holes );
  20920. /* Vertices */
  20921. var contour = vertices; // vertices has all points but contour has only points of circumference
  20922. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20923. ahole = holes[ h ];
  20924. vertices = vertices.concat( ahole );
  20925. }
  20926. function scalePt2( pt, vec, size ) {
  20927. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  20928. return vec.clone().multiplyScalar( size ).add( pt );
  20929. }
  20930. var b, bs, t, z,
  20931. vert, vlen = vertices.length,
  20932. face, flen = faces.length;
  20933. // Find directions for point movement
  20934. function getBevelVec( inPt, inPrev, inNext ) {
  20935. // computes for inPt the corresponding point inPt' on a new contour
  20936. // shifted by 1 unit (length of normalized vector) to the left
  20937. // if we walk along contour clockwise, this new contour is outside the old one
  20938. //
  20939. // inPt' is the intersection of the two lines parallel to the two
  20940. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20941. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20942. // good reading for geometry algorithms (here: line-line intersection)
  20943. // http://geomalgorithms.com/a05-_intersect-1.html
  20944. var v_prev_x = inPt.x - inPrev.x,
  20945. v_prev_y = inPt.y - inPrev.y;
  20946. var v_next_x = inNext.x - inPt.x,
  20947. v_next_y = inNext.y - inPt.y;
  20948. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20949. // check for collinear edges
  20950. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20951. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20952. // not collinear
  20953. // length of vectors for normalizing
  20954. var v_prev_len = Math.sqrt( v_prev_lensq );
  20955. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20956. // shift adjacent points by unit vectors to the left
  20957. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20958. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20959. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20960. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20961. // scaling factor for v_prev to intersection point
  20962. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20963. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20964. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20965. // vector from inPt to intersection point
  20966. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20967. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20968. // Don't normalize!, otherwise sharp corners become ugly
  20969. // but prevent crazy spikes
  20970. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20971. if ( v_trans_lensq <= 2 ) {
  20972. return new Vector2( v_trans_x, v_trans_y );
  20973. } else {
  20974. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20975. }
  20976. } else {
  20977. // handle special case of collinear edges
  20978. var direction_eq = false; // assumes: opposite
  20979. if ( v_prev_x > Number.EPSILON ) {
  20980. if ( v_next_x > Number.EPSILON ) {
  20981. direction_eq = true;
  20982. }
  20983. } else {
  20984. if ( v_prev_x < - Number.EPSILON ) {
  20985. if ( v_next_x < - Number.EPSILON ) {
  20986. direction_eq = true;
  20987. }
  20988. } else {
  20989. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20990. direction_eq = true;
  20991. }
  20992. }
  20993. }
  20994. if ( direction_eq ) {
  20995. // console.log("Warning: lines are a straight sequence");
  20996. v_trans_x = - v_prev_y;
  20997. v_trans_y = v_prev_x;
  20998. shrink_by = Math.sqrt( v_prev_lensq );
  20999. } else {
  21000. // console.log("Warning: lines are a straight spike");
  21001. v_trans_x = v_prev_x;
  21002. v_trans_y = v_prev_y;
  21003. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21004. }
  21005. }
  21006. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21007. }
  21008. var contourMovements = [];
  21009. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21010. if ( j === il ) j = 0;
  21011. if ( k === il ) k = 0;
  21012. // (j)---(i)---(k)
  21013. // console.log('i,j,k', i, j , k)
  21014. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21015. }
  21016. var holesMovements = [],
  21017. oneHoleMovements, verticesMovements = contourMovements.concat();
  21018. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21019. ahole = holes[ h ];
  21020. oneHoleMovements = [];
  21021. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21022. if ( j === il ) j = 0;
  21023. if ( k === il ) k = 0;
  21024. // (j)---(i)---(k)
  21025. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21026. }
  21027. holesMovements.push( oneHoleMovements );
  21028. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21029. }
  21030. // Loop bevelSegments, 1 for the front, 1 for the back
  21031. for ( b = 0; b < bevelSegments; b ++ ) {
  21032. //for ( b = bevelSegments; b > 0; b -- ) {
  21033. t = b / bevelSegments;
  21034. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21035. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  21036. // contract shape
  21037. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21038. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21039. v( vert.x, vert.y, - z );
  21040. }
  21041. // expand holes
  21042. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21043. ahole = holes[ h ];
  21044. oneHoleMovements = holesMovements[ h ];
  21045. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21046. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21047. v( vert.x, vert.y, - z );
  21048. }
  21049. }
  21050. }
  21051. bs = bevelSize;
  21052. // Back facing vertices
  21053. for ( i = 0; i < vlen; i ++ ) {
  21054. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21055. if ( ! extrudeByPath ) {
  21056. v( vert.x, vert.y, 0 );
  21057. } else {
  21058. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21059. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21060. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21061. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21062. v( position2.x, position2.y, position2.z );
  21063. }
  21064. }
  21065. // Add stepped vertices...
  21066. // Including front facing vertices
  21067. var s;
  21068. for ( s = 1; s <= steps; s ++ ) {
  21069. for ( i = 0; i < vlen; i ++ ) {
  21070. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21071. if ( ! extrudeByPath ) {
  21072. v( vert.x, vert.y, amount / steps * s );
  21073. } else {
  21074. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21075. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21076. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21077. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21078. v( position2.x, position2.y, position2.z );
  21079. }
  21080. }
  21081. }
  21082. // Add bevel segments planes
  21083. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21084. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  21085. t = b / bevelSegments;
  21086. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21087. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  21088. // contract shape
  21089. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21090. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21091. v( vert.x, vert.y, amount + z );
  21092. }
  21093. // expand holes
  21094. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21095. ahole = holes[ h ];
  21096. oneHoleMovements = holesMovements[ h ];
  21097. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21098. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21099. if ( ! extrudeByPath ) {
  21100. v( vert.x, vert.y, amount + z );
  21101. } else {
  21102. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21103. }
  21104. }
  21105. }
  21106. }
  21107. /* Faces */
  21108. // Top and bottom faces
  21109. buildLidFaces();
  21110. // Sides faces
  21111. buildSideFaces();
  21112. ///// Internal functions
  21113. function buildLidFaces() {
  21114. var start = verticesArray.length / 3;
  21115. if ( bevelEnabled ) {
  21116. var layer = 0; // steps + 1
  21117. var offset = vlen * layer;
  21118. // Bottom faces
  21119. for ( i = 0; i < flen; i ++ ) {
  21120. face = faces[ i ];
  21121. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21122. }
  21123. layer = steps + bevelSegments * 2;
  21124. offset = vlen * layer;
  21125. // Top faces
  21126. for ( i = 0; i < flen; i ++ ) {
  21127. face = faces[ i ];
  21128. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21129. }
  21130. } else {
  21131. // Bottom faces
  21132. for ( i = 0; i < flen; i ++ ) {
  21133. face = faces[ i ];
  21134. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21135. }
  21136. // Top faces
  21137. for ( i = 0; i < flen; i ++ ) {
  21138. face = faces[ i ];
  21139. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21140. }
  21141. }
  21142. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21143. }
  21144. // Create faces for the z-sides of the shape
  21145. function buildSideFaces() {
  21146. var start = verticesArray.length / 3;
  21147. var layeroffset = 0;
  21148. sidewalls( contour, layeroffset );
  21149. layeroffset += contour.length;
  21150. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21151. ahole = holes[ h ];
  21152. sidewalls( ahole, layeroffset );
  21153. //, true
  21154. layeroffset += ahole.length;
  21155. }
  21156. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21157. }
  21158. function sidewalls( contour, layeroffset ) {
  21159. var j, k;
  21160. i = contour.length;
  21161. while ( -- i >= 0 ) {
  21162. j = i;
  21163. k = i - 1;
  21164. if ( k < 0 ) k = contour.length - 1;
  21165. //console.log('b', i,j, i-1, k,vertices.length);
  21166. var s = 0,
  21167. sl = steps + bevelSegments * 2;
  21168. for ( s = 0; s < sl; s ++ ) {
  21169. var slen1 = vlen * s;
  21170. var slen2 = vlen * ( s + 1 );
  21171. var a = layeroffset + j + slen1,
  21172. b = layeroffset + k + slen1,
  21173. c = layeroffset + k + slen2,
  21174. d = layeroffset + j + slen2;
  21175. f4( a, b, c, d );
  21176. }
  21177. }
  21178. }
  21179. function v( x, y, z ) {
  21180. placeholder.push( x );
  21181. placeholder.push( y );
  21182. placeholder.push( z );
  21183. }
  21184. function f3( a, b, c ) {
  21185. addVertex( a );
  21186. addVertex( b );
  21187. addVertex( c );
  21188. var nextIndex = verticesArray.length / 3;
  21189. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21190. addUV( uvs[ 0 ] );
  21191. addUV( uvs[ 1 ] );
  21192. addUV( uvs[ 2 ] );
  21193. }
  21194. function f4( a, b, c, d ) {
  21195. addVertex( a );
  21196. addVertex( b );
  21197. addVertex( d );
  21198. addVertex( b );
  21199. addVertex( c );
  21200. addVertex( d );
  21201. var nextIndex = verticesArray.length / 3;
  21202. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21203. addUV( uvs[ 0 ] );
  21204. addUV( uvs[ 1 ] );
  21205. addUV( uvs[ 3 ] );
  21206. addUV( uvs[ 1 ] );
  21207. addUV( uvs[ 2 ] );
  21208. addUV( uvs[ 3 ] );
  21209. }
  21210. function addVertex( index ) {
  21211. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21212. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21213. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21214. }
  21215. function addUV( vector2 ) {
  21216. uvArray.push( vector2.x );
  21217. uvArray.push( vector2.y );
  21218. }
  21219. }
  21220. }
  21221. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21222. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  21223. var WorldUVGenerator = {
  21224. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21225. var a_x = vertices[ indexA * 3 ];
  21226. var a_y = vertices[ indexA * 3 + 1 ];
  21227. var b_x = vertices[ indexB * 3 ];
  21228. var b_y = vertices[ indexB * 3 + 1 ];
  21229. var c_x = vertices[ indexC * 3 ];
  21230. var c_y = vertices[ indexC * 3 + 1 ];
  21231. return [
  21232. new Vector2( a_x, a_y ),
  21233. new Vector2( b_x, b_y ),
  21234. new Vector2( c_x, c_y )
  21235. ];
  21236. },
  21237. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21238. var a_x = vertices[ indexA * 3 ];
  21239. var a_y = vertices[ indexA * 3 + 1 ];
  21240. var a_z = vertices[ indexA * 3 + 2 ];
  21241. var b_x = vertices[ indexB * 3 ];
  21242. var b_y = vertices[ indexB * 3 + 1 ];
  21243. var b_z = vertices[ indexB * 3 + 2 ];
  21244. var c_x = vertices[ indexC * 3 ];
  21245. var c_y = vertices[ indexC * 3 + 1 ];
  21246. var c_z = vertices[ indexC * 3 + 2 ];
  21247. var d_x = vertices[ indexD * 3 ];
  21248. var d_y = vertices[ indexD * 3 + 1 ];
  21249. var d_z = vertices[ indexD * 3 + 2 ];
  21250. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  21251. return [
  21252. new Vector2( a_x, 1 - a_z ),
  21253. new Vector2( b_x, 1 - b_z ),
  21254. new Vector2( c_x, 1 - c_z ),
  21255. new Vector2( d_x, 1 - d_z )
  21256. ];
  21257. } else {
  21258. return [
  21259. new Vector2( a_y, 1 - a_z ),
  21260. new Vector2( b_y, 1 - b_z ),
  21261. new Vector2( c_y, 1 - c_z ),
  21262. new Vector2( d_y, 1 - d_z )
  21263. ];
  21264. }
  21265. }
  21266. };
  21267. /**
  21268. * @author zz85 / http://www.lab4games.net/zz85/blog
  21269. * @author alteredq / http://alteredqualia.com/
  21270. *
  21271. * Text = 3D Text
  21272. *
  21273. * parameters = {
  21274. * font: <THREE.Font>, // font
  21275. *
  21276. * size: <float>, // size of the text
  21277. * height: <float>, // thickness to extrude text
  21278. * curveSegments: <int>, // number of points on the curves
  21279. *
  21280. * bevelEnabled: <bool>, // turn on bevel
  21281. * bevelThickness: <float>, // how deep into text bevel goes
  21282. * bevelSize: <float> // how far from text outline is bevel
  21283. * }
  21284. */
  21285. // TextGeometry
  21286. function TextGeometry( text, parameters ) {
  21287. Geometry.call( this );
  21288. this.type = 'TextGeometry';
  21289. this.parameters = {
  21290. text: text,
  21291. parameters: parameters
  21292. };
  21293. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  21294. this.mergeVertices();
  21295. }
  21296. TextGeometry.prototype = Object.create( Geometry.prototype );
  21297. TextGeometry.prototype.constructor = TextGeometry;
  21298. // TextBufferGeometry
  21299. function TextBufferGeometry( text, parameters ) {
  21300. parameters = parameters || {};
  21301. var font = parameters.font;
  21302. if ( ! ( font && font.isFont ) ) {
  21303. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  21304. return new Geometry();
  21305. }
  21306. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  21307. // translate parameters to ExtrudeGeometry API
  21308. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  21309. // defaults
  21310. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  21311. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  21312. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  21313. ExtrudeBufferGeometry.call( this, shapes, parameters );
  21314. this.type = 'TextBufferGeometry';
  21315. }
  21316. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  21317. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  21318. /**
  21319. * @author mrdoob / http://mrdoob.com/
  21320. * @author benaadams / https://twitter.com/ben_a_adams
  21321. * @author Mugen87 / https://github.com/Mugen87
  21322. */
  21323. // SphereGeometry
  21324. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21325. Geometry.call( this );
  21326. this.type = 'SphereGeometry';
  21327. this.parameters = {
  21328. radius: radius,
  21329. widthSegments: widthSegments,
  21330. heightSegments: heightSegments,
  21331. phiStart: phiStart,
  21332. phiLength: phiLength,
  21333. thetaStart: thetaStart,
  21334. thetaLength: thetaLength
  21335. };
  21336. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  21337. this.mergeVertices();
  21338. }
  21339. SphereGeometry.prototype = Object.create( Geometry.prototype );
  21340. SphereGeometry.prototype.constructor = SphereGeometry;
  21341. // SphereBufferGeometry
  21342. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21343. BufferGeometry.call( this );
  21344. this.type = 'SphereBufferGeometry';
  21345. this.parameters = {
  21346. radius: radius,
  21347. widthSegments: widthSegments,
  21348. heightSegments: heightSegments,
  21349. phiStart: phiStart,
  21350. phiLength: phiLength,
  21351. thetaStart: thetaStart,
  21352. thetaLength: thetaLength
  21353. };
  21354. radius = radius || 1;
  21355. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  21356. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  21357. phiStart = phiStart !== undefined ? phiStart : 0;
  21358. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  21359. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21360. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  21361. var thetaEnd = thetaStart + thetaLength;
  21362. var ix, iy;
  21363. var index = 0;
  21364. var grid = [];
  21365. var vertex = new Vector3();
  21366. var normal = new Vector3();
  21367. // buffers
  21368. var indices = [];
  21369. var vertices = [];
  21370. var normals = [];
  21371. var uvs = [];
  21372. // generate vertices, normals and uvs
  21373. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  21374. var verticesRow = [];
  21375. var v = iy / heightSegments;
  21376. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  21377. var u = ix / widthSegments;
  21378. // vertex
  21379. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21380. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21381. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21382. vertices.push( vertex.x, vertex.y, vertex.z );
  21383. // normal
  21384. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  21385. normals.push( normal.x, normal.y, normal.z );
  21386. // uv
  21387. uvs.push( u, 1 - v );
  21388. verticesRow.push( index ++ );
  21389. }
  21390. grid.push( verticesRow );
  21391. }
  21392. // indices
  21393. for ( iy = 0; iy < heightSegments; iy ++ ) {
  21394. for ( ix = 0; ix < widthSegments; ix ++ ) {
  21395. var a = grid[ iy ][ ix + 1 ];
  21396. var b = grid[ iy ][ ix ];
  21397. var c = grid[ iy + 1 ][ ix ];
  21398. var d = grid[ iy + 1 ][ ix + 1 ];
  21399. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21400. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21401. }
  21402. }
  21403. // build geometry
  21404. this.setIndex( indices );
  21405. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21406. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21407. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21408. }
  21409. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21410. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  21411. /**
  21412. * @author Kaleb Murphy
  21413. * @author Mugen87 / https://github.com/Mugen87
  21414. */
  21415. // RingGeometry
  21416. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21417. Geometry.call( this );
  21418. this.type = 'RingGeometry';
  21419. this.parameters = {
  21420. innerRadius: innerRadius,
  21421. outerRadius: outerRadius,
  21422. thetaSegments: thetaSegments,
  21423. phiSegments: phiSegments,
  21424. thetaStart: thetaStart,
  21425. thetaLength: thetaLength
  21426. };
  21427. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  21428. this.mergeVertices();
  21429. }
  21430. RingGeometry.prototype = Object.create( Geometry.prototype );
  21431. RingGeometry.prototype.constructor = RingGeometry;
  21432. // RingBufferGeometry
  21433. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21434. BufferGeometry.call( this );
  21435. this.type = 'RingBufferGeometry';
  21436. this.parameters = {
  21437. innerRadius: innerRadius,
  21438. outerRadius: outerRadius,
  21439. thetaSegments: thetaSegments,
  21440. phiSegments: phiSegments,
  21441. thetaStart: thetaStart,
  21442. thetaLength: thetaLength
  21443. };
  21444. innerRadius = innerRadius || 0.5;
  21445. outerRadius = outerRadius || 1;
  21446. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21447. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21448. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  21449. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  21450. // buffers
  21451. var indices = [];
  21452. var vertices = [];
  21453. var normals = [];
  21454. var uvs = [];
  21455. // some helper variables
  21456. var segment;
  21457. var radius = innerRadius;
  21458. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21459. var vertex = new Vector3();
  21460. var uv = new Vector2();
  21461. var j, i;
  21462. // generate vertices, normals and uvs
  21463. for ( j = 0; j <= phiSegments; j ++ ) {
  21464. for ( i = 0; i <= thetaSegments; i ++ ) {
  21465. // values are generate from the inside of the ring to the outside
  21466. segment = thetaStart + i / thetaSegments * thetaLength;
  21467. // vertex
  21468. vertex.x = radius * Math.cos( segment );
  21469. vertex.y = radius * Math.sin( segment );
  21470. vertices.push( vertex.x, vertex.y, vertex.z );
  21471. // normal
  21472. normals.push( 0, 0, 1 );
  21473. // uv
  21474. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21475. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21476. uvs.push( uv.x, uv.y );
  21477. }
  21478. // increase the radius for next row of vertices
  21479. radius += radiusStep;
  21480. }
  21481. // indices
  21482. for ( j = 0; j < phiSegments; j ++ ) {
  21483. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  21484. for ( i = 0; i < thetaSegments; i ++ ) {
  21485. segment = i + thetaSegmentLevel;
  21486. var a = segment;
  21487. var b = segment + thetaSegments + 1;
  21488. var c = segment + thetaSegments + 2;
  21489. var d = segment + 1;
  21490. // faces
  21491. indices.push( a, b, d );
  21492. indices.push( b, c, d );
  21493. }
  21494. }
  21495. // build geometry
  21496. this.setIndex( indices );
  21497. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21498. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21499. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21500. }
  21501. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21502. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  21503. /**
  21504. * @author astrodud / http://astrodud.isgreat.org/
  21505. * @author zz85 / https://github.com/zz85
  21506. * @author bhouston / http://clara.io
  21507. * @author Mugen87 / https://github.com/Mugen87
  21508. */
  21509. // LatheGeometry
  21510. function LatheGeometry( points, segments, phiStart, phiLength ) {
  21511. Geometry.call( this );
  21512. this.type = 'LatheGeometry';
  21513. this.parameters = {
  21514. points: points,
  21515. segments: segments,
  21516. phiStart: phiStart,
  21517. phiLength: phiLength
  21518. };
  21519. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  21520. this.mergeVertices();
  21521. }
  21522. LatheGeometry.prototype = Object.create( Geometry.prototype );
  21523. LatheGeometry.prototype.constructor = LatheGeometry;
  21524. // LatheBufferGeometry
  21525. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  21526. BufferGeometry.call( this );
  21527. this.type = 'LatheBufferGeometry';
  21528. this.parameters = {
  21529. points: points,
  21530. segments: segments,
  21531. phiStart: phiStart,
  21532. phiLength: phiLength
  21533. };
  21534. segments = Math.floor( segments ) || 12;
  21535. phiStart = phiStart || 0;
  21536. phiLength = phiLength || Math.PI * 2;
  21537. // clamp phiLength so it's in range of [ 0, 2PI ]
  21538. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  21539. // buffers
  21540. var indices = [];
  21541. var vertices = [];
  21542. var uvs = [];
  21543. // helper variables
  21544. var base;
  21545. var inverseSegments = 1.0 / segments;
  21546. var vertex = new Vector3();
  21547. var uv = new Vector2();
  21548. var i, j;
  21549. // generate vertices and uvs
  21550. for ( i = 0; i <= segments; i ++ ) {
  21551. var phi = phiStart + i * inverseSegments * phiLength;
  21552. var sin = Math.sin( phi );
  21553. var cos = Math.cos( phi );
  21554. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  21555. // vertex
  21556. vertex.x = points[ j ].x * sin;
  21557. vertex.y = points[ j ].y;
  21558. vertex.z = points[ j ].x * cos;
  21559. vertices.push( vertex.x, vertex.y, vertex.z );
  21560. // uv
  21561. uv.x = i / segments;
  21562. uv.y = j / ( points.length - 1 );
  21563. uvs.push( uv.x, uv.y );
  21564. }
  21565. }
  21566. // indices
  21567. for ( i = 0; i < segments; i ++ ) {
  21568. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  21569. base = j + i * points.length;
  21570. var a = base;
  21571. var b = base + points.length;
  21572. var c = base + points.length + 1;
  21573. var d = base + 1;
  21574. // faces
  21575. indices.push( a, b, d );
  21576. indices.push( b, c, d );
  21577. }
  21578. }
  21579. // build geometry
  21580. this.setIndex( indices );
  21581. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21582. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21583. // generate normals
  21584. this.computeVertexNormals();
  21585. // if the geometry is closed, we need to average the normals along the seam.
  21586. // because the corresponding vertices are identical (but still have different UVs).
  21587. if ( phiLength === Math.PI * 2 ) {
  21588. var normals = this.attributes.normal.array;
  21589. var n1 = new Vector3();
  21590. var n2 = new Vector3();
  21591. var n = new Vector3();
  21592. // this is the buffer offset for the last line of vertices
  21593. base = segments * points.length * 3;
  21594. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  21595. // select the normal of the vertex in the first line
  21596. n1.x = normals[ j + 0 ];
  21597. n1.y = normals[ j + 1 ];
  21598. n1.z = normals[ j + 2 ];
  21599. // select the normal of the vertex in the last line
  21600. n2.x = normals[ base + j + 0 ];
  21601. n2.y = normals[ base + j + 1 ];
  21602. n2.z = normals[ base + j + 2 ];
  21603. // average normals
  21604. n.addVectors( n1, n2 ).normalize();
  21605. // assign the new values to both normals
  21606. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  21607. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  21608. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  21609. }
  21610. }
  21611. }
  21612. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21613. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  21614. /**
  21615. * @author jonobr1 / http://jonobr1.com
  21616. * @author Mugen87 / https://github.com/Mugen87
  21617. */
  21618. // ShapeGeometry
  21619. function ShapeGeometry( shapes, curveSegments ) {
  21620. Geometry.call( this );
  21621. this.type = 'ShapeGeometry';
  21622. if ( typeof curveSegments === 'object' ) {
  21623. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  21624. curveSegments = curveSegments.curveSegments;
  21625. }
  21626. this.parameters = {
  21627. shapes: shapes,
  21628. curveSegments: curveSegments
  21629. };
  21630. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  21631. this.mergeVertices();
  21632. }
  21633. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  21634. ShapeGeometry.prototype.constructor = ShapeGeometry;
  21635. ShapeGeometry.prototype.toJSON = function () {
  21636. var data = Geometry.prototype.toJSON.call( this );
  21637. var shapes = this.parameters.shapes;
  21638. return toJSON( shapes, data );
  21639. };
  21640. // ShapeBufferGeometry
  21641. function ShapeBufferGeometry( shapes, curveSegments ) {
  21642. BufferGeometry.call( this );
  21643. this.type = 'ShapeBufferGeometry';
  21644. this.parameters = {
  21645. shapes: shapes,
  21646. curveSegments: curveSegments
  21647. };
  21648. curveSegments = curveSegments || 12;
  21649. // buffers
  21650. var indices = [];
  21651. var vertices = [];
  21652. var normals = [];
  21653. var uvs = [];
  21654. // helper variables
  21655. var groupStart = 0;
  21656. var groupCount = 0;
  21657. // allow single and array values for "shapes" parameter
  21658. if ( Array.isArray( shapes ) === false ) {
  21659. addShape( shapes );
  21660. } else {
  21661. for ( var i = 0; i < shapes.length; i ++ ) {
  21662. addShape( shapes[ i ] );
  21663. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21664. groupStart += groupCount;
  21665. groupCount = 0;
  21666. }
  21667. }
  21668. // build geometry
  21669. this.setIndex( indices );
  21670. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21671. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21672. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21673. // helper functions
  21674. function addShape( shape ) {
  21675. var i, l, shapeHole;
  21676. var indexOffset = vertices.length / 3;
  21677. var points = shape.extractPoints( curveSegments );
  21678. var shapeVertices = points.shape;
  21679. var shapeHoles = points.holes;
  21680. // check direction of vertices
  21681. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21682. shapeVertices = shapeVertices.reverse();
  21683. // also check if holes are in the opposite direction
  21684. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21685. shapeHole = shapeHoles[ i ];
  21686. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21687. shapeHoles[ i ] = shapeHole.reverse();
  21688. }
  21689. }
  21690. }
  21691. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21692. // join vertices of inner and outer paths to a single array
  21693. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21694. shapeHole = shapeHoles[ i ];
  21695. shapeVertices = shapeVertices.concat( shapeHole );
  21696. }
  21697. // vertices, normals, uvs
  21698. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21699. var vertex = shapeVertices[ i ];
  21700. vertices.push( vertex.x, vertex.y, 0 );
  21701. normals.push( 0, 0, 1 );
  21702. uvs.push( vertex.x, vertex.y ); // world uvs
  21703. }
  21704. // incides
  21705. for ( i = 0, l = faces.length; i < l; i ++ ) {
  21706. var face = faces[ i ];
  21707. var a = face[ 0 ] + indexOffset;
  21708. var b = face[ 1 ] + indexOffset;
  21709. var c = face[ 2 ] + indexOffset;
  21710. indices.push( a, b, c );
  21711. groupCount += 3;
  21712. }
  21713. }
  21714. }
  21715. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21716. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  21717. ShapeBufferGeometry.prototype.toJSON = function () {
  21718. var data = BufferGeometry.prototype.toJSON.call( this );
  21719. var shapes = this.parameters.shapes;
  21720. return toJSON( shapes, data );
  21721. };
  21722. //
  21723. function toJSON( shapes, data ) {
  21724. data.shapes = [];
  21725. if ( Array.isArray( shapes ) ) {
  21726. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  21727. var shape = shapes[ i ];
  21728. data.shapes.push( shape.uuid );
  21729. }
  21730. } else {
  21731. data.shapes.push( shapes.uuid );
  21732. }
  21733. return data;
  21734. }
  21735. /**
  21736. * @author WestLangley / http://github.com/WestLangley
  21737. * @author Mugen87 / https://github.com/Mugen87
  21738. */
  21739. function EdgesGeometry( geometry, thresholdAngle ) {
  21740. BufferGeometry.call( this );
  21741. this.type = 'EdgesGeometry';
  21742. this.parameters = {
  21743. thresholdAngle: thresholdAngle
  21744. };
  21745. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  21746. // buffer
  21747. var vertices = [];
  21748. // helper variables
  21749. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  21750. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  21751. var key, keys = [ 'a', 'b', 'c' ];
  21752. // prepare source geometry
  21753. var geometry2;
  21754. if ( geometry.isBufferGeometry ) {
  21755. geometry2 = new Geometry();
  21756. geometry2.fromBufferGeometry( geometry );
  21757. } else {
  21758. geometry2 = geometry.clone();
  21759. }
  21760. geometry2.mergeVertices();
  21761. geometry2.computeFaceNormals();
  21762. var sourceVertices = geometry2.vertices;
  21763. var faces = geometry2.faces;
  21764. // now create a data structure where each entry represents an edge with its adjoining faces
  21765. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21766. var face = faces[ i ];
  21767. for ( var j = 0; j < 3; j ++ ) {
  21768. edge1 = face[ keys[ j ] ];
  21769. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  21770. edge[ 0 ] = Math.min( edge1, edge2 );
  21771. edge[ 1 ] = Math.max( edge1, edge2 );
  21772. key = edge[ 0 ] + ',' + edge[ 1 ];
  21773. if ( edges[ key ] === undefined ) {
  21774. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  21775. } else {
  21776. edges[ key ].face2 = i;
  21777. }
  21778. }
  21779. }
  21780. // generate vertices
  21781. for ( key in edges ) {
  21782. var e = edges[ key ];
  21783. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  21784. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  21785. var vertex = sourceVertices[ e.index1 ];
  21786. vertices.push( vertex.x, vertex.y, vertex.z );
  21787. vertex = sourceVertices[ e.index2 ];
  21788. vertices.push( vertex.x, vertex.y, vertex.z );
  21789. }
  21790. }
  21791. // build geometry
  21792. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21793. }
  21794. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  21795. EdgesGeometry.prototype.constructor = EdgesGeometry;
  21796. /**
  21797. * @author mrdoob / http://mrdoob.com/
  21798. * @author Mugen87 / https://github.com/Mugen87
  21799. */
  21800. // CylinderGeometry
  21801. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21802. Geometry.call( this );
  21803. this.type = 'CylinderGeometry';
  21804. this.parameters = {
  21805. radiusTop: radiusTop,
  21806. radiusBottom: radiusBottom,
  21807. height: height,
  21808. radialSegments: radialSegments,
  21809. heightSegments: heightSegments,
  21810. openEnded: openEnded,
  21811. thetaStart: thetaStart,
  21812. thetaLength: thetaLength
  21813. };
  21814. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  21815. this.mergeVertices();
  21816. }
  21817. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  21818. CylinderGeometry.prototype.constructor = CylinderGeometry;
  21819. // CylinderBufferGeometry
  21820. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21821. BufferGeometry.call( this );
  21822. this.type = 'CylinderBufferGeometry';
  21823. this.parameters = {
  21824. radiusTop: radiusTop,
  21825. radiusBottom: radiusBottom,
  21826. height: height,
  21827. radialSegments: radialSegments,
  21828. heightSegments: heightSegments,
  21829. openEnded: openEnded,
  21830. thetaStart: thetaStart,
  21831. thetaLength: thetaLength
  21832. };
  21833. var scope = this;
  21834. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  21835. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  21836. height = height || 1;
  21837. radialSegments = Math.floor( radialSegments ) || 8;
  21838. heightSegments = Math.floor( heightSegments ) || 1;
  21839. openEnded = openEnded !== undefined ? openEnded : false;
  21840. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  21841. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21842. // buffers
  21843. var indices = [];
  21844. var vertices = [];
  21845. var normals = [];
  21846. var uvs = [];
  21847. // helper variables
  21848. var index = 0;
  21849. var indexArray = [];
  21850. var halfHeight = height / 2;
  21851. var groupStart = 0;
  21852. // generate geometry
  21853. generateTorso();
  21854. if ( openEnded === false ) {
  21855. if ( radiusTop > 0 ) generateCap( true );
  21856. if ( radiusBottom > 0 ) generateCap( false );
  21857. }
  21858. // build geometry
  21859. this.setIndex( indices );
  21860. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21861. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21862. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21863. function generateTorso() {
  21864. var x, y;
  21865. var normal = new Vector3();
  21866. var vertex = new Vector3();
  21867. var groupCount = 0;
  21868. // this will be used to calculate the normal
  21869. var slope = ( radiusBottom - radiusTop ) / height;
  21870. // generate vertices, normals and uvs
  21871. for ( y = 0; y <= heightSegments; y ++ ) {
  21872. var indexRow = [];
  21873. var v = y / heightSegments;
  21874. // calculate the radius of the current row
  21875. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21876. for ( x = 0; x <= radialSegments; x ++ ) {
  21877. var u = x / radialSegments;
  21878. var theta = u * thetaLength + thetaStart;
  21879. var sinTheta = Math.sin( theta );
  21880. var cosTheta = Math.cos( theta );
  21881. // vertex
  21882. vertex.x = radius * sinTheta;
  21883. vertex.y = - v * height + halfHeight;
  21884. vertex.z = radius * cosTheta;
  21885. vertices.push( vertex.x, vertex.y, vertex.z );
  21886. // normal
  21887. normal.set( sinTheta, slope, cosTheta ).normalize();
  21888. normals.push( normal.x, normal.y, normal.z );
  21889. // uv
  21890. uvs.push( u, 1 - v );
  21891. // save index of vertex in respective row
  21892. indexRow.push( index ++ );
  21893. }
  21894. // now save vertices of the row in our index array
  21895. indexArray.push( indexRow );
  21896. }
  21897. // generate indices
  21898. for ( x = 0; x < radialSegments; x ++ ) {
  21899. for ( y = 0; y < heightSegments; y ++ ) {
  21900. // we use the index array to access the correct indices
  21901. var a = indexArray[ y ][ x ];
  21902. var b = indexArray[ y + 1 ][ x ];
  21903. var c = indexArray[ y + 1 ][ x + 1 ];
  21904. var d = indexArray[ y ][ x + 1 ];
  21905. // faces
  21906. indices.push( a, b, d );
  21907. indices.push( b, c, d );
  21908. // update group counter
  21909. groupCount += 6;
  21910. }
  21911. }
  21912. // add a group to the geometry. this will ensure multi material support
  21913. scope.addGroup( groupStart, groupCount, 0 );
  21914. // calculate new start value for groups
  21915. groupStart += groupCount;
  21916. }
  21917. function generateCap( top ) {
  21918. var x, centerIndexStart, centerIndexEnd;
  21919. var uv = new Vector2();
  21920. var vertex = new Vector3();
  21921. var groupCount = 0;
  21922. var radius = ( top === true ) ? radiusTop : radiusBottom;
  21923. var sign = ( top === true ) ? 1 : - 1;
  21924. // save the index of the first center vertex
  21925. centerIndexStart = index;
  21926. // first we generate the center vertex data of the cap.
  21927. // because the geometry needs one set of uvs per face,
  21928. // we must generate a center vertex per face/segment
  21929. for ( x = 1; x <= radialSegments; x ++ ) {
  21930. // vertex
  21931. vertices.push( 0, halfHeight * sign, 0 );
  21932. // normal
  21933. normals.push( 0, sign, 0 );
  21934. // uv
  21935. uvs.push( 0.5, 0.5 );
  21936. // increase index
  21937. index ++;
  21938. }
  21939. // save the index of the last center vertex
  21940. centerIndexEnd = index;
  21941. // now we generate the surrounding vertices, normals and uvs
  21942. for ( x = 0; x <= radialSegments; x ++ ) {
  21943. var u = x / radialSegments;
  21944. var theta = u * thetaLength + thetaStart;
  21945. var cosTheta = Math.cos( theta );
  21946. var sinTheta = Math.sin( theta );
  21947. // vertex
  21948. vertex.x = radius * sinTheta;
  21949. vertex.y = halfHeight * sign;
  21950. vertex.z = radius * cosTheta;
  21951. vertices.push( vertex.x, vertex.y, vertex.z );
  21952. // normal
  21953. normals.push( 0, sign, 0 );
  21954. // uv
  21955. uv.x = ( cosTheta * 0.5 ) + 0.5;
  21956. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  21957. uvs.push( uv.x, uv.y );
  21958. // increase index
  21959. index ++;
  21960. }
  21961. // generate indices
  21962. for ( x = 0; x < radialSegments; x ++ ) {
  21963. var c = centerIndexStart + x;
  21964. var i = centerIndexEnd + x;
  21965. if ( top === true ) {
  21966. // face top
  21967. indices.push( i, i + 1, c );
  21968. } else {
  21969. // face bottom
  21970. indices.push( i + 1, i, c );
  21971. }
  21972. groupCount += 3;
  21973. }
  21974. // add a group to the geometry. this will ensure multi material support
  21975. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  21976. // calculate new start value for groups
  21977. groupStart += groupCount;
  21978. }
  21979. }
  21980. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21981. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  21982. /**
  21983. * @author abelnation / http://github.com/abelnation
  21984. */
  21985. // ConeGeometry
  21986. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21987. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  21988. this.type = 'ConeGeometry';
  21989. this.parameters = {
  21990. radius: radius,
  21991. height: height,
  21992. radialSegments: radialSegments,
  21993. heightSegments: heightSegments,
  21994. openEnded: openEnded,
  21995. thetaStart: thetaStart,
  21996. thetaLength: thetaLength
  21997. };
  21998. }
  21999. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  22000. ConeGeometry.prototype.constructor = ConeGeometry;
  22001. // ConeBufferGeometry
  22002. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22003. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22004. this.type = 'ConeBufferGeometry';
  22005. this.parameters = {
  22006. radius: radius,
  22007. height: height,
  22008. radialSegments: radialSegments,
  22009. heightSegments: heightSegments,
  22010. openEnded: openEnded,
  22011. thetaStart: thetaStart,
  22012. thetaLength: thetaLength
  22013. };
  22014. }
  22015. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  22016. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  22017. /**
  22018. * @author benaadams / https://twitter.com/ben_a_adams
  22019. * @author Mugen87 / https://github.com/Mugen87
  22020. * @author hughes
  22021. */
  22022. // CircleGeometry
  22023. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  22024. Geometry.call( this );
  22025. this.type = 'CircleGeometry';
  22026. this.parameters = {
  22027. radius: radius,
  22028. segments: segments,
  22029. thetaStart: thetaStart,
  22030. thetaLength: thetaLength
  22031. };
  22032. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  22033. this.mergeVertices();
  22034. }
  22035. CircleGeometry.prototype = Object.create( Geometry.prototype );
  22036. CircleGeometry.prototype.constructor = CircleGeometry;
  22037. // CircleBufferGeometry
  22038. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  22039. BufferGeometry.call( this );
  22040. this.type = 'CircleBufferGeometry';
  22041. this.parameters = {
  22042. radius: radius,
  22043. segments: segments,
  22044. thetaStart: thetaStart,
  22045. thetaLength: thetaLength
  22046. };
  22047. radius = radius || 1;
  22048. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  22049. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22050. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22051. // buffers
  22052. var indices = [];
  22053. var vertices = [];
  22054. var normals = [];
  22055. var uvs = [];
  22056. // helper variables
  22057. var i, s;
  22058. var vertex = new Vector3();
  22059. var uv = new Vector2();
  22060. // center point
  22061. vertices.push( 0, 0, 0 );
  22062. normals.push( 0, 0, 1 );
  22063. uvs.push( 0.5, 0.5 );
  22064. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22065. var segment = thetaStart + s / segments * thetaLength;
  22066. // vertex
  22067. vertex.x = radius * Math.cos( segment );
  22068. vertex.y = radius * Math.sin( segment );
  22069. vertices.push( vertex.x, vertex.y, vertex.z );
  22070. // normal
  22071. normals.push( 0, 0, 1 );
  22072. // uvs
  22073. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22074. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22075. uvs.push( uv.x, uv.y );
  22076. }
  22077. // indices
  22078. for ( i = 1; i <= segments; i ++ ) {
  22079. indices.push( i, i + 1, 0 );
  22080. }
  22081. // build geometry
  22082. this.setIndex( indices );
  22083. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22084. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22085. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22086. }
  22087. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22088. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  22089. var Geometries = Object.freeze({
  22090. WireframeGeometry: WireframeGeometry,
  22091. ParametricGeometry: ParametricGeometry,
  22092. ParametricBufferGeometry: ParametricBufferGeometry,
  22093. TetrahedronGeometry: TetrahedronGeometry,
  22094. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  22095. OctahedronGeometry: OctahedronGeometry,
  22096. OctahedronBufferGeometry: OctahedronBufferGeometry,
  22097. IcosahedronGeometry: IcosahedronGeometry,
  22098. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  22099. DodecahedronGeometry: DodecahedronGeometry,
  22100. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  22101. PolyhedronGeometry: PolyhedronGeometry,
  22102. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  22103. TubeGeometry: TubeGeometry,
  22104. TubeBufferGeometry: TubeBufferGeometry,
  22105. TorusKnotGeometry: TorusKnotGeometry,
  22106. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  22107. TorusGeometry: TorusGeometry,
  22108. TorusBufferGeometry: TorusBufferGeometry,
  22109. TextGeometry: TextGeometry,
  22110. TextBufferGeometry: TextBufferGeometry,
  22111. SphereGeometry: SphereGeometry,
  22112. SphereBufferGeometry: SphereBufferGeometry,
  22113. RingGeometry: RingGeometry,
  22114. RingBufferGeometry: RingBufferGeometry,
  22115. PlaneGeometry: PlaneGeometry,
  22116. PlaneBufferGeometry: PlaneBufferGeometry,
  22117. LatheGeometry: LatheGeometry,
  22118. LatheBufferGeometry: LatheBufferGeometry,
  22119. ShapeGeometry: ShapeGeometry,
  22120. ShapeBufferGeometry: ShapeBufferGeometry,
  22121. ExtrudeGeometry: ExtrudeGeometry,
  22122. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  22123. EdgesGeometry: EdgesGeometry,
  22124. ConeGeometry: ConeGeometry,
  22125. ConeBufferGeometry: ConeBufferGeometry,
  22126. CylinderGeometry: CylinderGeometry,
  22127. CylinderBufferGeometry: CylinderBufferGeometry,
  22128. CircleGeometry: CircleGeometry,
  22129. CircleBufferGeometry: CircleBufferGeometry,
  22130. BoxGeometry: BoxGeometry,
  22131. BoxBufferGeometry: BoxBufferGeometry
  22132. });
  22133. /**
  22134. * @author mrdoob / http://mrdoob.com/
  22135. *
  22136. * parameters = {
  22137. * color: <THREE.Color>
  22138. * }
  22139. */
  22140. function ShadowMaterial( parameters ) {
  22141. Material.call( this );
  22142. this.type = 'ShadowMaterial';
  22143. this.color = new Color( 0x000000 );
  22144. this.transparent = true;
  22145. this.setValues( parameters );
  22146. }
  22147. ShadowMaterial.prototype = Object.create( Material.prototype );
  22148. ShadowMaterial.prototype.constructor = ShadowMaterial;
  22149. ShadowMaterial.prototype.isShadowMaterial = true;
  22150. ShadowMaterial.prototype.copy = function ( source ) {
  22151. Material.prototype.copy.call( this, source );
  22152. this.color.copy( source.color );
  22153. return this;
  22154. };
  22155. /**
  22156. * @author mrdoob / http://mrdoob.com/
  22157. */
  22158. function RawShaderMaterial( parameters ) {
  22159. ShaderMaterial.call( this, parameters );
  22160. this.type = 'RawShaderMaterial';
  22161. }
  22162. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  22163. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  22164. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  22165. /**
  22166. * @author WestLangley / http://github.com/WestLangley
  22167. *
  22168. * parameters = {
  22169. * color: <hex>,
  22170. * roughness: <float>,
  22171. * metalness: <float>,
  22172. * opacity: <float>,
  22173. *
  22174. * map: new THREE.Texture( <Image> ),
  22175. *
  22176. * lightMap: new THREE.Texture( <Image> ),
  22177. * lightMapIntensity: <float>
  22178. *
  22179. * aoMap: new THREE.Texture( <Image> ),
  22180. * aoMapIntensity: <float>
  22181. *
  22182. * emissive: <hex>,
  22183. * emissiveIntensity: <float>
  22184. * emissiveMap: new THREE.Texture( <Image> ),
  22185. *
  22186. * bumpMap: new THREE.Texture( <Image> ),
  22187. * bumpScale: <float>,
  22188. *
  22189. * normalMap: new THREE.Texture( <Image> ),
  22190. * normalScale: <Vector2>,
  22191. *
  22192. * displacementMap: new THREE.Texture( <Image> ),
  22193. * displacementScale: <float>,
  22194. * displacementBias: <float>,
  22195. *
  22196. * roughnessMap: new THREE.Texture( <Image> ),
  22197. *
  22198. * metalnessMap: new THREE.Texture( <Image> ),
  22199. *
  22200. * alphaMap: new THREE.Texture( <Image> ),
  22201. *
  22202. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22203. * envMapIntensity: <float>
  22204. *
  22205. * refractionRatio: <float>,
  22206. *
  22207. * wireframe: <boolean>,
  22208. * wireframeLinewidth: <float>,
  22209. *
  22210. * skinning: <bool>,
  22211. * morphTargets: <bool>,
  22212. * morphNormals: <bool>
  22213. * }
  22214. */
  22215. function MeshStandardMaterial( parameters ) {
  22216. Material.call( this );
  22217. this.defines = { 'STANDARD': '' };
  22218. this.type = 'MeshStandardMaterial';
  22219. this.color = new Color( 0xffffff ); // diffuse
  22220. this.roughness = 0.5;
  22221. this.metalness = 0.5;
  22222. this.map = null;
  22223. this.lightMap = null;
  22224. this.lightMapIntensity = 1.0;
  22225. this.aoMap = null;
  22226. this.aoMapIntensity = 1.0;
  22227. this.emissive = new Color( 0x000000 );
  22228. this.emissiveIntensity = 1.0;
  22229. this.emissiveMap = null;
  22230. this.bumpMap = null;
  22231. this.bumpScale = 1;
  22232. this.normalMap = null;
  22233. this.normalScale = new Vector2( 1, 1 );
  22234. this.displacementMap = null;
  22235. this.displacementScale = 1;
  22236. this.displacementBias = 0;
  22237. this.roughnessMap = null;
  22238. this.metalnessMap = null;
  22239. this.alphaMap = null;
  22240. this.envMap = null;
  22241. this.envMapIntensity = 1.0;
  22242. this.refractionRatio = 0.98;
  22243. this.wireframe = false;
  22244. this.wireframeLinewidth = 1;
  22245. this.wireframeLinecap = 'round';
  22246. this.wireframeLinejoin = 'round';
  22247. this.skinning = false;
  22248. this.morphTargets = false;
  22249. this.morphNormals = false;
  22250. this.setValues( parameters );
  22251. }
  22252. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  22253. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  22254. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  22255. MeshStandardMaterial.prototype.copy = function ( source ) {
  22256. Material.prototype.copy.call( this, source );
  22257. this.defines = { 'STANDARD': '' };
  22258. this.color.copy( source.color );
  22259. this.roughness = source.roughness;
  22260. this.metalness = source.metalness;
  22261. this.map = source.map;
  22262. this.lightMap = source.lightMap;
  22263. this.lightMapIntensity = source.lightMapIntensity;
  22264. this.aoMap = source.aoMap;
  22265. this.aoMapIntensity = source.aoMapIntensity;
  22266. this.emissive.copy( source.emissive );
  22267. this.emissiveMap = source.emissiveMap;
  22268. this.emissiveIntensity = source.emissiveIntensity;
  22269. this.bumpMap = source.bumpMap;
  22270. this.bumpScale = source.bumpScale;
  22271. this.normalMap = source.normalMap;
  22272. this.normalScale.copy( source.normalScale );
  22273. this.displacementMap = source.displacementMap;
  22274. this.displacementScale = source.displacementScale;
  22275. this.displacementBias = source.displacementBias;
  22276. this.roughnessMap = source.roughnessMap;
  22277. this.metalnessMap = source.metalnessMap;
  22278. this.alphaMap = source.alphaMap;
  22279. this.envMap = source.envMap;
  22280. this.envMapIntensity = source.envMapIntensity;
  22281. this.refractionRatio = source.refractionRatio;
  22282. this.wireframe = source.wireframe;
  22283. this.wireframeLinewidth = source.wireframeLinewidth;
  22284. this.wireframeLinecap = source.wireframeLinecap;
  22285. this.wireframeLinejoin = source.wireframeLinejoin;
  22286. this.skinning = source.skinning;
  22287. this.morphTargets = source.morphTargets;
  22288. this.morphNormals = source.morphNormals;
  22289. return this;
  22290. };
  22291. /**
  22292. * @author WestLangley / http://github.com/WestLangley
  22293. *
  22294. * parameters = {
  22295. * reflectivity: <float>
  22296. * }
  22297. */
  22298. function MeshPhysicalMaterial( parameters ) {
  22299. MeshStandardMaterial.call( this );
  22300. this.defines = { 'PHYSICAL': '' };
  22301. this.type = 'MeshPhysicalMaterial';
  22302. this.reflectivity = 0.5; // maps to F0 = 0.04
  22303. this.clearCoat = 0.0;
  22304. this.clearCoatRoughness = 0.0;
  22305. this.setValues( parameters );
  22306. }
  22307. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  22308. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  22309. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  22310. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  22311. MeshStandardMaterial.prototype.copy.call( this, source );
  22312. this.defines = { 'PHYSICAL': '' };
  22313. this.reflectivity = source.reflectivity;
  22314. this.clearCoat = source.clearCoat;
  22315. this.clearCoatRoughness = source.clearCoatRoughness;
  22316. return this;
  22317. };
  22318. /**
  22319. * @author mrdoob / http://mrdoob.com/
  22320. * @author alteredq / http://alteredqualia.com/
  22321. *
  22322. * parameters = {
  22323. * color: <hex>,
  22324. * specular: <hex>,
  22325. * shininess: <float>,
  22326. * opacity: <float>,
  22327. *
  22328. * map: new THREE.Texture( <Image> ),
  22329. *
  22330. * lightMap: new THREE.Texture( <Image> ),
  22331. * lightMapIntensity: <float>
  22332. *
  22333. * aoMap: new THREE.Texture( <Image> ),
  22334. * aoMapIntensity: <float>
  22335. *
  22336. * emissive: <hex>,
  22337. * emissiveIntensity: <float>
  22338. * emissiveMap: new THREE.Texture( <Image> ),
  22339. *
  22340. * bumpMap: new THREE.Texture( <Image> ),
  22341. * bumpScale: <float>,
  22342. *
  22343. * normalMap: new THREE.Texture( <Image> ),
  22344. * normalScale: <Vector2>,
  22345. *
  22346. * displacementMap: new THREE.Texture( <Image> ),
  22347. * displacementScale: <float>,
  22348. * displacementBias: <float>,
  22349. *
  22350. * specularMap: new THREE.Texture( <Image> ),
  22351. *
  22352. * alphaMap: new THREE.Texture( <Image> ),
  22353. *
  22354. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22355. * combine: THREE.Multiply,
  22356. * reflectivity: <float>,
  22357. * refractionRatio: <float>,
  22358. *
  22359. * wireframe: <boolean>,
  22360. * wireframeLinewidth: <float>,
  22361. *
  22362. * skinning: <bool>,
  22363. * morphTargets: <bool>,
  22364. * morphNormals: <bool>
  22365. * }
  22366. */
  22367. function MeshPhongMaterial( parameters ) {
  22368. Material.call( this );
  22369. this.type = 'MeshPhongMaterial';
  22370. this.color = new Color( 0xffffff ); // diffuse
  22371. this.specular = new Color( 0x111111 );
  22372. this.shininess = 30;
  22373. this.map = null;
  22374. this.lightMap = null;
  22375. this.lightMapIntensity = 1.0;
  22376. this.aoMap = null;
  22377. this.aoMapIntensity = 1.0;
  22378. this.emissive = new Color( 0x000000 );
  22379. this.emissiveIntensity = 1.0;
  22380. this.emissiveMap = null;
  22381. this.bumpMap = null;
  22382. this.bumpScale = 1;
  22383. this.normalMap = null;
  22384. this.normalScale = new Vector2( 1, 1 );
  22385. this.displacementMap = null;
  22386. this.displacementScale = 1;
  22387. this.displacementBias = 0;
  22388. this.specularMap = null;
  22389. this.alphaMap = null;
  22390. this.envMap = null;
  22391. this.combine = MultiplyOperation;
  22392. this.reflectivity = 1;
  22393. this.refractionRatio = 0.98;
  22394. this.wireframe = false;
  22395. this.wireframeLinewidth = 1;
  22396. this.wireframeLinecap = 'round';
  22397. this.wireframeLinejoin = 'round';
  22398. this.skinning = false;
  22399. this.morphTargets = false;
  22400. this.morphNormals = false;
  22401. this.setValues( parameters );
  22402. }
  22403. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  22404. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  22405. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  22406. MeshPhongMaterial.prototype.copy = function ( source ) {
  22407. Material.prototype.copy.call( this, source );
  22408. this.color.copy( source.color );
  22409. this.specular.copy( source.specular );
  22410. this.shininess = source.shininess;
  22411. this.map = source.map;
  22412. this.lightMap = source.lightMap;
  22413. this.lightMapIntensity = source.lightMapIntensity;
  22414. this.aoMap = source.aoMap;
  22415. this.aoMapIntensity = source.aoMapIntensity;
  22416. this.emissive.copy( source.emissive );
  22417. this.emissiveMap = source.emissiveMap;
  22418. this.emissiveIntensity = source.emissiveIntensity;
  22419. this.bumpMap = source.bumpMap;
  22420. this.bumpScale = source.bumpScale;
  22421. this.normalMap = source.normalMap;
  22422. this.normalScale.copy( source.normalScale );
  22423. this.displacementMap = source.displacementMap;
  22424. this.displacementScale = source.displacementScale;
  22425. this.displacementBias = source.displacementBias;
  22426. this.specularMap = source.specularMap;
  22427. this.alphaMap = source.alphaMap;
  22428. this.envMap = source.envMap;
  22429. this.combine = source.combine;
  22430. this.reflectivity = source.reflectivity;
  22431. this.refractionRatio = source.refractionRatio;
  22432. this.wireframe = source.wireframe;
  22433. this.wireframeLinewidth = source.wireframeLinewidth;
  22434. this.wireframeLinecap = source.wireframeLinecap;
  22435. this.wireframeLinejoin = source.wireframeLinejoin;
  22436. this.skinning = source.skinning;
  22437. this.morphTargets = source.morphTargets;
  22438. this.morphNormals = source.morphNormals;
  22439. return this;
  22440. };
  22441. /**
  22442. * @author takahirox / http://github.com/takahirox
  22443. *
  22444. * parameters = {
  22445. * gradientMap: new THREE.Texture( <Image> )
  22446. * }
  22447. */
  22448. function MeshToonMaterial( parameters ) {
  22449. MeshPhongMaterial.call( this );
  22450. this.defines = { 'TOON': '' };
  22451. this.type = 'MeshToonMaterial';
  22452. this.gradientMap = null;
  22453. this.setValues( parameters );
  22454. }
  22455. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  22456. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  22457. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  22458. MeshToonMaterial.prototype.copy = function ( source ) {
  22459. MeshPhongMaterial.prototype.copy.call( this, source );
  22460. this.gradientMap = source.gradientMap;
  22461. return this;
  22462. };
  22463. /**
  22464. * @author mrdoob / http://mrdoob.com/
  22465. * @author WestLangley / http://github.com/WestLangley
  22466. *
  22467. * parameters = {
  22468. * opacity: <float>,
  22469. *
  22470. * bumpMap: new THREE.Texture( <Image> ),
  22471. * bumpScale: <float>,
  22472. *
  22473. * normalMap: new THREE.Texture( <Image> ),
  22474. * normalScale: <Vector2>,
  22475. *
  22476. * displacementMap: new THREE.Texture( <Image> ),
  22477. * displacementScale: <float>,
  22478. * displacementBias: <float>,
  22479. *
  22480. * wireframe: <boolean>,
  22481. * wireframeLinewidth: <float>
  22482. *
  22483. * skinning: <bool>,
  22484. * morphTargets: <bool>,
  22485. * morphNormals: <bool>
  22486. * }
  22487. */
  22488. function MeshNormalMaterial( parameters ) {
  22489. Material.call( this );
  22490. this.type = 'MeshNormalMaterial';
  22491. this.bumpMap = null;
  22492. this.bumpScale = 1;
  22493. this.normalMap = null;
  22494. this.normalScale = new Vector2( 1, 1 );
  22495. this.displacementMap = null;
  22496. this.displacementScale = 1;
  22497. this.displacementBias = 0;
  22498. this.wireframe = false;
  22499. this.wireframeLinewidth = 1;
  22500. this.fog = false;
  22501. this.lights = false;
  22502. this.skinning = false;
  22503. this.morphTargets = false;
  22504. this.morphNormals = false;
  22505. this.setValues( parameters );
  22506. }
  22507. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  22508. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  22509. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  22510. MeshNormalMaterial.prototype.copy = function ( source ) {
  22511. Material.prototype.copy.call( this, source );
  22512. this.bumpMap = source.bumpMap;
  22513. this.bumpScale = source.bumpScale;
  22514. this.normalMap = source.normalMap;
  22515. this.normalScale.copy( source.normalScale );
  22516. this.displacementMap = source.displacementMap;
  22517. this.displacementScale = source.displacementScale;
  22518. this.displacementBias = source.displacementBias;
  22519. this.wireframe = source.wireframe;
  22520. this.wireframeLinewidth = source.wireframeLinewidth;
  22521. this.skinning = source.skinning;
  22522. this.morphTargets = source.morphTargets;
  22523. this.morphNormals = source.morphNormals;
  22524. return this;
  22525. };
  22526. /**
  22527. * @author mrdoob / http://mrdoob.com/
  22528. * @author alteredq / http://alteredqualia.com/
  22529. *
  22530. * parameters = {
  22531. * color: <hex>,
  22532. * opacity: <float>,
  22533. *
  22534. * map: new THREE.Texture( <Image> ),
  22535. *
  22536. * lightMap: new THREE.Texture( <Image> ),
  22537. * lightMapIntensity: <float>
  22538. *
  22539. * aoMap: new THREE.Texture( <Image> ),
  22540. * aoMapIntensity: <float>
  22541. *
  22542. * emissive: <hex>,
  22543. * emissiveIntensity: <float>
  22544. * emissiveMap: new THREE.Texture( <Image> ),
  22545. *
  22546. * specularMap: new THREE.Texture( <Image> ),
  22547. *
  22548. * alphaMap: new THREE.Texture( <Image> ),
  22549. *
  22550. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22551. * combine: THREE.Multiply,
  22552. * reflectivity: <float>,
  22553. * refractionRatio: <float>,
  22554. *
  22555. * wireframe: <boolean>,
  22556. * wireframeLinewidth: <float>,
  22557. *
  22558. * skinning: <bool>,
  22559. * morphTargets: <bool>,
  22560. * morphNormals: <bool>
  22561. * }
  22562. */
  22563. function MeshLambertMaterial( parameters ) {
  22564. Material.call( this );
  22565. this.type = 'MeshLambertMaterial';
  22566. this.color = new Color( 0xffffff ); // diffuse
  22567. this.map = null;
  22568. this.lightMap = null;
  22569. this.lightMapIntensity = 1.0;
  22570. this.aoMap = null;
  22571. this.aoMapIntensity = 1.0;
  22572. this.emissive = new Color( 0x000000 );
  22573. this.emissiveIntensity = 1.0;
  22574. this.emissiveMap = null;
  22575. this.specularMap = null;
  22576. this.alphaMap = null;
  22577. this.envMap = null;
  22578. this.combine = MultiplyOperation;
  22579. this.reflectivity = 1;
  22580. this.refractionRatio = 0.98;
  22581. this.wireframe = false;
  22582. this.wireframeLinewidth = 1;
  22583. this.wireframeLinecap = 'round';
  22584. this.wireframeLinejoin = 'round';
  22585. this.skinning = false;
  22586. this.morphTargets = false;
  22587. this.morphNormals = false;
  22588. this.setValues( parameters );
  22589. }
  22590. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  22591. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  22592. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  22593. MeshLambertMaterial.prototype.copy = function ( source ) {
  22594. Material.prototype.copy.call( this, source );
  22595. this.color.copy( source.color );
  22596. this.map = source.map;
  22597. this.lightMap = source.lightMap;
  22598. this.lightMapIntensity = source.lightMapIntensity;
  22599. this.aoMap = source.aoMap;
  22600. this.aoMapIntensity = source.aoMapIntensity;
  22601. this.emissive.copy( source.emissive );
  22602. this.emissiveMap = source.emissiveMap;
  22603. this.emissiveIntensity = source.emissiveIntensity;
  22604. this.specularMap = source.specularMap;
  22605. this.alphaMap = source.alphaMap;
  22606. this.envMap = source.envMap;
  22607. this.combine = source.combine;
  22608. this.reflectivity = source.reflectivity;
  22609. this.refractionRatio = source.refractionRatio;
  22610. this.wireframe = source.wireframe;
  22611. this.wireframeLinewidth = source.wireframeLinewidth;
  22612. this.wireframeLinecap = source.wireframeLinecap;
  22613. this.wireframeLinejoin = source.wireframeLinejoin;
  22614. this.skinning = source.skinning;
  22615. this.morphTargets = source.morphTargets;
  22616. this.morphNormals = source.morphNormals;
  22617. return this;
  22618. };
  22619. /**
  22620. * @author alteredq / http://alteredqualia.com/
  22621. *
  22622. * parameters = {
  22623. * color: <hex>,
  22624. * opacity: <float>,
  22625. *
  22626. * linewidth: <float>,
  22627. *
  22628. * scale: <float>,
  22629. * dashSize: <float>,
  22630. * gapSize: <float>
  22631. * }
  22632. */
  22633. function LineDashedMaterial( parameters ) {
  22634. LineBasicMaterial.call( this );
  22635. this.type = 'LineDashedMaterial';
  22636. this.scale = 1;
  22637. this.dashSize = 3;
  22638. this.gapSize = 1;
  22639. this.setValues( parameters );
  22640. }
  22641. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  22642. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  22643. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  22644. LineDashedMaterial.prototype.copy = function ( source ) {
  22645. LineBasicMaterial.prototype.copy.call( this, source );
  22646. this.scale = source.scale;
  22647. this.dashSize = source.dashSize;
  22648. this.gapSize = source.gapSize;
  22649. return this;
  22650. };
  22651. var Materials = Object.freeze({
  22652. ShadowMaterial: ShadowMaterial,
  22653. SpriteMaterial: SpriteMaterial,
  22654. RawShaderMaterial: RawShaderMaterial,
  22655. ShaderMaterial: ShaderMaterial,
  22656. PointsMaterial: PointsMaterial,
  22657. MeshPhysicalMaterial: MeshPhysicalMaterial,
  22658. MeshStandardMaterial: MeshStandardMaterial,
  22659. MeshPhongMaterial: MeshPhongMaterial,
  22660. MeshToonMaterial: MeshToonMaterial,
  22661. MeshNormalMaterial: MeshNormalMaterial,
  22662. MeshLambertMaterial: MeshLambertMaterial,
  22663. MeshDepthMaterial: MeshDepthMaterial,
  22664. MeshDistanceMaterial: MeshDistanceMaterial,
  22665. MeshBasicMaterial: MeshBasicMaterial,
  22666. LineDashedMaterial: LineDashedMaterial,
  22667. LineBasicMaterial: LineBasicMaterial,
  22668. Material: Material
  22669. });
  22670. /**
  22671. * @author mrdoob / http://mrdoob.com/
  22672. */
  22673. var Cache = {
  22674. enabled: false,
  22675. files: {},
  22676. add: function ( key, file ) {
  22677. if ( this.enabled === false ) return;
  22678. // console.log( 'THREE.Cache', 'Adding key:', key );
  22679. this.files[ key ] = file;
  22680. },
  22681. get: function ( key ) {
  22682. if ( this.enabled === false ) return;
  22683. // console.log( 'THREE.Cache', 'Checking key:', key );
  22684. return this.files[ key ];
  22685. },
  22686. remove: function ( key ) {
  22687. delete this.files[ key ];
  22688. },
  22689. clear: function () {
  22690. this.files = {};
  22691. }
  22692. };
  22693. /**
  22694. * @author mrdoob / http://mrdoob.com/
  22695. */
  22696. function LoadingManager( onLoad, onProgress, onError ) {
  22697. var scope = this;
  22698. var isLoading = false;
  22699. var itemsLoaded = 0;
  22700. var itemsTotal = 0;
  22701. var urlModifier = undefined;
  22702. this.onStart = undefined;
  22703. this.onLoad = onLoad;
  22704. this.onProgress = onProgress;
  22705. this.onError = onError;
  22706. this.itemStart = function ( url ) {
  22707. itemsTotal ++;
  22708. if ( isLoading === false ) {
  22709. if ( scope.onStart !== undefined ) {
  22710. scope.onStart( url, itemsLoaded, itemsTotal );
  22711. }
  22712. }
  22713. isLoading = true;
  22714. };
  22715. this.itemEnd = function ( url ) {
  22716. itemsLoaded ++;
  22717. if ( scope.onProgress !== undefined ) {
  22718. scope.onProgress( url, itemsLoaded, itemsTotal );
  22719. }
  22720. if ( itemsLoaded === itemsTotal ) {
  22721. isLoading = false;
  22722. if ( scope.onLoad !== undefined ) {
  22723. scope.onLoad();
  22724. }
  22725. }
  22726. };
  22727. this.itemError = function ( url ) {
  22728. if ( scope.onError !== undefined ) {
  22729. scope.onError( url );
  22730. }
  22731. };
  22732. this.resolveURL = function ( url ) {
  22733. if ( urlModifier ) {
  22734. return urlModifier( url );
  22735. }
  22736. return url;
  22737. };
  22738. this.setURLModifier = function ( transform ) {
  22739. urlModifier = transform;
  22740. return this;
  22741. };
  22742. }
  22743. var DefaultLoadingManager = new LoadingManager();
  22744. /**
  22745. * @author mrdoob / http://mrdoob.com/
  22746. */
  22747. var loading = {};
  22748. function FileLoader( manager ) {
  22749. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22750. }
  22751. Object.assign( FileLoader.prototype, {
  22752. load: function ( url, onLoad, onProgress, onError ) {
  22753. if ( url === undefined ) url = '';
  22754. if ( this.path !== undefined ) url = this.path + url;
  22755. url = this.manager.resolveURL( url );
  22756. var scope = this;
  22757. var cached = Cache.get( url );
  22758. if ( cached !== undefined ) {
  22759. scope.manager.itemStart( url );
  22760. setTimeout( function () {
  22761. if ( onLoad ) onLoad( cached );
  22762. scope.manager.itemEnd( url );
  22763. }, 0 );
  22764. return cached;
  22765. }
  22766. // Check if request is duplicate
  22767. if ( loading[ url ] !== undefined ) {
  22768. loading[ url ].push( {
  22769. onLoad: onLoad,
  22770. onProgress: onProgress,
  22771. onError: onError
  22772. } );
  22773. return;
  22774. }
  22775. // Check for data: URI
  22776. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22777. var dataUriRegexResult = url.match( dataUriRegex );
  22778. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22779. if ( dataUriRegexResult ) {
  22780. var mimeType = dataUriRegexResult[ 1 ];
  22781. var isBase64 = !! dataUriRegexResult[ 2 ];
  22782. var data = dataUriRegexResult[ 3 ];
  22783. data = window.decodeURIComponent( data );
  22784. if ( isBase64 ) data = window.atob( data );
  22785. try {
  22786. var response;
  22787. var responseType = ( this.responseType || '' ).toLowerCase();
  22788. switch ( responseType ) {
  22789. case 'arraybuffer':
  22790. case 'blob':
  22791. var view = new Uint8Array( data.length );
  22792. for ( var i = 0; i < data.length; i ++ ) {
  22793. view[ i ] = data.charCodeAt( i );
  22794. }
  22795. if ( responseType === 'blob' ) {
  22796. response = new Blob( [ view.buffer ], { type: mimeType } );
  22797. } else {
  22798. response = view.buffer;
  22799. }
  22800. break;
  22801. case 'document':
  22802. var parser = new DOMParser();
  22803. response = parser.parseFromString( data, mimeType );
  22804. break;
  22805. case 'json':
  22806. response = JSON.parse( data );
  22807. break;
  22808. default: // 'text' or other
  22809. response = data;
  22810. break;
  22811. }
  22812. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22813. window.setTimeout( function () {
  22814. if ( onLoad ) onLoad( response );
  22815. scope.manager.itemEnd( url );
  22816. }, 0 );
  22817. } catch ( error ) {
  22818. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22819. window.setTimeout( function () {
  22820. if ( onError ) onError( error );
  22821. scope.manager.itemEnd( url );
  22822. scope.manager.itemError( url );
  22823. }, 0 );
  22824. }
  22825. } else {
  22826. // Initialise array for duplicate requests
  22827. loading[ url ] = [];
  22828. loading[ url ].push( {
  22829. onLoad: onLoad,
  22830. onProgress: onProgress,
  22831. onError: onError
  22832. } );
  22833. var request = new XMLHttpRequest();
  22834. request.open( 'GET', url, true );
  22835. request.addEventListener( 'load', function ( event ) {
  22836. var response = this.response;
  22837. Cache.add( url, response );
  22838. var callbacks = loading[ url ];
  22839. delete loading[ url ];
  22840. if ( this.status === 200 ) {
  22841. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22842. var callback = callbacks[ i ];
  22843. if ( callback.onLoad ) callback.onLoad( response );
  22844. }
  22845. scope.manager.itemEnd( url );
  22846. } else if ( this.status === 0 ) {
  22847. // Some browsers return HTTP Status 0 when using non-http protocol
  22848. // e.g. 'file://' or 'data://'. Handle as success.
  22849. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  22850. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22851. var callback = callbacks[ i ];
  22852. if ( callback.onLoad ) callback.onLoad( response );
  22853. }
  22854. scope.manager.itemEnd( url );
  22855. } else {
  22856. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22857. var callback = callbacks[ i ];
  22858. if ( callback.onError ) callback.onError( event );
  22859. }
  22860. scope.manager.itemEnd( url );
  22861. scope.manager.itemError( url );
  22862. }
  22863. }, false );
  22864. request.addEventListener( 'progress', function ( event ) {
  22865. var callbacks = loading[ url ];
  22866. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22867. var callback = callbacks[ i ];
  22868. if ( callback.onProgress ) callback.onProgress( event );
  22869. }
  22870. }, false );
  22871. request.addEventListener( 'error', function ( event ) {
  22872. var callbacks = loading[ url ];
  22873. delete loading[ url ];
  22874. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22875. var callback = callbacks[ i ];
  22876. if ( callback.onError ) callback.onError( event );
  22877. }
  22878. scope.manager.itemEnd( url );
  22879. scope.manager.itemError( url );
  22880. }, false );
  22881. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  22882. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  22883. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  22884. for ( var header in this.requestHeader ) {
  22885. request.setRequestHeader( header, this.requestHeader[ header ] );
  22886. }
  22887. request.send( null );
  22888. }
  22889. scope.manager.itemStart( url );
  22890. return request;
  22891. },
  22892. setPath: function ( value ) {
  22893. this.path = value;
  22894. return this;
  22895. },
  22896. setResponseType: function ( value ) {
  22897. this.responseType = value;
  22898. return this;
  22899. },
  22900. setWithCredentials: function ( value ) {
  22901. this.withCredentials = value;
  22902. return this;
  22903. },
  22904. setMimeType: function ( value ) {
  22905. this.mimeType = value;
  22906. return this;
  22907. },
  22908. setRequestHeader: function ( value ) {
  22909. this.requestHeader = value;
  22910. return this;
  22911. }
  22912. } );
  22913. /**
  22914. * @author mrdoob / http://mrdoob.com/
  22915. *
  22916. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22917. */
  22918. function CompressedTextureLoader( manager ) {
  22919. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22920. // override in sub classes
  22921. this._parser = null;
  22922. }
  22923. Object.assign( CompressedTextureLoader.prototype, {
  22924. load: function ( url, onLoad, onProgress, onError ) {
  22925. var scope = this;
  22926. var images = [];
  22927. var texture = new CompressedTexture();
  22928. texture.image = images;
  22929. var loader = new FileLoader( this.manager );
  22930. loader.setPath( this.path );
  22931. loader.setResponseType( 'arraybuffer' );
  22932. function loadTexture( i ) {
  22933. loader.load( url[ i ], function ( buffer ) {
  22934. var texDatas = scope._parser( buffer, true );
  22935. images[ i ] = {
  22936. width: texDatas.width,
  22937. height: texDatas.height,
  22938. format: texDatas.format,
  22939. mipmaps: texDatas.mipmaps
  22940. };
  22941. loaded += 1;
  22942. if ( loaded === 6 ) {
  22943. if ( texDatas.mipmapCount === 1 )
  22944. texture.minFilter = LinearFilter;
  22945. texture.format = texDatas.format;
  22946. texture.needsUpdate = true;
  22947. if ( onLoad ) onLoad( texture );
  22948. }
  22949. }, onProgress, onError );
  22950. }
  22951. if ( Array.isArray( url ) ) {
  22952. var loaded = 0;
  22953. for ( var i = 0, il = url.length; i < il; ++ i ) {
  22954. loadTexture( i );
  22955. }
  22956. } else {
  22957. // compressed cubemap texture stored in a single DDS file
  22958. loader.load( url, function ( buffer ) {
  22959. var texDatas = scope._parser( buffer, true );
  22960. if ( texDatas.isCubemap ) {
  22961. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22962. for ( var f = 0; f < faces; f ++ ) {
  22963. images[ f ] = { mipmaps: [] };
  22964. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  22965. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  22966. images[ f ].format = texDatas.format;
  22967. images[ f ].width = texDatas.width;
  22968. images[ f ].height = texDatas.height;
  22969. }
  22970. }
  22971. } else {
  22972. texture.image.width = texDatas.width;
  22973. texture.image.height = texDatas.height;
  22974. texture.mipmaps = texDatas.mipmaps;
  22975. }
  22976. if ( texDatas.mipmapCount === 1 ) {
  22977. texture.minFilter = LinearFilter;
  22978. }
  22979. texture.format = texDatas.format;
  22980. texture.needsUpdate = true;
  22981. if ( onLoad ) onLoad( texture );
  22982. }, onProgress, onError );
  22983. }
  22984. return texture;
  22985. },
  22986. setPath: function ( value ) {
  22987. this.path = value;
  22988. return this;
  22989. }
  22990. } );
  22991. /**
  22992. * @author Nikos M. / https://github.com/foo123/
  22993. *
  22994. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22995. */
  22996. function DataTextureLoader( manager ) {
  22997. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22998. // override in sub classes
  22999. this._parser = null;
  23000. }
  23001. Object.assign( DataTextureLoader.prototype, {
  23002. load: function ( url, onLoad, onProgress, onError ) {
  23003. var scope = this;
  23004. var texture = new DataTexture();
  23005. var loader = new FileLoader( this.manager );
  23006. loader.setResponseType( 'arraybuffer' );
  23007. loader.load( url, function ( buffer ) {
  23008. var texData = scope._parser( buffer );
  23009. if ( ! texData ) return;
  23010. if ( undefined !== texData.image ) {
  23011. texture.image = texData.image;
  23012. } else if ( undefined !== texData.data ) {
  23013. texture.image.width = texData.width;
  23014. texture.image.height = texData.height;
  23015. texture.image.data = texData.data;
  23016. }
  23017. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  23018. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  23019. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  23020. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  23021. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  23022. if ( undefined !== texData.format ) {
  23023. texture.format = texData.format;
  23024. }
  23025. if ( undefined !== texData.type ) {
  23026. texture.type = texData.type;
  23027. }
  23028. if ( undefined !== texData.mipmaps ) {
  23029. texture.mipmaps = texData.mipmaps;
  23030. }
  23031. if ( 1 === texData.mipmapCount ) {
  23032. texture.minFilter = LinearFilter;
  23033. }
  23034. texture.needsUpdate = true;
  23035. if ( onLoad ) onLoad( texture, texData );
  23036. }, onProgress, onError );
  23037. return texture;
  23038. }
  23039. } );
  23040. /**
  23041. * @author mrdoob / http://mrdoob.com/
  23042. */
  23043. function ImageLoader( manager ) {
  23044. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23045. }
  23046. Object.assign( ImageLoader.prototype, {
  23047. crossOrigin: 'Anonymous',
  23048. load: function ( url, onLoad, onProgress, onError ) {
  23049. if ( url === undefined ) url = '';
  23050. if ( this.path !== undefined ) url = this.path + url;
  23051. url = this.manager.resolveURL( url );
  23052. var scope = this;
  23053. var cached = Cache.get( url );
  23054. if ( cached !== undefined ) {
  23055. scope.manager.itemStart( url );
  23056. setTimeout( function () {
  23057. if ( onLoad ) onLoad( cached );
  23058. scope.manager.itemEnd( url );
  23059. }, 0 );
  23060. return cached;
  23061. }
  23062. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  23063. image.addEventListener( 'load', function () {
  23064. Cache.add( url, this );
  23065. if ( onLoad ) onLoad( this );
  23066. scope.manager.itemEnd( url );
  23067. }, false );
  23068. /*
  23069. image.addEventListener( 'progress', function ( event ) {
  23070. if ( onProgress ) onProgress( event );
  23071. }, false );
  23072. */
  23073. image.addEventListener( 'error', function ( event ) {
  23074. if ( onError ) onError( event );
  23075. scope.manager.itemEnd( url );
  23076. scope.manager.itemError( url );
  23077. }, false );
  23078. if ( url.substr( 0, 5 ) !== 'data:' ) {
  23079. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23080. }
  23081. scope.manager.itemStart( url );
  23082. image.src = url;
  23083. return image;
  23084. },
  23085. setCrossOrigin: function ( value ) {
  23086. this.crossOrigin = value;
  23087. return this;
  23088. },
  23089. setPath: function ( value ) {
  23090. this.path = value;
  23091. return this;
  23092. }
  23093. } );
  23094. /**
  23095. * @author mrdoob / http://mrdoob.com/
  23096. */
  23097. function CubeTextureLoader( manager ) {
  23098. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23099. }
  23100. Object.assign( CubeTextureLoader.prototype, {
  23101. crossOrigin: 'Anonymous',
  23102. load: function ( urls, onLoad, onProgress, onError ) {
  23103. var texture = new CubeTexture();
  23104. var loader = new ImageLoader( this.manager );
  23105. loader.setCrossOrigin( this.crossOrigin );
  23106. loader.setPath( this.path );
  23107. var loaded = 0;
  23108. function loadTexture( i ) {
  23109. loader.load( urls[ i ], function ( image ) {
  23110. texture.images[ i ] = image;
  23111. loaded ++;
  23112. if ( loaded === 6 ) {
  23113. texture.needsUpdate = true;
  23114. if ( onLoad ) onLoad( texture );
  23115. }
  23116. }, undefined, onError );
  23117. }
  23118. for ( var i = 0; i < urls.length; ++ i ) {
  23119. loadTexture( i );
  23120. }
  23121. return texture;
  23122. },
  23123. setCrossOrigin: function ( value ) {
  23124. this.crossOrigin = value;
  23125. return this;
  23126. },
  23127. setPath: function ( value ) {
  23128. this.path = value;
  23129. return this;
  23130. }
  23131. } );
  23132. /**
  23133. * @author mrdoob / http://mrdoob.com/
  23134. */
  23135. function TextureLoader( manager ) {
  23136. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23137. }
  23138. Object.assign( TextureLoader.prototype, {
  23139. crossOrigin: 'Anonymous',
  23140. load: function ( url, onLoad, onProgress, onError ) {
  23141. var texture = new Texture();
  23142. var loader = new ImageLoader( this.manager );
  23143. loader.setCrossOrigin( this.crossOrigin );
  23144. loader.setPath( this.path );
  23145. loader.load( url, function ( image ) {
  23146. texture.image = image;
  23147. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  23148. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  23149. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  23150. texture.needsUpdate = true;
  23151. if ( onLoad !== undefined ) {
  23152. onLoad( texture );
  23153. }
  23154. }, onProgress, onError );
  23155. return texture;
  23156. },
  23157. setCrossOrigin: function ( value ) {
  23158. this.crossOrigin = value;
  23159. return this;
  23160. },
  23161. setPath: function ( value ) {
  23162. this.path = value;
  23163. return this;
  23164. }
  23165. } );
  23166. /**
  23167. * @author zz85 / http://www.lab4games.net/zz85/blog
  23168. * Extensible curve object
  23169. *
  23170. * Some common of curve methods:
  23171. * .getPoint( t, optionalTarget ), .getTangent( t )
  23172. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  23173. * .getPoints(), .getSpacedPoints()
  23174. * .getLength()
  23175. * .updateArcLengths()
  23176. *
  23177. * This following curves inherit from THREE.Curve:
  23178. *
  23179. * -- 2D curves --
  23180. * THREE.ArcCurve
  23181. * THREE.CubicBezierCurve
  23182. * THREE.EllipseCurve
  23183. * THREE.LineCurve
  23184. * THREE.QuadraticBezierCurve
  23185. * THREE.SplineCurve
  23186. *
  23187. * -- 3D curves --
  23188. * THREE.CatmullRomCurve3
  23189. * THREE.CubicBezierCurve3
  23190. * THREE.LineCurve3
  23191. * THREE.QuadraticBezierCurve3
  23192. *
  23193. * A series of curves can be represented as a THREE.CurvePath.
  23194. *
  23195. **/
  23196. /**************************************************************
  23197. * Abstract Curve base class
  23198. **************************************************************/
  23199. function Curve() {
  23200. this.type = 'Curve';
  23201. this.arcLengthDivisions = 200;
  23202. }
  23203. Object.assign( Curve.prototype, {
  23204. // Virtual base class method to overwrite and implement in subclasses
  23205. // - t [0 .. 1]
  23206. getPoint: function ( /* t, optionalTarget */ ) {
  23207. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  23208. return null;
  23209. },
  23210. // Get point at relative position in curve according to arc length
  23211. // - u [0 .. 1]
  23212. getPointAt: function ( u, optionalTarget ) {
  23213. var t = this.getUtoTmapping( u );
  23214. return this.getPoint( t, optionalTarget );
  23215. },
  23216. // Get sequence of points using getPoint( t )
  23217. getPoints: function ( divisions ) {
  23218. if ( divisions === undefined ) divisions = 5;
  23219. var points = [];
  23220. for ( var d = 0; d <= divisions; d ++ ) {
  23221. points.push( this.getPoint( d / divisions ) );
  23222. }
  23223. return points;
  23224. },
  23225. // Get sequence of points using getPointAt( u )
  23226. getSpacedPoints: function ( divisions ) {
  23227. if ( divisions === undefined ) divisions = 5;
  23228. var points = [];
  23229. for ( var d = 0; d <= divisions; d ++ ) {
  23230. points.push( this.getPointAt( d / divisions ) );
  23231. }
  23232. return points;
  23233. },
  23234. // Get total curve arc length
  23235. getLength: function () {
  23236. var lengths = this.getLengths();
  23237. return lengths[ lengths.length - 1 ];
  23238. },
  23239. // Get list of cumulative segment lengths
  23240. getLengths: function ( divisions ) {
  23241. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  23242. if ( this.cacheArcLengths &&
  23243. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23244. ! this.needsUpdate ) {
  23245. return this.cacheArcLengths;
  23246. }
  23247. this.needsUpdate = false;
  23248. var cache = [];
  23249. var current, last = this.getPoint( 0 );
  23250. var p, sum = 0;
  23251. cache.push( 0 );
  23252. for ( p = 1; p <= divisions; p ++ ) {
  23253. current = this.getPoint( p / divisions );
  23254. sum += current.distanceTo( last );
  23255. cache.push( sum );
  23256. last = current;
  23257. }
  23258. this.cacheArcLengths = cache;
  23259. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23260. },
  23261. updateArcLengths: function () {
  23262. this.needsUpdate = true;
  23263. this.getLengths();
  23264. },
  23265. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  23266. getUtoTmapping: function ( u, distance ) {
  23267. var arcLengths = this.getLengths();
  23268. var i = 0, il = arcLengths.length;
  23269. var targetArcLength; // The targeted u distance value to get
  23270. if ( distance ) {
  23271. targetArcLength = distance;
  23272. } else {
  23273. targetArcLength = u * arcLengths[ il - 1 ];
  23274. }
  23275. // binary search for the index with largest value smaller than target u distance
  23276. var low = 0, high = il - 1, comparison;
  23277. while ( low <= high ) {
  23278. 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
  23279. comparison = arcLengths[ i ] - targetArcLength;
  23280. if ( comparison < 0 ) {
  23281. low = i + 1;
  23282. } else if ( comparison > 0 ) {
  23283. high = i - 1;
  23284. } else {
  23285. high = i;
  23286. break;
  23287. // DONE
  23288. }
  23289. }
  23290. i = high;
  23291. if ( arcLengths[ i ] === targetArcLength ) {
  23292. return i / ( il - 1 );
  23293. }
  23294. // we could get finer grain at lengths, or use simple interpolation between two points
  23295. var lengthBefore = arcLengths[ i ];
  23296. var lengthAfter = arcLengths[ i + 1 ];
  23297. var segmentLength = lengthAfter - lengthBefore;
  23298. // determine where we are between the 'before' and 'after' points
  23299. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23300. // add that fractional amount to t
  23301. var t = ( i + segmentFraction ) / ( il - 1 );
  23302. return t;
  23303. },
  23304. // Returns a unit vector tangent at t
  23305. // In case any sub curve does not implement its tangent derivation,
  23306. // 2 points a small delta apart will be used to find its gradient
  23307. // which seems to give a reasonable approximation
  23308. getTangent: function ( t ) {
  23309. var delta = 0.0001;
  23310. var t1 = t - delta;
  23311. var t2 = t + delta;
  23312. // Capping in case of danger
  23313. if ( t1 < 0 ) t1 = 0;
  23314. if ( t2 > 1 ) t2 = 1;
  23315. var pt1 = this.getPoint( t1 );
  23316. var pt2 = this.getPoint( t2 );
  23317. var vec = pt2.clone().sub( pt1 );
  23318. return vec.normalize();
  23319. },
  23320. getTangentAt: function ( u ) {
  23321. var t = this.getUtoTmapping( u );
  23322. return this.getTangent( t );
  23323. },
  23324. computeFrenetFrames: function ( segments, closed ) {
  23325. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23326. var normal = new Vector3();
  23327. var tangents = [];
  23328. var normals = [];
  23329. var binormals = [];
  23330. var vec = new Vector3();
  23331. var mat = new Matrix4();
  23332. var i, u, theta;
  23333. // compute the tangent vectors for each segment on the curve
  23334. for ( i = 0; i <= segments; i ++ ) {
  23335. u = i / segments;
  23336. tangents[ i ] = this.getTangentAt( u );
  23337. tangents[ i ].normalize();
  23338. }
  23339. // select an initial normal vector perpendicular to the first tangent vector,
  23340. // and in the direction of the minimum tangent xyz component
  23341. normals[ 0 ] = new Vector3();
  23342. binormals[ 0 ] = new Vector3();
  23343. var min = Number.MAX_VALUE;
  23344. var tx = Math.abs( tangents[ 0 ].x );
  23345. var ty = Math.abs( tangents[ 0 ].y );
  23346. var tz = Math.abs( tangents[ 0 ].z );
  23347. if ( tx <= min ) {
  23348. min = tx;
  23349. normal.set( 1, 0, 0 );
  23350. }
  23351. if ( ty <= min ) {
  23352. min = ty;
  23353. normal.set( 0, 1, 0 );
  23354. }
  23355. if ( tz <= min ) {
  23356. normal.set( 0, 0, 1 );
  23357. }
  23358. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23359. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23360. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23361. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23362. for ( i = 1; i <= segments; i ++ ) {
  23363. normals[ i ] = normals[ i - 1 ].clone();
  23364. binormals[ i ] = binormals[ i - 1 ].clone();
  23365. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23366. if ( vec.length() > Number.EPSILON ) {
  23367. vec.normalize();
  23368. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  23369. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23370. }
  23371. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23372. }
  23373. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23374. if ( closed === true ) {
  23375. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  23376. theta /= segments;
  23377. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23378. theta = - theta;
  23379. }
  23380. for ( i = 1; i <= segments; i ++ ) {
  23381. // twist a little...
  23382. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23383. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23384. }
  23385. }
  23386. return {
  23387. tangents: tangents,
  23388. normals: normals,
  23389. binormals: binormals
  23390. };
  23391. },
  23392. clone: function () {
  23393. return new this.constructor().copy( this );
  23394. },
  23395. copy: function ( source ) {
  23396. this.arcLengthDivisions = source.arcLengthDivisions;
  23397. return this;
  23398. },
  23399. toJSON: function () {
  23400. var data = {
  23401. metadata: {
  23402. version: 4.5,
  23403. type: 'Curve',
  23404. generator: 'Curve.toJSON'
  23405. }
  23406. };
  23407. data.arcLengthDivisions = this.arcLengthDivisions;
  23408. data.type = this.type;
  23409. return data;
  23410. },
  23411. fromJSON: function ( json ) {
  23412. this.arcLengthDivisions = json.arcLengthDivisions;
  23413. return this;
  23414. }
  23415. } );
  23416. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23417. Curve.call( this );
  23418. this.type = 'EllipseCurve';
  23419. this.aX = aX || 0;
  23420. this.aY = aY || 0;
  23421. this.xRadius = xRadius || 1;
  23422. this.yRadius = yRadius || 1;
  23423. this.aStartAngle = aStartAngle || 0;
  23424. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23425. this.aClockwise = aClockwise || false;
  23426. this.aRotation = aRotation || 0;
  23427. }
  23428. EllipseCurve.prototype = Object.create( Curve.prototype );
  23429. EllipseCurve.prototype.constructor = EllipseCurve;
  23430. EllipseCurve.prototype.isEllipseCurve = true;
  23431. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23432. var point = optionalTarget || new Vector2();
  23433. var twoPi = Math.PI * 2;
  23434. var deltaAngle = this.aEndAngle - this.aStartAngle;
  23435. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23436. // ensures that deltaAngle is 0 .. 2 PI
  23437. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23438. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23439. if ( deltaAngle < Number.EPSILON ) {
  23440. if ( samePoints ) {
  23441. deltaAngle = 0;
  23442. } else {
  23443. deltaAngle = twoPi;
  23444. }
  23445. }
  23446. if ( this.aClockwise === true && ! samePoints ) {
  23447. if ( deltaAngle === twoPi ) {
  23448. deltaAngle = - twoPi;
  23449. } else {
  23450. deltaAngle = deltaAngle - twoPi;
  23451. }
  23452. }
  23453. var angle = this.aStartAngle + t * deltaAngle;
  23454. var x = this.aX + this.xRadius * Math.cos( angle );
  23455. var y = this.aY + this.yRadius * Math.sin( angle );
  23456. if ( this.aRotation !== 0 ) {
  23457. var cos = Math.cos( this.aRotation );
  23458. var sin = Math.sin( this.aRotation );
  23459. var tx = x - this.aX;
  23460. var ty = y - this.aY;
  23461. // Rotate the point about the center of the ellipse.
  23462. x = tx * cos - ty * sin + this.aX;
  23463. y = tx * sin + ty * cos + this.aY;
  23464. }
  23465. return point.set( x, y );
  23466. };
  23467. EllipseCurve.prototype.copy = function ( source ) {
  23468. Curve.prototype.copy.call( this, source );
  23469. this.aX = source.aX;
  23470. this.aY = source.aY;
  23471. this.xRadius = source.xRadius;
  23472. this.yRadius = source.yRadius;
  23473. this.aStartAngle = source.aStartAngle;
  23474. this.aEndAngle = source.aEndAngle;
  23475. this.aClockwise = source.aClockwise;
  23476. this.aRotation = source.aRotation;
  23477. return this;
  23478. };
  23479. EllipseCurve.prototype.toJSON = function () {
  23480. var data = Curve.prototype.toJSON.call( this );
  23481. data.aX = this.aX;
  23482. data.aY = this.aY;
  23483. data.xRadius = this.xRadius;
  23484. data.yRadius = this.yRadius;
  23485. data.aStartAngle = this.aStartAngle;
  23486. data.aEndAngle = this.aEndAngle;
  23487. data.aClockwise = this.aClockwise;
  23488. data.aRotation = this.aRotation;
  23489. return data;
  23490. };
  23491. EllipseCurve.prototype.fromJSON = function ( json ) {
  23492. Curve.prototype.fromJSON.call( this, json );
  23493. this.aX = json.aX;
  23494. this.aY = json.aY;
  23495. this.xRadius = json.xRadius;
  23496. this.yRadius = json.yRadius;
  23497. this.aStartAngle = json.aStartAngle;
  23498. this.aEndAngle = json.aEndAngle;
  23499. this.aClockwise = json.aClockwise;
  23500. this.aRotation = json.aRotation;
  23501. return this;
  23502. };
  23503. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23504. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23505. this.type = 'ArcCurve';
  23506. }
  23507. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  23508. ArcCurve.prototype.constructor = ArcCurve;
  23509. ArcCurve.prototype.isArcCurve = true;
  23510. /**
  23511. * @author zz85 https://github.com/zz85
  23512. *
  23513. * Centripetal CatmullRom Curve - which is useful for avoiding
  23514. * cusps and self-intersections in non-uniform catmull rom curves.
  23515. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23516. *
  23517. * curve.type accepts centripetal(default), chordal and catmullrom
  23518. * curve.tension is used for catmullrom which defaults to 0.5
  23519. */
  23520. /*
  23521. Based on an optimized c++ solution in
  23522. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23523. - http://ideone.com/NoEbVM
  23524. This CubicPoly class could be used for reusing some variables and calculations,
  23525. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23526. which can be placed in CurveUtils.
  23527. */
  23528. function CubicPoly() {
  23529. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23530. /*
  23531. * Compute coefficients for a cubic polynomial
  23532. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23533. * such that
  23534. * p(0) = x0, p(1) = x1
  23535. * and
  23536. * p'(0) = t0, p'(1) = t1.
  23537. */
  23538. function init( x0, x1, t0, t1 ) {
  23539. c0 = x0;
  23540. c1 = t0;
  23541. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  23542. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23543. }
  23544. return {
  23545. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23546. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23547. },
  23548. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23549. // compute tangents when parameterized in [t1,t2]
  23550. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23551. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23552. // rescale tangents for parametrization in [0,1]
  23553. t1 *= dt1;
  23554. t2 *= dt1;
  23555. init( x1, x2, t1, t2 );
  23556. },
  23557. calc: function ( t ) {
  23558. var t2 = t * t;
  23559. var t3 = t2 * t;
  23560. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23561. }
  23562. };
  23563. }
  23564. //
  23565. var tmp = new Vector3();
  23566. var px = new CubicPoly();
  23567. var py = new CubicPoly();
  23568. var pz = new CubicPoly();
  23569. function CatmullRomCurve3( points, closed, curveType, tension ) {
  23570. Curve.call( this );
  23571. this.type = 'CatmullRomCurve3';
  23572. this.points = points || [];
  23573. this.closed = closed || false;
  23574. this.curveType = curveType || 'centripetal';
  23575. this.tension = tension || 0.5;
  23576. }
  23577. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  23578. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23579. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23580. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23581. var point = optionalTarget || new Vector3();
  23582. var points = this.points;
  23583. var l = points.length;
  23584. var p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23585. var intPoint = Math.floor( p );
  23586. var weight = p - intPoint;
  23587. if ( this.closed ) {
  23588. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23589. } else if ( weight === 0 && intPoint === l - 1 ) {
  23590. intPoint = l - 2;
  23591. weight = 1;
  23592. }
  23593. var p0, p1, p2, p3; // 4 points
  23594. if ( this.closed || intPoint > 0 ) {
  23595. p0 = points[ ( intPoint - 1 ) % l ];
  23596. } else {
  23597. // extrapolate first point
  23598. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23599. p0 = tmp;
  23600. }
  23601. p1 = points[ intPoint % l ];
  23602. p2 = points[ ( intPoint + 1 ) % l ];
  23603. if ( this.closed || intPoint + 2 < l ) {
  23604. p3 = points[ ( intPoint + 2 ) % l ];
  23605. } else {
  23606. // extrapolate last point
  23607. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23608. p3 = tmp;
  23609. }
  23610. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23611. // init Centripetal / Chordal Catmull-Rom
  23612. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23613. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23614. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23615. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23616. // safety check for repeated points
  23617. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23618. if ( dt0 < 1e-4 ) dt0 = dt1;
  23619. if ( dt2 < 1e-4 ) dt2 = dt1;
  23620. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23621. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23622. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23623. } else if ( this.curveType === 'catmullrom' ) {
  23624. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23625. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23626. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23627. }
  23628. point.set(
  23629. px.calc( weight ),
  23630. py.calc( weight ),
  23631. pz.calc( weight )
  23632. );
  23633. return point;
  23634. };
  23635. CatmullRomCurve3.prototype.copy = function ( source ) {
  23636. Curve.prototype.copy.call( this, source );
  23637. this.points = [];
  23638. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  23639. var point = source.points[ i ];
  23640. this.points.push( point.clone() );
  23641. }
  23642. this.closed = source.closed;
  23643. this.curveType = source.curveType;
  23644. this.tension = source.tension;
  23645. return this;
  23646. };
  23647. CatmullRomCurve3.prototype.toJSON = function () {
  23648. var data = Curve.prototype.toJSON.call( this );
  23649. data.points = [];
  23650. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  23651. var point = this.points[ i ];
  23652. data.points.push( point.toArray() );
  23653. }
  23654. data.closed = this.closed;
  23655. data.curveType = this.curveType;
  23656. data.tension = this.tension;
  23657. return data;
  23658. };
  23659. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  23660. Curve.prototype.fromJSON.call( this, json );
  23661. this.points = [];
  23662. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  23663. var point = json.points[ i ];
  23664. this.points.push( new Vector3().fromArray( point ) );
  23665. }
  23666. this.closed = json.closed;
  23667. this.curveType = json.curveType;
  23668. this.tension = json.tension;
  23669. return this;
  23670. };
  23671. /**
  23672. * @author zz85 / http://www.lab4games.net/zz85/blog
  23673. *
  23674. * Bezier Curves formulas obtained from
  23675. * http://en.wikipedia.org/wiki/Bézier_curve
  23676. */
  23677. function CatmullRom( t, p0, p1, p2, p3 ) {
  23678. var v0 = ( p2 - p0 ) * 0.5;
  23679. var v1 = ( p3 - p1 ) * 0.5;
  23680. var t2 = t * t;
  23681. var t3 = t * t2;
  23682. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23683. }
  23684. //
  23685. function QuadraticBezierP0( t, p ) {
  23686. var k = 1 - t;
  23687. return k * k * p;
  23688. }
  23689. function QuadraticBezierP1( t, p ) {
  23690. return 2 * ( 1 - t ) * t * p;
  23691. }
  23692. function QuadraticBezierP2( t, p ) {
  23693. return t * t * p;
  23694. }
  23695. function QuadraticBezier( t, p0, p1, p2 ) {
  23696. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23697. QuadraticBezierP2( t, p2 );
  23698. }
  23699. //
  23700. function CubicBezierP0( t, p ) {
  23701. var k = 1 - t;
  23702. return k * k * k * p;
  23703. }
  23704. function CubicBezierP1( t, p ) {
  23705. var k = 1 - t;
  23706. return 3 * k * k * t * p;
  23707. }
  23708. function CubicBezierP2( t, p ) {
  23709. return 3 * ( 1 - t ) * t * t * p;
  23710. }
  23711. function CubicBezierP3( t, p ) {
  23712. return t * t * t * p;
  23713. }
  23714. function CubicBezier( t, p0, p1, p2, p3 ) {
  23715. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23716. CubicBezierP3( t, p3 );
  23717. }
  23718. function CubicBezierCurve( v0, v1, v2, v3 ) {
  23719. Curve.call( this );
  23720. this.type = 'CubicBezierCurve';
  23721. this.v0 = v0 || new Vector2();
  23722. this.v1 = v1 || new Vector2();
  23723. this.v2 = v2 || new Vector2();
  23724. this.v3 = v3 || new Vector2();
  23725. }
  23726. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  23727. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23728. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23729. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23730. var point = optionalTarget || new Vector2();
  23731. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23732. point.set(
  23733. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23734. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23735. );
  23736. return point;
  23737. };
  23738. CubicBezierCurve.prototype.copy = function ( source ) {
  23739. Curve.prototype.copy.call( this, source );
  23740. this.v0.copy( source.v0 );
  23741. this.v1.copy( source.v1 );
  23742. this.v2.copy( source.v2 );
  23743. this.v3.copy( source.v3 );
  23744. return this;
  23745. };
  23746. CubicBezierCurve.prototype.toJSON = function () {
  23747. var data = Curve.prototype.toJSON.call( this );
  23748. data.v0 = this.v0.toArray();
  23749. data.v1 = this.v1.toArray();
  23750. data.v2 = this.v2.toArray();
  23751. data.v3 = this.v3.toArray();
  23752. return data;
  23753. };
  23754. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  23755. Curve.prototype.fromJSON.call( this, json );
  23756. this.v0.fromArray( json.v0 );
  23757. this.v1.fromArray( json.v1 );
  23758. this.v2.fromArray( json.v2 );
  23759. this.v3.fromArray( json.v3 );
  23760. return this;
  23761. };
  23762. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  23763. Curve.call( this );
  23764. this.type = 'CubicBezierCurve3';
  23765. this.v0 = v0 || new Vector3();
  23766. this.v1 = v1 || new Vector3();
  23767. this.v2 = v2 || new Vector3();
  23768. this.v3 = v3 || new Vector3();
  23769. }
  23770. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  23771. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23772. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23773. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23774. var point = optionalTarget || new Vector3();
  23775. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23776. point.set(
  23777. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23778. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23779. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23780. );
  23781. return point;
  23782. };
  23783. CubicBezierCurve3.prototype.copy = function ( source ) {
  23784. Curve.prototype.copy.call( this, source );
  23785. this.v0.copy( source.v0 );
  23786. this.v1.copy( source.v1 );
  23787. this.v2.copy( source.v2 );
  23788. this.v3.copy( source.v3 );
  23789. return this;
  23790. };
  23791. CubicBezierCurve3.prototype.toJSON = function () {
  23792. var data = Curve.prototype.toJSON.call( this );
  23793. data.v0 = this.v0.toArray();
  23794. data.v1 = this.v1.toArray();
  23795. data.v2 = this.v2.toArray();
  23796. data.v3 = this.v3.toArray();
  23797. return data;
  23798. };
  23799. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  23800. Curve.prototype.fromJSON.call( this, json );
  23801. this.v0.fromArray( json.v0 );
  23802. this.v1.fromArray( json.v1 );
  23803. this.v2.fromArray( json.v2 );
  23804. this.v3.fromArray( json.v3 );
  23805. return this;
  23806. };
  23807. function LineCurve( v1, v2 ) {
  23808. Curve.call( this );
  23809. this.type = 'LineCurve';
  23810. this.v1 = v1 || new Vector2();
  23811. this.v2 = v2 || new Vector2();
  23812. }
  23813. LineCurve.prototype = Object.create( Curve.prototype );
  23814. LineCurve.prototype.constructor = LineCurve;
  23815. LineCurve.prototype.isLineCurve = true;
  23816. LineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23817. var point = optionalTarget || new Vector2();
  23818. if ( t === 1 ) {
  23819. point.copy( this.v2 );
  23820. } else {
  23821. point.copy( this.v2 ).sub( this.v1 );
  23822. point.multiplyScalar( t ).add( this.v1 );
  23823. }
  23824. return point;
  23825. };
  23826. // Line curve is linear, so we can overwrite default getPointAt
  23827. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  23828. return this.getPoint( u, optionalTarget );
  23829. };
  23830. LineCurve.prototype.getTangent = function ( /* t */ ) {
  23831. var tangent = this.v2.clone().sub( this.v1 );
  23832. return tangent.normalize();
  23833. };
  23834. LineCurve.prototype.copy = function ( source ) {
  23835. Curve.prototype.copy.call( this, source );
  23836. this.v1.copy( source.v1 );
  23837. this.v2.copy( source.v2 );
  23838. return this;
  23839. };
  23840. LineCurve.prototype.toJSON = function () {
  23841. var data = Curve.prototype.toJSON.call( this );
  23842. data.v1 = this.v1.toArray();
  23843. data.v2 = this.v2.toArray();
  23844. return data;
  23845. };
  23846. LineCurve.prototype.fromJSON = function ( json ) {
  23847. Curve.prototype.fromJSON.call( this, json );
  23848. this.v1.fromArray( json.v1 );
  23849. this.v2.fromArray( json.v2 );
  23850. return this;
  23851. };
  23852. function LineCurve3( v1, v2 ) {
  23853. Curve.call( this );
  23854. this.type = 'LineCurve3';
  23855. this.v1 = v1 || new Vector3();
  23856. this.v2 = v2 || new Vector3();
  23857. }
  23858. LineCurve3.prototype = Object.create( Curve.prototype );
  23859. LineCurve3.prototype.constructor = LineCurve3;
  23860. LineCurve3.prototype.isLineCurve3 = true;
  23861. LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23862. var point = optionalTarget || new Vector3();
  23863. if ( t === 1 ) {
  23864. point.copy( this.v2 );
  23865. } else {
  23866. point.copy( this.v2 ).sub( this.v1 );
  23867. point.multiplyScalar( t ).add( this.v1 );
  23868. }
  23869. return point;
  23870. };
  23871. // Line curve is linear, so we can overwrite default getPointAt
  23872. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  23873. return this.getPoint( u, optionalTarget );
  23874. };
  23875. LineCurve3.prototype.copy = function ( source ) {
  23876. Curve.prototype.copy.call( this, source );
  23877. this.v1.copy( source.v1 );
  23878. this.v2.copy( source.v2 );
  23879. return this;
  23880. };
  23881. LineCurve3.prototype.toJSON = function () {
  23882. var data = Curve.prototype.toJSON.call( this );
  23883. data.v1 = this.v1.toArray();
  23884. data.v2 = this.v2.toArray();
  23885. return data;
  23886. };
  23887. LineCurve3.prototype.fromJSON = function ( json ) {
  23888. Curve.prototype.fromJSON.call( this, json );
  23889. this.v1.fromArray( json.v1 );
  23890. this.v2.fromArray( json.v2 );
  23891. return this;
  23892. };
  23893. function QuadraticBezierCurve( v0, v1, v2 ) {
  23894. Curve.call( this );
  23895. this.type = 'QuadraticBezierCurve';
  23896. this.v0 = v0 || new Vector2();
  23897. this.v1 = v1 || new Vector2();
  23898. this.v2 = v2 || new Vector2();
  23899. }
  23900. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  23901. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23902. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23903. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23904. var point = optionalTarget || new Vector2();
  23905. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23906. point.set(
  23907. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23908. QuadraticBezier( t, v0.y, v1.y, v2.y )
  23909. );
  23910. return point;
  23911. };
  23912. QuadraticBezierCurve.prototype.copy = function ( source ) {
  23913. Curve.prototype.copy.call( this, source );
  23914. this.v0.copy( source.v0 );
  23915. this.v1.copy( source.v1 );
  23916. this.v2.copy( source.v2 );
  23917. return this;
  23918. };
  23919. QuadraticBezierCurve.prototype.toJSON = function () {
  23920. var data = Curve.prototype.toJSON.call( this );
  23921. data.v0 = this.v0.toArray();
  23922. data.v1 = this.v1.toArray();
  23923. data.v2 = this.v2.toArray();
  23924. return data;
  23925. };
  23926. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  23927. Curve.prototype.fromJSON.call( this, json );
  23928. this.v0.fromArray( json.v0 );
  23929. this.v1.fromArray( json.v1 );
  23930. this.v2.fromArray( json.v2 );
  23931. return this;
  23932. };
  23933. function QuadraticBezierCurve3( v0, v1, v2 ) {
  23934. Curve.call( this );
  23935. this.type = 'QuadraticBezierCurve3';
  23936. this.v0 = v0 || new Vector3();
  23937. this.v1 = v1 || new Vector3();
  23938. this.v2 = v2 || new Vector3();
  23939. }
  23940. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  23941. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23942. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23943. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23944. var point = optionalTarget || new Vector3();
  23945. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23946. point.set(
  23947. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23948. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  23949. QuadraticBezier( t, v0.z, v1.z, v2.z )
  23950. );
  23951. return point;
  23952. };
  23953. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  23954. Curve.prototype.copy.call( this, source );
  23955. this.v0.copy( source.v0 );
  23956. this.v1.copy( source.v1 );
  23957. this.v2.copy( source.v2 );
  23958. return this;
  23959. };
  23960. QuadraticBezierCurve3.prototype.toJSON = function () {
  23961. var data = Curve.prototype.toJSON.call( this );
  23962. data.v0 = this.v0.toArray();
  23963. data.v1 = this.v1.toArray();
  23964. data.v2 = this.v2.toArray();
  23965. return data;
  23966. };
  23967. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  23968. Curve.prototype.fromJSON.call( this, json );
  23969. this.v0.fromArray( json.v0 );
  23970. this.v1.fromArray( json.v1 );
  23971. this.v2.fromArray( json.v2 );
  23972. return this;
  23973. };
  23974. function SplineCurve( points /* array of Vector2 */ ) {
  23975. Curve.call( this );
  23976. this.type = 'SplineCurve';
  23977. this.points = points || [];
  23978. }
  23979. SplineCurve.prototype = Object.create( Curve.prototype );
  23980. SplineCurve.prototype.constructor = SplineCurve;
  23981. SplineCurve.prototype.isSplineCurve = true;
  23982. SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23983. var point = optionalTarget || new Vector2();
  23984. var points = this.points;
  23985. var p = ( points.length - 1 ) * t;
  23986. var intPoint = Math.floor( p );
  23987. var weight = p - intPoint;
  23988. var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  23989. var p1 = points[ intPoint ];
  23990. var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  23991. var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  23992. point.set(
  23993. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  23994. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  23995. );
  23996. return point;
  23997. };
  23998. SplineCurve.prototype.copy = function ( source ) {
  23999. Curve.prototype.copy.call( this, source );
  24000. this.points = [];
  24001. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  24002. var point = source.points[ i ];
  24003. this.points.push( point.clone() );
  24004. }
  24005. return this;
  24006. };
  24007. SplineCurve.prototype.toJSON = function () {
  24008. var data = Curve.prototype.toJSON.call( this );
  24009. data.points = [];
  24010. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  24011. var point = this.points[ i ];
  24012. data.points.push( point.toArray() );
  24013. }
  24014. return data;
  24015. };
  24016. SplineCurve.prototype.fromJSON = function ( json ) {
  24017. Curve.prototype.fromJSON.call( this, json );
  24018. this.points = [];
  24019. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  24020. var point = json.points[ i ];
  24021. this.points.push( new Vector2().fromArray( point ) );
  24022. }
  24023. return this;
  24024. };
  24025. var Curves = Object.freeze({
  24026. ArcCurve: ArcCurve,
  24027. CatmullRomCurve3: CatmullRomCurve3,
  24028. CubicBezierCurve: CubicBezierCurve,
  24029. CubicBezierCurve3: CubicBezierCurve3,
  24030. EllipseCurve: EllipseCurve,
  24031. LineCurve: LineCurve,
  24032. LineCurve3: LineCurve3,
  24033. QuadraticBezierCurve: QuadraticBezierCurve,
  24034. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24035. SplineCurve: SplineCurve
  24036. });
  24037. /**
  24038. * @author zz85 / http://www.lab4games.net/zz85/blog
  24039. *
  24040. **/
  24041. /**************************************************************
  24042. * Curved Path - a curve path is simply a array of connected
  24043. * curves, but retains the api of a curve
  24044. **************************************************************/
  24045. function CurvePath() {
  24046. Curve.call( this );
  24047. this.type = 'CurvePath';
  24048. this.curves = [];
  24049. this.autoClose = false; // Automatically closes the path
  24050. }
  24051. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  24052. constructor: CurvePath,
  24053. add: function ( curve ) {
  24054. this.curves.push( curve );
  24055. },
  24056. closePath: function () {
  24057. // Add a line curve if start and end of lines are not connected
  24058. var startPoint = this.curves[ 0 ].getPoint( 0 );
  24059. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24060. if ( ! startPoint.equals( endPoint ) ) {
  24061. this.curves.push( new LineCurve( endPoint, startPoint ) );
  24062. }
  24063. },
  24064. // To get accurate point with reference to
  24065. // entire path distance at time t,
  24066. // following has to be done:
  24067. // 1. Length of each sub path have to be known
  24068. // 2. Locate and identify type of curve
  24069. // 3. Get t for the curve
  24070. // 4. Return curve.getPointAt(t')
  24071. getPoint: function ( t ) {
  24072. var d = t * this.getLength();
  24073. var curveLengths = this.getCurveLengths();
  24074. var i = 0;
  24075. // To think about boundaries points.
  24076. while ( i < curveLengths.length ) {
  24077. if ( curveLengths[ i ] >= d ) {
  24078. var diff = curveLengths[ i ] - d;
  24079. var curve = this.curves[ i ];
  24080. var segmentLength = curve.getLength();
  24081. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24082. return curve.getPointAt( u );
  24083. }
  24084. i ++;
  24085. }
  24086. return null;
  24087. // loop where sum != 0, sum > d , sum+1 <d
  24088. },
  24089. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24090. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24091. // getPoint() depends on getLength
  24092. getLength: function () {
  24093. var lens = this.getCurveLengths();
  24094. return lens[ lens.length - 1 ];
  24095. },
  24096. // cacheLengths must be recalculated.
  24097. updateArcLengths: function () {
  24098. this.needsUpdate = true;
  24099. this.cacheLengths = null;
  24100. this.getCurveLengths();
  24101. },
  24102. // Compute lengths and cache them
  24103. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24104. getCurveLengths: function () {
  24105. // We use cache values if curves and cache array are same length
  24106. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24107. return this.cacheLengths;
  24108. }
  24109. // Get length of sub-curve
  24110. // Push sums into cached array
  24111. var lengths = [], sums = 0;
  24112. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  24113. sums += this.curves[ i ].getLength();
  24114. lengths.push( sums );
  24115. }
  24116. this.cacheLengths = lengths;
  24117. return lengths;
  24118. },
  24119. getSpacedPoints: function ( divisions ) {
  24120. if ( divisions === undefined ) divisions = 40;
  24121. var points = [];
  24122. for ( var i = 0; i <= divisions; i ++ ) {
  24123. points.push( this.getPoint( i / divisions ) );
  24124. }
  24125. if ( this.autoClose ) {
  24126. points.push( points[ 0 ] );
  24127. }
  24128. return points;
  24129. },
  24130. getPoints: function ( divisions ) {
  24131. divisions = divisions || 12;
  24132. var points = [], last;
  24133. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24134. var curve = curves[ i ];
  24135. var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  24136. : ( curve && curve.isLineCurve ) ? 1
  24137. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  24138. : divisions;
  24139. var pts = curve.getPoints( resolution );
  24140. for ( var j = 0; j < pts.length; j ++ ) {
  24141. var point = pts[ j ];
  24142. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24143. points.push( point );
  24144. last = point;
  24145. }
  24146. }
  24147. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24148. points.push( points[ 0 ] );
  24149. }
  24150. return points;
  24151. },
  24152. copy: function ( source ) {
  24153. Curve.prototype.copy.call( this, source );
  24154. this.curves = [];
  24155. for ( var i = 0, l = source.curves.length; i < l; i ++ ) {
  24156. var curve = source.curves[ i ];
  24157. this.curves.push( curve.clone() );
  24158. }
  24159. this.autoClose = source.autoClose;
  24160. return this;
  24161. },
  24162. toJSON: function () {
  24163. var data = Curve.prototype.toJSON.call( this );
  24164. data.autoClose = this.autoClose;
  24165. data.curves = [];
  24166. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  24167. var curve = this.curves[ i ];
  24168. data.curves.push( curve.toJSON() );
  24169. }
  24170. return data;
  24171. },
  24172. fromJSON: function ( json ) {
  24173. Curve.prototype.fromJSON.call( this, json );
  24174. this.autoClose = json.autoClose;
  24175. this.curves = [];
  24176. for ( var i = 0, l = json.curves.length; i < l; i ++ ) {
  24177. var curve = json.curves[ i ];
  24178. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24179. }
  24180. return this;
  24181. }
  24182. } );
  24183. /**
  24184. * @author zz85 / http://www.lab4games.net/zz85/blog
  24185. * Creates free form 2d path using series of points, lines or curves.
  24186. **/
  24187. function Path( points ) {
  24188. CurvePath.call( this );
  24189. this.type = 'Path';
  24190. this.currentPoint = new Vector2();
  24191. if ( points ) {
  24192. this.setFromPoints( points );
  24193. }
  24194. }
  24195. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  24196. constructor: Path,
  24197. setFromPoints: function ( points ) {
  24198. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24199. for ( var i = 1, l = points.length; i < l; i ++ ) {
  24200. this.lineTo( points[ i ].x, points[ i ].y );
  24201. }
  24202. },
  24203. moveTo: function ( x, y ) {
  24204. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24205. },
  24206. lineTo: function ( x, y ) {
  24207. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24208. this.curves.push( curve );
  24209. this.currentPoint.set( x, y );
  24210. },
  24211. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  24212. var curve = new QuadraticBezierCurve(
  24213. this.currentPoint.clone(),
  24214. new Vector2( aCPx, aCPy ),
  24215. new Vector2( aX, aY )
  24216. );
  24217. this.curves.push( curve );
  24218. this.currentPoint.set( aX, aY );
  24219. },
  24220. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24221. var curve = new CubicBezierCurve(
  24222. this.currentPoint.clone(),
  24223. new Vector2( aCP1x, aCP1y ),
  24224. new Vector2( aCP2x, aCP2y ),
  24225. new Vector2( aX, aY )
  24226. );
  24227. this.curves.push( curve );
  24228. this.currentPoint.set( aX, aY );
  24229. },
  24230. splineThru: function ( pts /*Array of Vector*/ ) {
  24231. var npts = [ this.currentPoint.clone() ].concat( pts );
  24232. var curve = new SplineCurve( npts );
  24233. this.curves.push( curve );
  24234. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24235. },
  24236. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24237. var x0 = this.currentPoint.x;
  24238. var y0 = this.currentPoint.y;
  24239. this.absarc( aX + x0, aY + y0, aRadius,
  24240. aStartAngle, aEndAngle, aClockwise );
  24241. },
  24242. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24243. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24244. },
  24245. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24246. var x0 = this.currentPoint.x;
  24247. var y0 = this.currentPoint.y;
  24248. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24249. },
  24250. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24251. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24252. if ( this.curves.length > 0 ) {
  24253. // if a previous curve is present, attempt to join
  24254. var firstPoint = curve.getPoint( 0 );
  24255. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24256. this.lineTo( firstPoint.x, firstPoint.y );
  24257. }
  24258. }
  24259. this.curves.push( curve );
  24260. var lastPoint = curve.getPoint( 1 );
  24261. this.currentPoint.copy( lastPoint );
  24262. },
  24263. copy: function ( source ) {
  24264. CurvePath.prototype.copy.call( this, source );
  24265. this.currentPoint.copy( source.currentPoint );
  24266. return this;
  24267. },
  24268. toJSON: function () {
  24269. var data = CurvePath.prototype.toJSON.call( this );
  24270. data.currentPoint = this.currentPoint.toArray();
  24271. return data;
  24272. },
  24273. fromJSON: function ( json ) {
  24274. CurvePath.prototype.fromJSON.call( this, json );
  24275. this.currentPoint.fromArray( json.currentPoint );
  24276. return this;
  24277. }
  24278. } );
  24279. /**
  24280. * @author zz85 / http://www.lab4games.net/zz85/blog
  24281. * Defines a 2d shape plane using paths.
  24282. **/
  24283. // STEP 1 Create a path.
  24284. // STEP 2 Turn path into shape.
  24285. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  24286. // STEP 3a - Extract points from each shape, turn to vertices
  24287. // STEP 3b - Triangulate each shape, add faces.
  24288. function Shape( points ) {
  24289. Path.call( this, points );
  24290. this.uuid = _Math.generateUUID();
  24291. this.type = 'Shape';
  24292. this.holes = [];
  24293. }
  24294. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  24295. constructor: Shape,
  24296. getPointsHoles: function ( divisions ) {
  24297. var holesPts = [];
  24298. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  24299. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24300. }
  24301. return holesPts;
  24302. },
  24303. // get points of shape and holes (keypoints based on segments parameter)
  24304. extractPoints: function ( divisions ) {
  24305. return {
  24306. shape: this.getPoints( divisions ),
  24307. holes: this.getPointsHoles( divisions )
  24308. };
  24309. },
  24310. copy: function ( source ) {
  24311. Path.prototype.copy.call( this, source );
  24312. this.holes = [];
  24313. for ( var i = 0, l = source.holes.length; i < l; i ++ ) {
  24314. var hole = source.holes[ i ];
  24315. this.holes.push( hole.clone() );
  24316. }
  24317. return this;
  24318. },
  24319. toJSON: function () {
  24320. var data = Path.prototype.toJSON.call( this );
  24321. data.uuid = this.uuid;
  24322. data.holes = [];
  24323. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  24324. var hole = this.holes[ i ];
  24325. data.holes.push( hole.toJSON() );
  24326. }
  24327. return data;
  24328. },
  24329. fromJSON: function ( json ) {
  24330. Path.prototype.fromJSON.call( this, json );
  24331. this.uuid = json.uuid;
  24332. this.holes = [];
  24333. for ( var i = 0, l = json.holes.length; i < l; i ++ ) {
  24334. var hole = json.holes[ i ];
  24335. this.holes.push( new Path().fromJSON( hole ) );
  24336. }
  24337. return this;
  24338. }
  24339. } );
  24340. /**
  24341. * @author mrdoob / http://mrdoob.com/
  24342. * @author alteredq / http://alteredqualia.com/
  24343. */
  24344. function Light( color, intensity ) {
  24345. Object3D.call( this );
  24346. this.type = 'Light';
  24347. this.color = new Color( color );
  24348. this.intensity = intensity !== undefined ? intensity : 1;
  24349. this.receiveShadow = undefined;
  24350. }
  24351. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  24352. constructor: Light,
  24353. isLight: true,
  24354. copy: function ( source ) {
  24355. Object3D.prototype.copy.call( this, source );
  24356. this.color.copy( source.color );
  24357. this.intensity = source.intensity;
  24358. return this;
  24359. },
  24360. toJSON: function ( meta ) {
  24361. var data = Object3D.prototype.toJSON.call( this, meta );
  24362. data.object.color = this.color.getHex();
  24363. data.object.intensity = this.intensity;
  24364. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24365. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24366. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24367. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24368. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24369. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24370. return data;
  24371. }
  24372. } );
  24373. /**
  24374. * @author alteredq / http://alteredqualia.com/
  24375. */
  24376. function HemisphereLight( skyColor, groundColor, intensity ) {
  24377. Light.call( this, skyColor, intensity );
  24378. this.type = 'HemisphereLight';
  24379. this.castShadow = undefined;
  24380. this.position.copy( Object3D.DefaultUp );
  24381. this.updateMatrix();
  24382. this.groundColor = new Color( groundColor );
  24383. }
  24384. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24385. constructor: HemisphereLight,
  24386. isHemisphereLight: true,
  24387. copy: function ( source ) {
  24388. Light.prototype.copy.call( this, source );
  24389. this.groundColor.copy( source.groundColor );
  24390. return this;
  24391. }
  24392. } );
  24393. /**
  24394. * @author mrdoob / http://mrdoob.com/
  24395. */
  24396. function LightShadow( camera ) {
  24397. this.camera = camera;
  24398. this.bias = 0;
  24399. this.radius = 1;
  24400. this.mapSize = new Vector2( 512, 512 );
  24401. this.map = null;
  24402. this.matrix = new Matrix4();
  24403. }
  24404. Object.assign( LightShadow.prototype, {
  24405. copy: function ( source ) {
  24406. this.camera = source.camera.clone();
  24407. this.bias = source.bias;
  24408. this.radius = source.radius;
  24409. this.mapSize.copy( source.mapSize );
  24410. return this;
  24411. },
  24412. clone: function () {
  24413. return new this.constructor().copy( this );
  24414. },
  24415. toJSON: function () {
  24416. var object = {};
  24417. if ( this.bias !== 0 ) object.bias = this.bias;
  24418. if ( this.radius !== 1 ) object.radius = this.radius;
  24419. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24420. object.camera = this.camera.toJSON( false ).object;
  24421. delete object.camera.matrix;
  24422. return object;
  24423. }
  24424. } );
  24425. /**
  24426. * @author mrdoob / http://mrdoob.com/
  24427. */
  24428. function SpotLightShadow() {
  24429. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24430. }
  24431. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24432. constructor: SpotLightShadow,
  24433. isSpotLightShadow: true,
  24434. update: function ( light ) {
  24435. var camera = this.camera;
  24436. var fov = _Math.RAD2DEG * 2 * light.angle;
  24437. var aspect = this.mapSize.width / this.mapSize.height;
  24438. var far = light.distance || camera.far;
  24439. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24440. camera.fov = fov;
  24441. camera.aspect = aspect;
  24442. camera.far = far;
  24443. camera.updateProjectionMatrix();
  24444. }
  24445. }
  24446. } );
  24447. /**
  24448. * @author alteredq / http://alteredqualia.com/
  24449. */
  24450. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  24451. Light.call( this, color, intensity );
  24452. this.type = 'SpotLight';
  24453. this.position.copy( Object3D.DefaultUp );
  24454. this.updateMatrix();
  24455. this.target = new Object3D();
  24456. Object.defineProperty( this, 'power', {
  24457. get: function () {
  24458. // intensity = power per solid angle.
  24459. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24460. return this.intensity * Math.PI;
  24461. },
  24462. set: function ( power ) {
  24463. // intensity = power per solid angle.
  24464. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24465. this.intensity = power / Math.PI;
  24466. }
  24467. } );
  24468. this.distance = ( distance !== undefined ) ? distance : 0;
  24469. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  24470. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  24471. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24472. this.shadow = new SpotLightShadow();
  24473. }
  24474. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24475. constructor: SpotLight,
  24476. isSpotLight: true,
  24477. copy: function ( source ) {
  24478. Light.prototype.copy.call( this, source );
  24479. this.distance = source.distance;
  24480. this.angle = source.angle;
  24481. this.penumbra = source.penumbra;
  24482. this.decay = source.decay;
  24483. this.target = source.target.clone();
  24484. this.shadow = source.shadow.clone();
  24485. return this;
  24486. }
  24487. } );
  24488. /**
  24489. * @author mrdoob / http://mrdoob.com/
  24490. */
  24491. function PointLight( color, intensity, distance, decay ) {
  24492. Light.call( this, color, intensity );
  24493. this.type = 'PointLight';
  24494. Object.defineProperty( this, 'power', {
  24495. get: function () {
  24496. // intensity = power per solid angle.
  24497. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24498. return this.intensity * 4 * Math.PI;
  24499. },
  24500. set: function ( power ) {
  24501. // intensity = power per solid angle.
  24502. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24503. this.intensity = power / ( 4 * Math.PI );
  24504. }
  24505. } );
  24506. this.distance = ( distance !== undefined ) ? distance : 0;
  24507. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24508. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24509. }
  24510. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24511. constructor: PointLight,
  24512. isPointLight: true,
  24513. copy: function ( source ) {
  24514. Light.prototype.copy.call( this, source );
  24515. this.distance = source.distance;
  24516. this.decay = source.decay;
  24517. this.shadow = source.shadow.clone();
  24518. return this;
  24519. }
  24520. } );
  24521. /**
  24522. * @author mrdoob / http://mrdoob.com/
  24523. */
  24524. function DirectionalLightShadow( ) {
  24525. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24526. }
  24527. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24528. constructor: DirectionalLightShadow
  24529. } );
  24530. /**
  24531. * @author mrdoob / http://mrdoob.com/
  24532. * @author alteredq / http://alteredqualia.com/
  24533. */
  24534. function DirectionalLight( color, intensity ) {
  24535. Light.call( this, color, intensity );
  24536. this.type = 'DirectionalLight';
  24537. this.position.copy( Object3D.DefaultUp );
  24538. this.updateMatrix();
  24539. this.target = new Object3D();
  24540. this.shadow = new DirectionalLightShadow();
  24541. }
  24542. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24543. constructor: DirectionalLight,
  24544. isDirectionalLight: true,
  24545. copy: function ( source ) {
  24546. Light.prototype.copy.call( this, source );
  24547. this.target = source.target.clone();
  24548. this.shadow = source.shadow.clone();
  24549. return this;
  24550. }
  24551. } );
  24552. /**
  24553. * @author mrdoob / http://mrdoob.com/
  24554. */
  24555. function AmbientLight( color, intensity ) {
  24556. Light.call( this, color, intensity );
  24557. this.type = 'AmbientLight';
  24558. this.castShadow = undefined;
  24559. }
  24560. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24561. constructor: AmbientLight,
  24562. isAmbientLight: true
  24563. } );
  24564. /**
  24565. * @author abelnation / http://github.com/abelnation
  24566. */
  24567. function RectAreaLight( color, intensity, width, height ) {
  24568. Light.call( this, color, intensity );
  24569. this.type = 'RectAreaLight';
  24570. this.width = ( width !== undefined ) ? width : 10;
  24571. this.height = ( height !== undefined ) ? height : 10;
  24572. }
  24573. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24574. constructor: RectAreaLight,
  24575. isRectAreaLight: true,
  24576. copy: function ( source ) {
  24577. Light.prototype.copy.call( this, source );
  24578. this.width = source.width;
  24579. this.height = source.height;
  24580. return this;
  24581. },
  24582. toJSON: function ( meta ) {
  24583. var data = Light.prototype.toJSON.call( this, meta );
  24584. data.object.width = this.width;
  24585. data.object.height = this.height;
  24586. return data;
  24587. }
  24588. } );
  24589. /**
  24590. *
  24591. * A Track that interpolates Strings
  24592. *
  24593. *
  24594. * @author Ben Houston / http://clara.io/
  24595. * @author David Sarno / http://lighthaus.us/
  24596. * @author tschw
  24597. */
  24598. function StringKeyframeTrack( name, times, values, interpolation ) {
  24599. KeyframeTrack.call( this, name, times, values, interpolation );
  24600. }
  24601. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24602. constructor: StringKeyframeTrack,
  24603. ValueTypeName: 'string',
  24604. ValueBufferType: Array,
  24605. DefaultInterpolation: InterpolateDiscrete,
  24606. InterpolantFactoryMethodLinear: undefined,
  24607. InterpolantFactoryMethodSmooth: undefined
  24608. } );
  24609. /**
  24610. *
  24611. * A Track of Boolean keyframe values.
  24612. *
  24613. *
  24614. * @author Ben Houston / http://clara.io/
  24615. * @author David Sarno / http://lighthaus.us/
  24616. * @author tschw
  24617. */
  24618. function BooleanKeyframeTrack( name, times, values ) {
  24619. KeyframeTrack.call( this, name, times, values );
  24620. }
  24621. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24622. constructor: BooleanKeyframeTrack,
  24623. ValueTypeName: 'bool',
  24624. ValueBufferType: Array,
  24625. DefaultInterpolation: InterpolateDiscrete,
  24626. InterpolantFactoryMethodLinear: undefined,
  24627. InterpolantFactoryMethodSmooth: undefined
  24628. // Note: Actually this track could have a optimized / compressed
  24629. // representation of a single value and a custom interpolant that
  24630. // computes "firstValue ^ isOdd( index )".
  24631. } );
  24632. /**
  24633. * Abstract base class of interpolants over parametric samples.
  24634. *
  24635. * The parameter domain is one dimensional, typically the time or a path
  24636. * along a curve defined by the data.
  24637. *
  24638. * The sample values can have any dimensionality and derived classes may
  24639. * apply special interpretations to the data.
  24640. *
  24641. * This class provides the interval seek in a Template Method, deferring
  24642. * the actual interpolation to derived classes.
  24643. *
  24644. * Time complexity is O(1) for linear access crossing at most two points
  24645. * and O(log N) for random access, where N is the number of positions.
  24646. *
  24647. * References:
  24648. *
  24649. * http://www.oodesign.com/template-method-pattern.html
  24650. *
  24651. * @author tschw
  24652. */
  24653. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24654. this.parameterPositions = parameterPositions;
  24655. this._cachedIndex = 0;
  24656. this.resultBuffer = resultBuffer !== undefined ?
  24657. resultBuffer : new sampleValues.constructor( sampleSize );
  24658. this.sampleValues = sampleValues;
  24659. this.valueSize = sampleSize;
  24660. }
  24661. Object.assign( Interpolant.prototype, {
  24662. evaluate: function ( t ) {
  24663. var pp = this.parameterPositions,
  24664. i1 = this._cachedIndex,
  24665. t1 = pp[ i1 ],
  24666. t0 = pp[ i1 - 1 ];
  24667. validate_interval: {
  24668. seek: {
  24669. var right;
  24670. linear_scan: {
  24671. //- See http://jsperf.com/comparison-to-undefined/3
  24672. //- slower code:
  24673. //-
  24674. //- if ( t >= t1 || t1 === undefined ) {
  24675. forward_scan: if ( ! ( t < t1 ) ) {
  24676. for ( var giveUpAt = i1 + 2; ; ) {
  24677. if ( t1 === undefined ) {
  24678. if ( t < t0 ) break forward_scan;
  24679. // after end
  24680. i1 = pp.length;
  24681. this._cachedIndex = i1;
  24682. return this.afterEnd_( i1 - 1, t, t0 );
  24683. }
  24684. if ( i1 === giveUpAt ) break; // this loop
  24685. t0 = t1;
  24686. t1 = pp[ ++ i1 ];
  24687. if ( t < t1 ) {
  24688. // we have arrived at the sought interval
  24689. break seek;
  24690. }
  24691. }
  24692. // prepare binary search on the right side of the index
  24693. right = pp.length;
  24694. break linear_scan;
  24695. }
  24696. //- slower code:
  24697. //- if ( t < t0 || t0 === undefined ) {
  24698. if ( ! ( t >= t0 ) ) {
  24699. // looping?
  24700. var t1global = pp[ 1 ];
  24701. if ( t < t1global ) {
  24702. i1 = 2; // + 1, using the scan for the details
  24703. t0 = t1global;
  24704. }
  24705. // linear reverse scan
  24706. for ( var giveUpAt = i1 - 2; ; ) {
  24707. if ( t0 === undefined ) {
  24708. // before start
  24709. this._cachedIndex = 0;
  24710. return this.beforeStart_( 0, t, t1 );
  24711. }
  24712. if ( i1 === giveUpAt ) break; // this loop
  24713. t1 = t0;
  24714. t0 = pp[ -- i1 - 1 ];
  24715. if ( t >= t0 ) {
  24716. // we have arrived at the sought interval
  24717. break seek;
  24718. }
  24719. }
  24720. // prepare binary search on the left side of the index
  24721. right = i1;
  24722. i1 = 0;
  24723. break linear_scan;
  24724. }
  24725. // the interval is valid
  24726. break validate_interval;
  24727. } // linear scan
  24728. // binary search
  24729. while ( i1 < right ) {
  24730. var mid = ( i1 + right ) >>> 1;
  24731. if ( t < pp[ mid ] ) {
  24732. right = mid;
  24733. } else {
  24734. i1 = mid + 1;
  24735. }
  24736. }
  24737. t1 = pp[ i1 ];
  24738. t0 = pp[ i1 - 1 ];
  24739. // check boundary cases, again
  24740. if ( t0 === undefined ) {
  24741. this._cachedIndex = 0;
  24742. return this.beforeStart_( 0, t, t1 );
  24743. }
  24744. if ( t1 === undefined ) {
  24745. i1 = pp.length;
  24746. this._cachedIndex = i1;
  24747. return this.afterEnd_( i1 - 1, t0, t );
  24748. }
  24749. } // seek
  24750. this._cachedIndex = i1;
  24751. this.intervalChanged_( i1, t0, t1 );
  24752. } // validate_interval
  24753. return this.interpolate_( i1, t0, t, t1 );
  24754. },
  24755. settings: null, // optional, subclass-specific settings structure
  24756. // Note: The indirection allows central control of many interpolants.
  24757. // --- Protected interface
  24758. DefaultSettings_: {},
  24759. getSettings_: function () {
  24760. return this.settings || this.DefaultSettings_;
  24761. },
  24762. copySampleValue_: function ( index ) {
  24763. // copies a sample value to the result buffer
  24764. var result = this.resultBuffer,
  24765. values = this.sampleValues,
  24766. stride = this.valueSize,
  24767. offset = index * stride;
  24768. for ( var i = 0; i !== stride; ++ i ) {
  24769. result[ i ] = values[ offset + i ];
  24770. }
  24771. return result;
  24772. },
  24773. // Template methods for derived classes:
  24774. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  24775. throw new Error( 'call to abstract method' );
  24776. // implementations shall return this.resultBuffer
  24777. },
  24778. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  24779. // empty
  24780. }
  24781. } );
  24782. //!\ DECLARE ALIAS AFTER assign prototype !
  24783. Object.assign( Interpolant.prototype, {
  24784. //( 0, t, t0 ), returns this.resultBuffer
  24785. beforeStart_: Interpolant.prototype.copySampleValue_,
  24786. //( N-1, tN-1, t ), returns this.resultBuffer
  24787. afterEnd_: Interpolant.prototype.copySampleValue_,
  24788. } );
  24789. /**
  24790. * Spherical linear unit quaternion interpolant.
  24791. *
  24792. * @author tschw
  24793. */
  24794. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24795. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24796. }
  24797. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24798. constructor: QuaternionLinearInterpolant,
  24799. interpolate_: function ( i1, t0, t, t1 ) {
  24800. var result = this.resultBuffer,
  24801. values = this.sampleValues,
  24802. stride = this.valueSize,
  24803. offset = i1 * stride,
  24804. alpha = ( t - t0 ) / ( t1 - t0 );
  24805. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  24806. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  24807. }
  24808. return result;
  24809. }
  24810. } );
  24811. /**
  24812. *
  24813. * A Track of quaternion keyframe values.
  24814. *
  24815. * @author Ben Houston / http://clara.io/
  24816. * @author David Sarno / http://lighthaus.us/
  24817. * @author tschw
  24818. */
  24819. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  24820. KeyframeTrack.call( this, name, times, values, interpolation );
  24821. }
  24822. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24823. constructor: QuaternionKeyframeTrack,
  24824. ValueTypeName: 'quaternion',
  24825. // ValueBufferType is inherited
  24826. DefaultInterpolation: InterpolateLinear,
  24827. InterpolantFactoryMethodLinear: function ( result ) {
  24828. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24829. },
  24830. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  24831. } );
  24832. /**
  24833. *
  24834. * A Track of keyframe values that represent color.
  24835. *
  24836. *
  24837. * @author Ben Houston / http://clara.io/
  24838. * @author David Sarno / http://lighthaus.us/
  24839. * @author tschw
  24840. */
  24841. function ColorKeyframeTrack( name, times, values, interpolation ) {
  24842. KeyframeTrack.call( this, name, times, values, interpolation );
  24843. }
  24844. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24845. constructor: ColorKeyframeTrack,
  24846. ValueTypeName: 'color'
  24847. // ValueBufferType is inherited
  24848. // DefaultInterpolation is inherited
  24849. // Note: Very basic implementation and nothing special yet.
  24850. // However, this is the place for color space parameterization.
  24851. } );
  24852. /**
  24853. *
  24854. * A Track of numeric keyframe values.
  24855. *
  24856. * @author Ben Houston / http://clara.io/
  24857. * @author David Sarno / http://lighthaus.us/
  24858. * @author tschw
  24859. */
  24860. function NumberKeyframeTrack( name, times, values, interpolation ) {
  24861. KeyframeTrack.call( this, name, times, values, interpolation );
  24862. }
  24863. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24864. constructor: NumberKeyframeTrack,
  24865. ValueTypeName: 'number'
  24866. // ValueBufferType is inherited
  24867. // DefaultInterpolation is inherited
  24868. } );
  24869. /**
  24870. * Fast and simple cubic spline interpolant.
  24871. *
  24872. * It was derived from a Hermitian construction setting the first derivative
  24873. * at each sample position to the linear slope between neighboring positions
  24874. * over their parameter interval.
  24875. *
  24876. * @author tschw
  24877. */
  24878. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24879. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24880. this._weightPrev = - 0;
  24881. this._offsetPrev = - 0;
  24882. this._weightNext = - 0;
  24883. this._offsetNext = - 0;
  24884. }
  24885. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24886. constructor: CubicInterpolant,
  24887. DefaultSettings_: {
  24888. endingStart: ZeroCurvatureEnding,
  24889. endingEnd: ZeroCurvatureEnding
  24890. },
  24891. intervalChanged_: function ( i1, t0, t1 ) {
  24892. var pp = this.parameterPositions,
  24893. iPrev = i1 - 2,
  24894. iNext = i1 + 1,
  24895. tPrev = pp[ iPrev ],
  24896. tNext = pp[ iNext ];
  24897. if ( tPrev === undefined ) {
  24898. switch ( this.getSettings_().endingStart ) {
  24899. case ZeroSlopeEnding:
  24900. // f'(t0) = 0
  24901. iPrev = i1;
  24902. tPrev = 2 * t0 - t1;
  24903. break;
  24904. case WrapAroundEnding:
  24905. // use the other end of the curve
  24906. iPrev = pp.length - 2;
  24907. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  24908. break;
  24909. default: // ZeroCurvatureEnding
  24910. // f''(t0) = 0 a.k.a. Natural Spline
  24911. iPrev = i1;
  24912. tPrev = t1;
  24913. }
  24914. }
  24915. if ( tNext === undefined ) {
  24916. switch ( this.getSettings_().endingEnd ) {
  24917. case ZeroSlopeEnding:
  24918. // f'(tN) = 0
  24919. iNext = i1;
  24920. tNext = 2 * t1 - t0;
  24921. break;
  24922. case WrapAroundEnding:
  24923. // use the other end of the curve
  24924. iNext = 1;
  24925. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  24926. break;
  24927. default: // ZeroCurvatureEnding
  24928. // f''(tN) = 0, a.k.a. Natural Spline
  24929. iNext = i1 - 1;
  24930. tNext = t0;
  24931. }
  24932. }
  24933. var halfDt = ( t1 - t0 ) * 0.5,
  24934. stride = this.valueSize;
  24935. this._weightPrev = halfDt / ( t0 - tPrev );
  24936. this._weightNext = halfDt / ( tNext - t1 );
  24937. this._offsetPrev = iPrev * stride;
  24938. this._offsetNext = iNext * stride;
  24939. },
  24940. interpolate_: function ( i1, t0, t, t1 ) {
  24941. var result = this.resultBuffer,
  24942. values = this.sampleValues,
  24943. stride = this.valueSize,
  24944. o1 = i1 * stride, o0 = o1 - stride,
  24945. oP = this._offsetPrev, oN = this._offsetNext,
  24946. wP = this._weightPrev, wN = this._weightNext,
  24947. p = ( t - t0 ) / ( t1 - t0 ),
  24948. pp = p * p,
  24949. ppp = pp * p;
  24950. // evaluate polynomials
  24951. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  24952. var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  24953. var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  24954. var sN = wN * ppp - wN * pp;
  24955. // combine data linearly
  24956. for ( var i = 0; i !== stride; ++ i ) {
  24957. result[ i ] =
  24958. sP * values[ oP + i ] +
  24959. s0 * values[ o0 + i ] +
  24960. s1 * values[ o1 + i ] +
  24961. sN * values[ oN + i ];
  24962. }
  24963. return result;
  24964. }
  24965. } );
  24966. /**
  24967. * @author tschw
  24968. */
  24969. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24970. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24971. }
  24972. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24973. constructor: LinearInterpolant,
  24974. interpolate_: function ( i1, t0, t, t1 ) {
  24975. var result = this.resultBuffer,
  24976. values = this.sampleValues,
  24977. stride = this.valueSize,
  24978. offset1 = i1 * stride,
  24979. offset0 = offset1 - stride,
  24980. weight1 = ( t - t0 ) / ( t1 - t0 ),
  24981. weight0 = 1 - weight1;
  24982. for ( var i = 0; i !== stride; ++ i ) {
  24983. result[ i ] =
  24984. values[ offset0 + i ] * weight0 +
  24985. values[ offset1 + i ] * weight1;
  24986. }
  24987. return result;
  24988. }
  24989. } );
  24990. /**
  24991. *
  24992. * Interpolant that evaluates to the sample value at the position preceeding
  24993. * the parameter.
  24994. *
  24995. * @author tschw
  24996. */
  24997. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24998. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24999. }
  25000. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  25001. constructor: DiscreteInterpolant,
  25002. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  25003. return this.copySampleValue_( i1 - 1 );
  25004. }
  25005. } );
  25006. /**
  25007. * @author tschw
  25008. * @author Ben Houston / http://clara.io/
  25009. * @author David Sarno / http://lighthaus.us/
  25010. */
  25011. var AnimationUtils = {
  25012. // same as Array.prototype.slice, but also works on typed arrays
  25013. arraySlice: function ( array, from, to ) {
  25014. if ( AnimationUtils.isTypedArray( array ) ) {
  25015. // in ios9 array.subarray(from, undefined) will return empty array
  25016. // but array.subarray(from) or array.subarray(from, len) is correct
  25017. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  25018. }
  25019. return array.slice( from, to );
  25020. },
  25021. // converts an array to a specific type
  25022. convertArray: function ( array, type, forceClone ) {
  25023. if ( ! array || // let 'undefined' and 'null' pass
  25024. ! forceClone && array.constructor === type ) return array;
  25025. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  25026. return new type( array ); // create typed array
  25027. }
  25028. return Array.prototype.slice.call( array ); // create Array
  25029. },
  25030. isTypedArray: function ( object ) {
  25031. return ArrayBuffer.isView( object ) &&
  25032. ! ( object instanceof DataView );
  25033. },
  25034. // returns an array by which times and values can be sorted
  25035. getKeyframeOrder: function ( times ) {
  25036. function compareTime( i, j ) {
  25037. return times[ i ] - times[ j ];
  25038. }
  25039. var n = times.length;
  25040. var result = new Array( n );
  25041. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  25042. result.sort( compareTime );
  25043. return result;
  25044. },
  25045. // uses the array previously returned by 'getKeyframeOrder' to sort data
  25046. sortedArray: function ( values, stride, order ) {
  25047. var nValues = values.length;
  25048. var result = new values.constructor( nValues );
  25049. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  25050. var srcOffset = order[ i ] * stride;
  25051. for ( var j = 0; j !== stride; ++ j ) {
  25052. result[ dstOffset ++ ] = values[ srcOffset + j ];
  25053. }
  25054. }
  25055. return result;
  25056. },
  25057. // function for parsing AOS keyframe formats
  25058. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  25059. var i = 1, key = jsonKeys[ 0 ];
  25060. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  25061. key = jsonKeys[ i ++ ];
  25062. }
  25063. if ( key === undefined ) return; // no data
  25064. var value = key[ valuePropertyName ];
  25065. if ( value === undefined ) return; // no data
  25066. if ( Array.isArray( value ) ) {
  25067. do {
  25068. value = key[ valuePropertyName ];
  25069. if ( value !== undefined ) {
  25070. times.push( key.time );
  25071. values.push.apply( values, value ); // push all elements
  25072. }
  25073. key = jsonKeys[ i ++ ];
  25074. } while ( key !== undefined );
  25075. } else if ( value.toArray !== undefined ) {
  25076. // ...assume THREE.Math-ish
  25077. do {
  25078. value = key[ valuePropertyName ];
  25079. if ( value !== undefined ) {
  25080. times.push( key.time );
  25081. value.toArray( values, values.length );
  25082. }
  25083. key = jsonKeys[ i ++ ];
  25084. } while ( key !== undefined );
  25085. } else {
  25086. // otherwise push as-is
  25087. do {
  25088. value = key[ valuePropertyName ];
  25089. if ( value !== undefined ) {
  25090. times.push( key.time );
  25091. values.push( value );
  25092. }
  25093. key = jsonKeys[ i ++ ];
  25094. } while ( key !== undefined );
  25095. }
  25096. }
  25097. };
  25098. /**
  25099. *
  25100. * A timed sequence of keyframes for a specific property.
  25101. *
  25102. *
  25103. * @author Ben Houston / http://clara.io/
  25104. * @author David Sarno / http://lighthaus.us/
  25105. * @author tschw
  25106. */
  25107. function KeyframeTrack( name, times, values, interpolation ) {
  25108. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  25109. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  25110. this.name = name;
  25111. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  25112. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  25113. this.setInterpolation( interpolation || this.DefaultInterpolation );
  25114. this.validate();
  25115. this.optimize();
  25116. }
  25117. // Static methods:
  25118. Object.assign( KeyframeTrack, {
  25119. // Serialization (in static context, because of constructor invocation
  25120. // and automatic invocation of .toJSON):
  25121. parse: function ( json ) {
  25122. if ( json.type === undefined ) {
  25123. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  25124. }
  25125. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  25126. if ( json.times === undefined ) {
  25127. var times = [], values = [];
  25128. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  25129. json.times = times;
  25130. json.values = values;
  25131. }
  25132. // derived classes can define a static parse method
  25133. if ( trackType.parse !== undefined ) {
  25134. return trackType.parse( json );
  25135. } else {
  25136. // by default, we assume a constructor compatible with the base
  25137. return new trackType( json.name, json.times, json.values, json.interpolation );
  25138. }
  25139. },
  25140. toJSON: function ( track ) {
  25141. var trackType = track.constructor;
  25142. var json;
  25143. // derived classes can define a static toJSON method
  25144. if ( trackType.toJSON !== undefined ) {
  25145. json = trackType.toJSON( track );
  25146. } else {
  25147. // by default, we assume the data can be serialized as-is
  25148. json = {
  25149. 'name': track.name,
  25150. 'times': AnimationUtils.convertArray( track.times, Array ),
  25151. 'values': AnimationUtils.convertArray( track.values, Array )
  25152. };
  25153. var interpolation = track.getInterpolation();
  25154. if ( interpolation !== track.DefaultInterpolation ) {
  25155. json.interpolation = interpolation;
  25156. }
  25157. }
  25158. json.type = track.ValueTypeName; // mandatory
  25159. return json;
  25160. },
  25161. _getTrackTypeForValueTypeName: function ( typeName ) {
  25162. switch ( typeName.toLowerCase() ) {
  25163. case 'scalar':
  25164. case 'double':
  25165. case 'float':
  25166. case 'number':
  25167. case 'integer':
  25168. return NumberKeyframeTrack;
  25169. case 'vector':
  25170. case 'vector2':
  25171. case 'vector3':
  25172. case 'vector4':
  25173. return VectorKeyframeTrack;
  25174. case 'color':
  25175. return ColorKeyframeTrack;
  25176. case 'quaternion':
  25177. return QuaternionKeyframeTrack;
  25178. case 'bool':
  25179. case 'boolean':
  25180. return BooleanKeyframeTrack;
  25181. case 'string':
  25182. return StringKeyframeTrack;
  25183. }
  25184. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  25185. }
  25186. } );
  25187. Object.assign( KeyframeTrack.prototype, {
  25188. constructor: KeyframeTrack,
  25189. TimeBufferType: Float32Array,
  25190. ValueBufferType: Float32Array,
  25191. DefaultInterpolation: InterpolateLinear,
  25192. InterpolantFactoryMethodDiscrete: function ( result ) {
  25193. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  25194. },
  25195. InterpolantFactoryMethodLinear: function ( result ) {
  25196. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25197. },
  25198. InterpolantFactoryMethodSmooth: function ( result ) {
  25199. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  25200. },
  25201. setInterpolation: function ( interpolation ) {
  25202. var factoryMethod;
  25203. switch ( interpolation ) {
  25204. case InterpolateDiscrete:
  25205. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  25206. break;
  25207. case InterpolateLinear:
  25208. factoryMethod = this.InterpolantFactoryMethodLinear;
  25209. break;
  25210. case InterpolateSmooth:
  25211. factoryMethod = this.InterpolantFactoryMethodSmooth;
  25212. break;
  25213. }
  25214. if ( factoryMethod === undefined ) {
  25215. var message = "unsupported interpolation for " +
  25216. this.ValueTypeName + " keyframe track named " + this.name;
  25217. if ( this.createInterpolant === undefined ) {
  25218. // fall back to default, unless the default itself is messed up
  25219. if ( interpolation !== this.DefaultInterpolation ) {
  25220. this.setInterpolation( this.DefaultInterpolation );
  25221. } else {
  25222. throw new Error( message ); // fatal, in this case
  25223. }
  25224. }
  25225. console.warn( 'THREE.KeyframeTrack:', message );
  25226. return;
  25227. }
  25228. this.createInterpolant = factoryMethod;
  25229. },
  25230. getInterpolation: function () {
  25231. switch ( this.createInterpolant ) {
  25232. case this.InterpolantFactoryMethodDiscrete:
  25233. return InterpolateDiscrete;
  25234. case this.InterpolantFactoryMethodLinear:
  25235. return InterpolateLinear;
  25236. case this.InterpolantFactoryMethodSmooth:
  25237. return InterpolateSmooth;
  25238. }
  25239. },
  25240. getValueSize: function () {
  25241. return this.values.length / this.times.length;
  25242. },
  25243. // move all keyframes either forwards or backwards in time
  25244. shift: function ( timeOffset ) {
  25245. if ( timeOffset !== 0.0 ) {
  25246. var times = this.times;
  25247. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  25248. times[ i ] += timeOffset;
  25249. }
  25250. }
  25251. return this;
  25252. },
  25253. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  25254. scale: function ( timeScale ) {
  25255. if ( timeScale !== 1.0 ) {
  25256. var times = this.times;
  25257. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  25258. times[ i ] *= timeScale;
  25259. }
  25260. }
  25261. return this;
  25262. },
  25263. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  25264. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  25265. trim: function ( startTime, endTime ) {
  25266. var times = this.times,
  25267. nKeys = times.length,
  25268. from = 0,
  25269. to = nKeys - 1;
  25270. while ( from !== nKeys && times[ from ] < startTime ) {
  25271. ++ from;
  25272. }
  25273. while ( to !== - 1 && times[ to ] > endTime ) {
  25274. -- to;
  25275. }
  25276. ++ to; // inclusive -> exclusive bound
  25277. if ( from !== 0 || to !== nKeys ) {
  25278. // empty tracks are forbidden, so keep at least one keyframe
  25279. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  25280. var stride = this.getValueSize();
  25281. this.times = AnimationUtils.arraySlice( times, from, to );
  25282. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  25283. }
  25284. return this;
  25285. },
  25286. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  25287. validate: function () {
  25288. var valid = true;
  25289. var valueSize = this.getValueSize();
  25290. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  25291. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  25292. valid = false;
  25293. }
  25294. var times = this.times,
  25295. values = this.values,
  25296. nKeys = times.length;
  25297. if ( nKeys === 0 ) {
  25298. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  25299. valid = false;
  25300. }
  25301. var prevTime = null;
  25302. for ( var i = 0; i !== nKeys; i ++ ) {
  25303. var currTime = times[ i ];
  25304. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  25305. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  25306. valid = false;
  25307. break;
  25308. }
  25309. if ( prevTime !== null && prevTime > currTime ) {
  25310. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  25311. valid = false;
  25312. break;
  25313. }
  25314. prevTime = currTime;
  25315. }
  25316. if ( values !== undefined ) {
  25317. if ( AnimationUtils.isTypedArray( values ) ) {
  25318. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  25319. var value = values[ i ];
  25320. if ( isNaN( value ) ) {
  25321. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  25322. valid = false;
  25323. break;
  25324. }
  25325. }
  25326. }
  25327. }
  25328. return valid;
  25329. },
  25330. // removes equivalent sequential keys as common in morph target sequences
  25331. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  25332. optimize: function () {
  25333. var times = this.times,
  25334. values = this.values,
  25335. stride = this.getValueSize(),
  25336. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  25337. writeIndex = 1,
  25338. lastIndex = times.length - 1;
  25339. for ( var i = 1; i < lastIndex; ++ i ) {
  25340. var keep = false;
  25341. var time = times[ i ];
  25342. var timeNext = times[ i + 1 ];
  25343. // remove adjacent keyframes scheduled at the same time
  25344. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  25345. if ( ! smoothInterpolation ) {
  25346. // remove unnecessary keyframes same as their neighbors
  25347. var offset = i * stride,
  25348. offsetP = offset - stride,
  25349. offsetN = offset + stride;
  25350. for ( var j = 0; j !== stride; ++ j ) {
  25351. var value = values[ offset + j ];
  25352. if ( value !== values[ offsetP + j ] ||
  25353. value !== values[ offsetN + j ] ) {
  25354. keep = true;
  25355. break;
  25356. }
  25357. }
  25358. } else {
  25359. keep = true;
  25360. }
  25361. }
  25362. // in-place compaction
  25363. if ( keep ) {
  25364. if ( i !== writeIndex ) {
  25365. times[ writeIndex ] = times[ i ];
  25366. var readOffset = i * stride,
  25367. writeOffset = writeIndex * stride;
  25368. for ( var j = 0; j !== stride; ++ j ) {
  25369. values[ writeOffset + j ] = values[ readOffset + j ];
  25370. }
  25371. }
  25372. ++ writeIndex;
  25373. }
  25374. }
  25375. // flush last keyframe (compaction looks ahead)
  25376. if ( lastIndex > 0 ) {
  25377. times[ writeIndex ] = times[ lastIndex ];
  25378. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  25379. values[ writeOffset + j ] = values[ readOffset + j ];
  25380. }
  25381. ++ writeIndex;
  25382. }
  25383. if ( writeIndex !== times.length ) {
  25384. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  25385. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  25386. }
  25387. return this;
  25388. }
  25389. } );
  25390. /**
  25391. *
  25392. * A Track of vectored keyframe values.
  25393. *
  25394. *
  25395. * @author Ben Houston / http://clara.io/
  25396. * @author David Sarno / http://lighthaus.us/
  25397. * @author tschw
  25398. */
  25399. function VectorKeyframeTrack( name, times, values, interpolation ) {
  25400. KeyframeTrack.call( this, name, times, values, interpolation );
  25401. }
  25402. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  25403. constructor: VectorKeyframeTrack,
  25404. ValueTypeName: 'vector'
  25405. // ValueBufferType is inherited
  25406. // DefaultInterpolation is inherited
  25407. } );
  25408. /**
  25409. *
  25410. * Reusable set of Tracks that represent an animation.
  25411. *
  25412. * @author Ben Houston / http://clara.io/
  25413. * @author David Sarno / http://lighthaus.us/
  25414. */
  25415. function AnimationClip( name, duration, tracks ) {
  25416. this.name = name;
  25417. this.tracks = tracks;
  25418. this.duration = ( duration !== undefined ) ? duration : - 1;
  25419. this.uuid = _Math.generateUUID();
  25420. // this means it should figure out its duration by scanning the tracks
  25421. if ( this.duration < 0 ) {
  25422. this.resetDuration();
  25423. }
  25424. this.optimize();
  25425. }
  25426. Object.assign( AnimationClip, {
  25427. parse: function ( json ) {
  25428. var tracks = [],
  25429. jsonTracks = json.tracks,
  25430. frameTime = 1.0 / ( json.fps || 1.0 );
  25431. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  25432. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  25433. }
  25434. return new AnimationClip( json.name, json.duration, tracks );
  25435. },
  25436. toJSON: function ( clip ) {
  25437. var tracks = [],
  25438. clipTracks = clip.tracks;
  25439. var json = {
  25440. 'name': clip.name,
  25441. 'duration': clip.duration,
  25442. 'tracks': tracks
  25443. };
  25444. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25445. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25446. }
  25447. return json;
  25448. },
  25449. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  25450. var numMorphTargets = morphTargetSequence.length;
  25451. var tracks = [];
  25452. for ( var i = 0; i < numMorphTargets; i ++ ) {
  25453. var times = [];
  25454. var values = [];
  25455. times.push(
  25456. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25457. i,
  25458. ( i + 1 ) % numMorphTargets );
  25459. values.push( 0, 1, 0 );
  25460. var order = AnimationUtils.getKeyframeOrder( times );
  25461. times = AnimationUtils.sortedArray( times, 1, order );
  25462. values = AnimationUtils.sortedArray( values, 1, order );
  25463. // if there is a key at the first frame, duplicate it as the
  25464. // last frame as well for perfect loop.
  25465. if ( ! noLoop && times[ 0 ] === 0 ) {
  25466. times.push( numMorphTargets );
  25467. values.push( values[ 0 ] );
  25468. }
  25469. tracks.push(
  25470. new NumberKeyframeTrack(
  25471. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25472. times, values
  25473. ).scale( 1.0 / fps ) );
  25474. }
  25475. return new AnimationClip( name, - 1, tracks );
  25476. },
  25477. findByName: function ( objectOrClipArray, name ) {
  25478. var clipArray = objectOrClipArray;
  25479. if ( ! Array.isArray( objectOrClipArray ) ) {
  25480. var o = objectOrClipArray;
  25481. clipArray = o.geometry && o.geometry.animations || o.animations;
  25482. }
  25483. for ( var i = 0; i < clipArray.length; i ++ ) {
  25484. if ( clipArray[ i ].name === name ) {
  25485. return clipArray[ i ];
  25486. }
  25487. }
  25488. return null;
  25489. },
  25490. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  25491. var animationToMorphTargets = {};
  25492. // tested with https://regex101.com/ on trick sequences
  25493. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25494. var pattern = /^([\w-]*?)([\d]+)$/;
  25495. // sort morph target names into animation groups based
  25496. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25497. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  25498. var morphTarget = morphTargets[ i ];
  25499. var parts = morphTarget.name.match( pattern );
  25500. if ( parts && parts.length > 1 ) {
  25501. var name = parts[ 1 ];
  25502. var animationMorphTargets = animationToMorphTargets[ name ];
  25503. if ( ! animationMorphTargets ) {
  25504. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25505. }
  25506. animationMorphTargets.push( morphTarget );
  25507. }
  25508. }
  25509. var clips = [];
  25510. for ( var name in animationToMorphTargets ) {
  25511. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25512. }
  25513. return clips;
  25514. },
  25515. // parse the animation.hierarchy format
  25516. parseAnimation: function ( animation, bones ) {
  25517. if ( ! animation ) {
  25518. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25519. return null;
  25520. }
  25521. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25522. // only return track if there are actually keys.
  25523. if ( animationKeys.length !== 0 ) {
  25524. var times = [];
  25525. var values = [];
  25526. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  25527. // empty keys are filtered out, so check again
  25528. if ( times.length !== 0 ) {
  25529. destTracks.push( new trackType( trackName, times, values ) );
  25530. }
  25531. }
  25532. };
  25533. var tracks = [];
  25534. var clipName = animation.name || 'default';
  25535. // automatic length determination in AnimationClip.
  25536. var duration = animation.length || - 1;
  25537. var fps = animation.fps || 30;
  25538. var hierarchyTracks = animation.hierarchy || [];
  25539. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  25540. var animationKeys = hierarchyTracks[ h ].keys;
  25541. // skip empty tracks
  25542. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25543. // process morph targets
  25544. if ( animationKeys[ 0 ].morphTargets ) {
  25545. // figure out all morph targets used in this track
  25546. var morphTargetNames = {};
  25547. for ( var k = 0; k < animationKeys.length; k ++ ) {
  25548. if ( animationKeys[ k ].morphTargets ) {
  25549. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25550. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25551. }
  25552. }
  25553. }
  25554. // create a track for each morph target with all zero
  25555. // morphTargetInfluences except for the keys in which
  25556. // the morphTarget is named.
  25557. for ( var morphTargetName in morphTargetNames ) {
  25558. var times = [];
  25559. var values = [];
  25560. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  25561. var animationKey = animationKeys[ k ];
  25562. times.push( animationKey.time );
  25563. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  25564. }
  25565. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  25566. }
  25567. duration = morphTargetNames.length * ( fps || 1.0 );
  25568. } else {
  25569. // ...assume skeletal animation
  25570. var boneName = '.bones[' + bones[ h ].name + ']';
  25571. addNonemptyTrack(
  25572. VectorKeyframeTrack, boneName + '.position',
  25573. animationKeys, 'pos', tracks );
  25574. addNonemptyTrack(
  25575. QuaternionKeyframeTrack, boneName + '.quaternion',
  25576. animationKeys, 'rot', tracks );
  25577. addNonemptyTrack(
  25578. VectorKeyframeTrack, boneName + '.scale',
  25579. animationKeys, 'scl', tracks );
  25580. }
  25581. }
  25582. if ( tracks.length === 0 ) {
  25583. return null;
  25584. }
  25585. var clip = new AnimationClip( clipName, duration, tracks );
  25586. return clip;
  25587. }
  25588. } );
  25589. Object.assign( AnimationClip.prototype, {
  25590. resetDuration: function () {
  25591. var tracks = this.tracks, duration = 0;
  25592. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  25593. var track = this.tracks[ i ];
  25594. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  25595. }
  25596. this.duration = duration;
  25597. },
  25598. trim: function () {
  25599. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25600. this.tracks[ i ].trim( 0, this.duration );
  25601. }
  25602. return this;
  25603. },
  25604. optimize: function () {
  25605. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25606. this.tracks[ i ].optimize();
  25607. }
  25608. return this;
  25609. }
  25610. } );
  25611. /**
  25612. * @author mrdoob / http://mrdoob.com/
  25613. */
  25614. function MaterialLoader( manager ) {
  25615. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25616. this.textures = {};
  25617. }
  25618. Object.assign( MaterialLoader.prototype, {
  25619. load: function ( url, onLoad, onProgress, onError ) {
  25620. var scope = this;
  25621. var loader = new FileLoader( scope.manager );
  25622. loader.load( url, function ( text ) {
  25623. onLoad( scope.parse( JSON.parse( text ) ) );
  25624. }, onProgress, onError );
  25625. },
  25626. setTextures: function ( value ) {
  25627. this.textures = value;
  25628. },
  25629. parse: function ( json ) {
  25630. var textures = this.textures;
  25631. function getTexture( name ) {
  25632. if ( textures[ name ] === undefined ) {
  25633. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25634. }
  25635. return textures[ name ];
  25636. }
  25637. var material = new Materials[ json.type ]();
  25638. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25639. if ( json.name !== undefined ) material.name = json.name;
  25640. if ( json.color !== undefined ) material.color.setHex( json.color );
  25641. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25642. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25643. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25644. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  25645. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25646. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  25647. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  25648. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  25649. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25650. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25651. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  25652. if ( json.fog !== undefined ) material.fog = json.fog;
  25653. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25654. if ( json.blending !== undefined ) material.blending = json.blending;
  25655. if ( json.side !== undefined ) material.side = json.side;
  25656. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25657. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25658. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25659. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25660. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25661. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25662. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25663. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25664. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25665. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25666. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25667. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25668. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25669. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25670. if ( json.scale !== undefined ) material.scale = json.scale;
  25671. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25672. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25673. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25674. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  25675. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  25676. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25677. if ( json.visible !== undefined ) material.visible = json.visible;
  25678. if ( json.userData !== undefined ) material.userData = json.userData;
  25679. // Deprecated
  25680. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  25681. // for PointsMaterial
  25682. if ( json.size !== undefined ) material.size = json.size;
  25683. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25684. // maps
  25685. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25686. if ( json.alphaMap !== undefined ) {
  25687. material.alphaMap = getTexture( json.alphaMap );
  25688. material.transparent = true;
  25689. }
  25690. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25691. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25692. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25693. if ( json.normalScale !== undefined ) {
  25694. var normalScale = json.normalScale;
  25695. if ( Array.isArray( normalScale ) === false ) {
  25696. // Blender exporter used to export a scalar. See #7459
  25697. normalScale = [ normalScale, normalScale ];
  25698. }
  25699. material.normalScale = new Vector2().fromArray( normalScale );
  25700. }
  25701. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25702. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25703. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25704. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25705. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25706. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25707. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25708. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25709. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25710. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25711. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25712. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25713. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25714. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25715. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25716. return material;
  25717. }
  25718. } );
  25719. /**
  25720. * @author mrdoob / http://mrdoob.com/
  25721. */
  25722. function BufferGeometryLoader( manager ) {
  25723. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25724. }
  25725. Object.assign( BufferGeometryLoader.prototype, {
  25726. load: function ( url, onLoad, onProgress, onError ) {
  25727. var scope = this;
  25728. var loader = new FileLoader( scope.manager );
  25729. loader.load( url, function ( text ) {
  25730. onLoad( scope.parse( JSON.parse( text ) ) );
  25731. }, onProgress, onError );
  25732. },
  25733. parse: function ( json ) {
  25734. var geometry = new BufferGeometry();
  25735. var index = json.data.index;
  25736. if ( index !== undefined ) {
  25737. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  25738. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25739. }
  25740. var attributes = json.data.attributes;
  25741. for ( var key in attributes ) {
  25742. var attribute = attributes[ key ];
  25743. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  25744. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  25745. }
  25746. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25747. if ( groups !== undefined ) {
  25748. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  25749. var group = groups[ i ];
  25750. geometry.addGroup( group.start, group.count, group.materialIndex );
  25751. }
  25752. }
  25753. var boundingSphere = json.data.boundingSphere;
  25754. if ( boundingSphere !== undefined ) {
  25755. var center = new Vector3();
  25756. if ( boundingSphere.center !== undefined ) {
  25757. center.fromArray( boundingSphere.center );
  25758. }
  25759. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25760. }
  25761. return geometry;
  25762. }
  25763. } );
  25764. var TYPED_ARRAYS = {
  25765. Int8Array: Int8Array,
  25766. Uint8Array: Uint8Array,
  25767. // Workaround for IE11 pre KB2929437. See #11440
  25768. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  25769. Int16Array: Int16Array,
  25770. Uint16Array: Uint16Array,
  25771. Int32Array: Int32Array,
  25772. Uint32Array: Uint32Array,
  25773. Float32Array: Float32Array,
  25774. Float64Array: Float64Array
  25775. };
  25776. /**
  25777. * @author alteredq / http://alteredqualia.com/
  25778. */
  25779. function Loader() {}
  25780. Loader.Handlers = {
  25781. handlers: [],
  25782. add: function ( regex, loader ) {
  25783. this.handlers.push( regex, loader );
  25784. },
  25785. get: function ( file ) {
  25786. var handlers = this.handlers;
  25787. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  25788. var regex = handlers[ i ];
  25789. var loader = handlers[ i + 1 ];
  25790. if ( regex.test( file ) ) {
  25791. return loader;
  25792. }
  25793. }
  25794. return null;
  25795. }
  25796. };
  25797. Object.assign( Loader.prototype, {
  25798. crossOrigin: undefined,
  25799. onLoadStart: function () {},
  25800. onLoadProgress: function () {},
  25801. onLoadComplete: function () {},
  25802. initMaterials: function ( materials, texturePath, crossOrigin ) {
  25803. var array = [];
  25804. for ( var i = 0; i < materials.length; ++ i ) {
  25805. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  25806. }
  25807. return array;
  25808. },
  25809. createMaterial: ( function () {
  25810. var BlendingMode = {
  25811. NoBlending: NoBlending,
  25812. NormalBlending: NormalBlending,
  25813. AdditiveBlending: AdditiveBlending,
  25814. SubtractiveBlending: SubtractiveBlending,
  25815. MultiplyBlending: MultiplyBlending,
  25816. CustomBlending: CustomBlending
  25817. };
  25818. var color = new Color();
  25819. var textureLoader = new TextureLoader();
  25820. var materialLoader = new MaterialLoader();
  25821. return function createMaterial( m, texturePath, crossOrigin ) {
  25822. // convert from old material format
  25823. var textures = {};
  25824. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  25825. var fullPath = texturePath + path;
  25826. var loader = Loader.Handlers.get( fullPath );
  25827. var texture;
  25828. if ( loader !== null ) {
  25829. texture = loader.load( fullPath );
  25830. } else {
  25831. textureLoader.setCrossOrigin( crossOrigin );
  25832. texture = textureLoader.load( fullPath );
  25833. }
  25834. if ( repeat !== undefined ) {
  25835. texture.repeat.fromArray( repeat );
  25836. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  25837. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  25838. }
  25839. if ( offset !== undefined ) {
  25840. texture.offset.fromArray( offset );
  25841. }
  25842. if ( wrap !== undefined ) {
  25843. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  25844. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  25845. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  25846. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  25847. }
  25848. if ( anisotropy !== undefined ) {
  25849. texture.anisotropy = anisotropy;
  25850. }
  25851. var uuid = _Math.generateUUID();
  25852. textures[ uuid ] = texture;
  25853. return uuid;
  25854. }
  25855. //
  25856. var json = {
  25857. uuid: _Math.generateUUID(),
  25858. type: 'MeshLambertMaterial'
  25859. };
  25860. for ( var name in m ) {
  25861. var value = m[ name ];
  25862. switch ( name ) {
  25863. case 'DbgColor':
  25864. case 'DbgIndex':
  25865. case 'opticalDensity':
  25866. case 'illumination':
  25867. break;
  25868. case 'DbgName':
  25869. json.name = value;
  25870. break;
  25871. case 'blending':
  25872. json.blending = BlendingMode[ value ];
  25873. break;
  25874. case 'colorAmbient':
  25875. case 'mapAmbient':
  25876. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  25877. break;
  25878. case 'colorDiffuse':
  25879. json.color = color.fromArray( value ).getHex();
  25880. break;
  25881. case 'colorSpecular':
  25882. json.specular = color.fromArray( value ).getHex();
  25883. break;
  25884. case 'colorEmissive':
  25885. json.emissive = color.fromArray( value ).getHex();
  25886. break;
  25887. case 'specularCoef':
  25888. json.shininess = value;
  25889. break;
  25890. case 'shading':
  25891. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  25892. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  25893. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  25894. break;
  25895. case 'mapDiffuse':
  25896. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  25897. break;
  25898. case 'mapDiffuseRepeat':
  25899. case 'mapDiffuseOffset':
  25900. case 'mapDiffuseWrap':
  25901. case 'mapDiffuseAnisotropy':
  25902. break;
  25903. case 'mapEmissive':
  25904. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  25905. break;
  25906. case 'mapEmissiveRepeat':
  25907. case 'mapEmissiveOffset':
  25908. case 'mapEmissiveWrap':
  25909. case 'mapEmissiveAnisotropy':
  25910. break;
  25911. case 'mapLight':
  25912. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  25913. break;
  25914. case 'mapLightRepeat':
  25915. case 'mapLightOffset':
  25916. case 'mapLightWrap':
  25917. case 'mapLightAnisotropy':
  25918. break;
  25919. case 'mapAO':
  25920. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  25921. break;
  25922. case 'mapAORepeat':
  25923. case 'mapAOOffset':
  25924. case 'mapAOWrap':
  25925. case 'mapAOAnisotropy':
  25926. break;
  25927. case 'mapBump':
  25928. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  25929. break;
  25930. case 'mapBumpScale':
  25931. json.bumpScale = value;
  25932. break;
  25933. case 'mapBumpRepeat':
  25934. case 'mapBumpOffset':
  25935. case 'mapBumpWrap':
  25936. case 'mapBumpAnisotropy':
  25937. break;
  25938. case 'mapNormal':
  25939. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  25940. break;
  25941. case 'mapNormalFactor':
  25942. json.normalScale = value;
  25943. break;
  25944. case 'mapNormalRepeat':
  25945. case 'mapNormalOffset':
  25946. case 'mapNormalWrap':
  25947. case 'mapNormalAnisotropy':
  25948. break;
  25949. case 'mapSpecular':
  25950. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  25951. break;
  25952. case 'mapSpecularRepeat':
  25953. case 'mapSpecularOffset':
  25954. case 'mapSpecularWrap':
  25955. case 'mapSpecularAnisotropy':
  25956. break;
  25957. case 'mapMetalness':
  25958. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  25959. break;
  25960. case 'mapMetalnessRepeat':
  25961. case 'mapMetalnessOffset':
  25962. case 'mapMetalnessWrap':
  25963. case 'mapMetalnessAnisotropy':
  25964. break;
  25965. case 'mapRoughness':
  25966. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  25967. break;
  25968. case 'mapRoughnessRepeat':
  25969. case 'mapRoughnessOffset':
  25970. case 'mapRoughnessWrap':
  25971. case 'mapRoughnessAnisotropy':
  25972. break;
  25973. case 'mapAlpha':
  25974. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  25975. break;
  25976. case 'mapAlphaRepeat':
  25977. case 'mapAlphaOffset':
  25978. case 'mapAlphaWrap':
  25979. case 'mapAlphaAnisotropy':
  25980. break;
  25981. case 'flipSided':
  25982. json.side = BackSide;
  25983. break;
  25984. case 'doubleSided':
  25985. json.side = DoubleSide;
  25986. break;
  25987. case 'transparency':
  25988. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  25989. json.opacity = value;
  25990. break;
  25991. case 'depthTest':
  25992. case 'depthWrite':
  25993. case 'colorWrite':
  25994. case 'opacity':
  25995. case 'reflectivity':
  25996. case 'transparent':
  25997. case 'visible':
  25998. case 'wireframe':
  25999. json[ name ] = value;
  26000. break;
  26001. case 'vertexColors':
  26002. if ( value === true ) json.vertexColors = VertexColors;
  26003. if ( value === 'face' ) json.vertexColors = FaceColors;
  26004. break;
  26005. default:
  26006. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  26007. break;
  26008. }
  26009. }
  26010. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  26011. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  26012. if ( json.opacity < 1 ) json.transparent = true;
  26013. materialLoader.setTextures( textures );
  26014. return materialLoader.parse( json );
  26015. };
  26016. } )()
  26017. } );
  26018. /**
  26019. * @author Don McCurdy / https://www.donmccurdy.com
  26020. */
  26021. var LoaderUtils = {
  26022. decodeText: function ( array ) {
  26023. if ( typeof TextDecoder !== 'undefined' ) {
  26024. return new TextDecoder().decode( array );
  26025. }
  26026. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  26027. // throws a "maximum call stack size exceeded" error for large arrays.
  26028. var s = '';
  26029. for ( var i = 0, il = array.length; i < il; i ++ ) {
  26030. // Implicitly assumes little-endian.
  26031. s += String.fromCharCode( array[ i ] );
  26032. }
  26033. // Merges multi-byte utf-8 characters.
  26034. return decodeURIComponent( escape( s ) );
  26035. },
  26036. extractUrlBase: function ( url ) {
  26037. var index = url.lastIndexOf( '/' );
  26038. if ( index === - 1 ) return './';
  26039. return url.substr( 0, index + 1 );
  26040. }
  26041. };
  26042. /**
  26043. * @author mrdoob / http://mrdoob.com/
  26044. * @author alteredq / http://alteredqualia.com/
  26045. */
  26046. function JSONLoader( manager ) {
  26047. if ( typeof manager === 'boolean' ) {
  26048. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  26049. manager = undefined;
  26050. }
  26051. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26052. this.withCredentials = false;
  26053. }
  26054. Object.assign( JSONLoader.prototype, {
  26055. load: function ( url, onLoad, onProgress, onError ) {
  26056. var scope = this;
  26057. var texturePath = this.texturePath && ( typeof this.texturePath === 'string' ) ? this.texturePath : LoaderUtils.extractUrlBase( url );
  26058. var loader = new FileLoader( this.manager );
  26059. loader.setWithCredentials( this.withCredentials );
  26060. loader.load( url, function ( text ) {
  26061. var json = JSON.parse( text );
  26062. var metadata = json.metadata;
  26063. if ( metadata !== undefined ) {
  26064. var type = metadata.type;
  26065. if ( type !== undefined ) {
  26066. if ( type.toLowerCase() === 'object' ) {
  26067. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  26068. return;
  26069. }
  26070. }
  26071. }
  26072. var object = scope.parse( json, texturePath );
  26073. onLoad( object.geometry, object.materials );
  26074. }, onProgress, onError );
  26075. },
  26076. setTexturePath: function ( value ) {
  26077. this.texturePath = value;
  26078. },
  26079. parse: ( function () {
  26080. function parseModel( json, geometry ) {
  26081. function isBitSet( value, position ) {
  26082. return value & ( 1 << position );
  26083. }
  26084. var i, j, fi,
  26085. offset, zLength,
  26086. colorIndex, normalIndex, uvIndex, materialIndex,
  26087. type,
  26088. isQuad,
  26089. hasMaterial,
  26090. hasFaceVertexUv,
  26091. hasFaceNormal, hasFaceVertexNormal,
  26092. hasFaceColor, hasFaceVertexColor,
  26093. vertex, face, faceA, faceB, hex, normal,
  26094. uvLayer, uv, u, v,
  26095. faces = json.faces,
  26096. vertices = json.vertices,
  26097. normals = json.normals,
  26098. colors = json.colors,
  26099. scale = json.scale,
  26100. nUvLayers = 0;
  26101. if ( json.uvs !== undefined ) {
  26102. // disregard empty arrays
  26103. for ( i = 0; i < json.uvs.length; i ++ ) {
  26104. if ( json.uvs[ i ].length ) nUvLayers ++;
  26105. }
  26106. for ( i = 0; i < nUvLayers; i ++ ) {
  26107. geometry.faceVertexUvs[ i ] = [];
  26108. }
  26109. }
  26110. offset = 0;
  26111. zLength = vertices.length;
  26112. while ( offset < zLength ) {
  26113. vertex = new Vector3();
  26114. vertex.x = vertices[ offset ++ ] * scale;
  26115. vertex.y = vertices[ offset ++ ] * scale;
  26116. vertex.z = vertices[ offset ++ ] * scale;
  26117. geometry.vertices.push( vertex );
  26118. }
  26119. offset = 0;
  26120. zLength = faces.length;
  26121. while ( offset < zLength ) {
  26122. type = faces[ offset ++ ];
  26123. isQuad = isBitSet( type, 0 );
  26124. hasMaterial = isBitSet( type, 1 );
  26125. hasFaceVertexUv = isBitSet( type, 3 );
  26126. hasFaceNormal = isBitSet( type, 4 );
  26127. hasFaceVertexNormal = isBitSet( type, 5 );
  26128. hasFaceColor = isBitSet( type, 6 );
  26129. hasFaceVertexColor = isBitSet( type, 7 );
  26130. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  26131. if ( isQuad ) {
  26132. faceA = new Face3();
  26133. faceA.a = faces[ offset ];
  26134. faceA.b = faces[ offset + 1 ];
  26135. faceA.c = faces[ offset + 3 ];
  26136. faceB = new Face3();
  26137. faceB.a = faces[ offset + 1 ];
  26138. faceB.b = faces[ offset + 2 ];
  26139. faceB.c = faces[ offset + 3 ];
  26140. offset += 4;
  26141. if ( hasMaterial ) {
  26142. materialIndex = faces[ offset ++ ];
  26143. faceA.materialIndex = materialIndex;
  26144. faceB.materialIndex = materialIndex;
  26145. }
  26146. // to get face <=> uv index correspondence
  26147. fi = geometry.faces.length;
  26148. if ( hasFaceVertexUv ) {
  26149. for ( i = 0; i < nUvLayers; i ++ ) {
  26150. uvLayer = json.uvs[ i ];
  26151. geometry.faceVertexUvs[ i ][ fi ] = [];
  26152. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  26153. for ( j = 0; j < 4; j ++ ) {
  26154. uvIndex = faces[ offset ++ ];
  26155. u = uvLayer[ uvIndex * 2 ];
  26156. v = uvLayer[ uvIndex * 2 + 1 ];
  26157. uv = new Vector2( u, v );
  26158. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  26159. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  26160. }
  26161. }
  26162. }
  26163. if ( hasFaceNormal ) {
  26164. normalIndex = faces[ offset ++ ] * 3;
  26165. faceA.normal.set(
  26166. normals[ normalIndex ++ ],
  26167. normals[ normalIndex ++ ],
  26168. normals[ normalIndex ]
  26169. );
  26170. faceB.normal.copy( faceA.normal );
  26171. }
  26172. if ( hasFaceVertexNormal ) {
  26173. for ( i = 0; i < 4; i ++ ) {
  26174. normalIndex = faces[ offset ++ ] * 3;
  26175. normal = new Vector3(
  26176. normals[ normalIndex ++ ],
  26177. normals[ normalIndex ++ ],
  26178. normals[ normalIndex ]
  26179. );
  26180. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  26181. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  26182. }
  26183. }
  26184. if ( hasFaceColor ) {
  26185. colorIndex = faces[ offset ++ ];
  26186. hex = colors[ colorIndex ];
  26187. faceA.color.setHex( hex );
  26188. faceB.color.setHex( hex );
  26189. }
  26190. if ( hasFaceVertexColor ) {
  26191. for ( i = 0; i < 4; i ++ ) {
  26192. colorIndex = faces[ offset ++ ];
  26193. hex = colors[ colorIndex ];
  26194. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  26195. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  26196. }
  26197. }
  26198. geometry.faces.push( faceA );
  26199. geometry.faces.push( faceB );
  26200. } else {
  26201. face = new Face3();
  26202. face.a = faces[ offset ++ ];
  26203. face.b = faces[ offset ++ ];
  26204. face.c = faces[ offset ++ ];
  26205. if ( hasMaterial ) {
  26206. materialIndex = faces[ offset ++ ];
  26207. face.materialIndex = materialIndex;
  26208. }
  26209. // to get face <=> uv index correspondence
  26210. fi = geometry.faces.length;
  26211. if ( hasFaceVertexUv ) {
  26212. for ( i = 0; i < nUvLayers; i ++ ) {
  26213. uvLayer = json.uvs[ i ];
  26214. geometry.faceVertexUvs[ i ][ fi ] = [];
  26215. for ( j = 0; j < 3; j ++ ) {
  26216. uvIndex = faces[ offset ++ ];
  26217. u = uvLayer[ uvIndex * 2 ];
  26218. v = uvLayer[ uvIndex * 2 + 1 ];
  26219. uv = new Vector2( u, v );
  26220. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  26221. }
  26222. }
  26223. }
  26224. if ( hasFaceNormal ) {
  26225. normalIndex = faces[ offset ++ ] * 3;
  26226. face.normal.set(
  26227. normals[ normalIndex ++ ],
  26228. normals[ normalIndex ++ ],
  26229. normals[ normalIndex ]
  26230. );
  26231. }
  26232. if ( hasFaceVertexNormal ) {
  26233. for ( i = 0; i < 3; i ++ ) {
  26234. normalIndex = faces[ offset ++ ] * 3;
  26235. normal = new Vector3(
  26236. normals[ normalIndex ++ ],
  26237. normals[ normalIndex ++ ],
  26238. normals[ normalIndex ]
  26239. );
  26240. face.vertexNormals.push( normal );
  26241. }
  26242. }
  26243. if ( hasFaceColor ) {
  26244. colorIndex = faces[ offset ++ ];
  26245. face.color.setHex( colors[ colorIndex ] );
  26246. }
  26247. if ( hasFaceVertexColor ) {
  26248. for ( i = 0; i < 3; i ++ ) {
  26249. colorIndex = faces[ offset ++ ];
  26250. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  26251. }
  26252. }
  26253. geometry.faces.push( face );
  26254. }
  26255. }
  26256. }
  26257. function parseSkin( json, geometry ) {
  26258. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  26259. if ( json.skinWeights ) {
  26260. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  26261. var x = json.skinWeights[ i ];
  26262. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  26263. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  26264. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  26265. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  26266. }
  26267. }
  26268. if ( json.skinIndices ) {
  26269. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  26270. var a = json.skinIndices[ i ];
  26271. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  26272. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  26273. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  26274. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  26275. }
  26276. }
  26277. geometry.bones = json.bones;
  26278. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  26279. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  26280. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  26281. }
  26282. }
  26283. function parseMorphing( json, geometry ) {
  26284. var scale = json.scale;
  26285. if ( json.morphTargets !== undefined ) {
  26286. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  26287. geometry.morphTargets[ i ] = {};
  26288. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  26289. geometry.morphTargets[ i ].vertices = [];
  26290. var dstVertices = geometry.morphTargets[ i ].vertices;
  26291. var srcVertices = json.morphTargets[ i ].vertices;
  26292. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  26293. var vertex = new Vector3();
  26294. vertex.x = srcVertices[ v ] * scale;
  26295. vertex.y = srcVertices[ v + 1 ] * scale;
  26296. vertex.z = srcVertices[ v + 2 ] * scale;
  26297. dstVertices.push( vertex );
  26298. }
  26299. }
  26300. }
  26301. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  26302. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  26303. var faces = geometry.faces;
  26304. var morphColors = json.morphColors[ 0 ].colors;
  26305. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  26306. faces[ i ].color.fromArray( morphColors, i * 3 );
  26307. }
  26308. }
  26309. }
  26310. function parseAnimations( json, geometry ) {
  26311. var outputAnimations = [];
  26312. // parse old style Bone/Hierarchy animations
  26313. var animations = [];
  26314. if ( json.animation !== undefined ) {
  26315. animations.push( json.animation );
  26316. }
  26317. if ( json.animations !== undefined ) {
  26318. if ( json.animations.length ) {
  26319. animations = animations.concat( json.animations );
  26320. } else {
  26321. animations.push( json.animations );
  26322. }
  26323. }
  26324. for ( var i = 0; i < animations.length; i ++ ) {
  26325. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  26326. if ( clip ) outputAnimations.push( clip );
  26327. }
  26328. // parse implicit morph animations
  26329. if ( geometry.morphTargets ) {
  26330. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  26331. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  26332. outputAnimations = outputAnimations.concat( morphAnimationClips );
  26333. }
  26334. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  26335. }
  26336. return function parse( json, texturePath ) {
  26337. if ( json.data !== undefined ) {
  26338. // Geometry 4.0 spec
  26339. json = json.data;
  26340. }
  26341. if ( json.scale !== undefined ) {
  26342. json.scale = 1.0 / json.scale;
  26343. } else {
  26344. json.scale = 1.0;
  26345. }
  26346. var geometry = new Geometry();
  26347. parseModel( json, geometry );
  26348. parseSkin( json, geometry );
  26349. parseMorphing( json, geometry );
  26350. parseAnimations( json, geometry );
  26351. geometry.computeFaceNormals();
  26352. geometry.computeBoundingSphere();
  26353. if ( json.materials === undefined || json.materials.length === 0 ) {
  26354. return { geometry: geometry };
  26355. } else {
  26356. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  26357. return { geometry: geometry, materials: materials };
  26358. }
  26359. };
  26360. } )()
  26361. } );
  26362. /**
  26363. * @author mrdoob / http://mrdoob.com/
  26364. */
  26365. function ObjectLoader( manager ) {
  26366. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26367. this.texturePath = '';
  26368. }
  26369. Object.assign( ObjectLoader.prototype, {
  26370. load: function ( url, onLoad, onProgress, onError ) {
  26371. if ( this.texturePath === '' ) {
  26372. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  26373. }
  26374. var scope = this;
  26375. var loader = new FileLoader( scope.manager );
  26376. loader.load( url, function ( text ) {
  26377. var json = null;
  26378. try {
  26379. json = JSON.parse( text );
  26380. } catch ( error ) {
  26381. if ( onError !== undefined ) onError( error );
  26382. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  26383. return;
  26384. }
  26385. var metadata = json.metadata;
  26386. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26387. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  26388. return;
  26389. }
  26390. scope.parse( json, onLoad );
  26391. }, onProgress, onError );
  26392. },
  26393. setTexturePath: function ( value ) {
  26394. this.texturePath = value;
  26395. },
  26396. setCrossOrigin: function ( value ) {
  26397. this.crossOrigin = value;
  26398. },
  26399. parse: function ( json, onLoad ) {
  26400. var shapes = this.parseShape( json.shapes );
  26401. var geometries = this.parseGeometries( json.geometries, shapes );
  26402. var images = this.parseImages( json.images, function () {
  26403. if ( onLoad !== undefined ) onLoad( object );
  26404. } );
  26405. var textures = this.parseTextures( json.textures, images );
  26406. var materials = this.parseMaterials( json.materials, textures );
  26407. var object = this.parseObject( json.object, geometries, materials );
  26408. if ( json.animations ) {
  26409. object.animations = this.parseAnimations( json.animations );
  26410. }
  26411. if ( json.images === undefined || json.images.length === 0 ) {
  26412. if ( onLoad !== undefined ) onLoad( object );
  26413. }
  26414. return object;
  26415. },
  26416. parseShape: function ( json ) {
  26417. var shapes = {};
  26418. if ( json !== undefined ) {
  26419. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26420. var shape = new Shape().fromJSON( json[ i ] );
  26421. shapes[ shape.uuid ] = shape;
  26422. }
  26423. }
  26424. return shapes;
  26425. },
  26426. parseGeometries: function ( json, shapes ) {
  26427. var geometries = {};
  26428. if ( json !== undefined ) {
  26429. var geometryLoader = new JSONLoader();
  26430. var bufferGeometryLoader = new BufferGeometryLoader();
  26431. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26432. var geometry;
  26433. var data = json[ i ];
  26434. switch ( data.type ) {
  26435. case 'PlaneGeometry':
  26436. case 'PlaneBufferGeometry':
  26437. geometry = new Geometries[ data.type ](
  26438. data.width,
  26439. data.height,
  26440. data.widthSegments,
  26441. data.heightSegments
  26442. );
  26443. break;
  26444. case 'BoxGeometry':
  26445. case 'BoxBufferGeometry':
  26446. case 'CubeGeometry': // backwards compatible
  26447. geometry = new Geometries[ data.type ](
  26448. data.width,
  26449. data.height,
  26450. data.depth,
  26451. data.widthSegments,
  26452. data.heightSegments,
  26453. data.depthSegments
  26454. );
  26455. break;
  26456. case 'CircleGeometry':
  26457. case 'CircleBufferGeometry':
  26458. geometry = new Geometries[ data.type ](
  26459. data.radius,
  26460. data.segments,
  26461. data.thetaStart,
  26462. data.thetaLength
  26463. );
  26464. break;
  26465. case 'CylinderGeometry':
  26466. case 'CylinderBufferGeometry':
  26467. geometry = new Geometries[ data.type ](
  26468. data.radiusTop,
  26469. data.radiusBottom,
  26470. data.height,
  26471. data.radialSegments,
  26472. data.heightSegments,
  26473. data.openEnded,
  26474. data.thetaStart,
  26475. data.thetaLength
  26476. );
  26477. break;
  26478. case 'ConeGeometry':
  26479. case 'ConeBufferGeometry':
  26480. geometry = new Geometries[ data.type ](
  26481. data.radius,
  26482. data.height,
  26483. data.radialSegments,
  26484. data.heightSegments,
  26485. data.openEnded,
  26486. data.thetaStart,
  26487. data.thetaLength
  26488. );
  26489. break;
  26490. case 'SphereGeometry':
  26491. case 'SphereBufferGeometry':
  26492. geometry = new Geometries[ data.type ](
  26493. data.radius,
  26494. data.widthSegments,
  26495. data.heightSegments,
  26496. data.phiStart,
  26497. data.phiLength,
  26498. data.thetaStart,
  26499. data.thetaLength
  26500. );
  26501. break;
  26502. case 'DodecahedronGeometry':
  26503. case 'DodecahedronBufferGeometry':
  26504. case 'IcosahedronGeometry':
  26505. case 'IcosahedronBufferGeometry':
  26506. case 'OctahedronGeometry':
  26507. case 'OctahedronBufferGeometry':
  26508. case 'TetrahedronGeometry':
  26509. case 'TetrahedronBufferGeometry':
  26510. geometry = new Geometries[ data.type ](
  26511. data.radius,
  26512. data.detail
  26513. );
  26514. break;
  26515. case 'RingGeometry':
  26516. case 'RingBufferGeometry':
  26517. geometry = new Geometries[ data.type ](
  26518. data.innerRadius,
  26519. data.outerRadius,
  26520. data.thetaSegments,
  26521. data.phiSegments,
  26522. data.thetaStart,
  26523. data.thetaLength
  26524. );
  26525. break;
  26526. case 'TorusGeometry':
  26527. case 'TorusBufferGeometry':
  26528. geometry = new Geometries[ data.type ](
  26529. data.radius,
  26530. data.tube,
  26531. data.radialSegments,
  26532. data.tubularSegments,
  26533. data.arc
  26534. );
  26535. break;
  26536. case 'TorusKnotGeometry':
  26537. case 'TorusKnotBufferGeometry':
  26538. geometry = new Geometries[ data.type ](
  26539. data.radius,
  26540. data.tube,
  26541. data.tubularSegments,
  26542. data.radialSegments,
  26543. data.p,
  26544. data.q
  26545. );
  26546. break;
  26547. case 'LatheGeometry':
  26548. case 'LatheBufferGeometry':
  26549. geometry = new Geometries[ data.type ](
  26550. data.points,
  26551. data.segments,
  26552. data.phiStart,
  26553. data.phiLength
  26554. );
  26555. break;
  26556. case 'PolyhedronGeometry':
  26557. case 'PolyhedronBufferGeometry':
  26558. geometry = new Geometries[ data.type ](
  26559. data.vertices,
  26560. data.indices,
  26561. data.radius,
  26562. data.details
  26563. );
  26564. break;
  26565. case 'ShapeGeometry':
  26566. case 'ShapeBufferGeometry':
  26567. var geometryShapes = [];
  26568. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26569. var shape = shapes[ data.shapes[ j ] ];
  26570. geometryShapes.push( shape );
  26571. }
  26572. geometry = new Geometries[ data.type ](
  26573. geometryShapes,
  26574. data.curveSegments
  26575. );
  26576. break;
  26577. case 'BufferGeometry':
  26578. geometry = bufferGeometryLoader.parse( data );
  26579. break;
  26580. case 'Geometry':
  26581. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  26582. break;
  26583. default:
  26584. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  26585. continue;
  26586. }
  26587. geometry.uuid = data.uuid;
  26588. if ( data.name !== undefined ) geometry.name = data.name;
  26589. geometries[ data.uuid ] = geometry;
  26590. }
  26591. }
  26592. return geometries;
  26593. },
  26594. parseMaterials: function ( json, textures ) {
  26595. var materials = {};
  26596. if ( json !== undefined ) {
  26597. var loader = new MaterialLoader();
  26598. loader.setTextures( textures );
  26599. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26600. var data = json[ i ];
  26601. if ( data.type === 'MultiMaterial' ) {
  26602. // Deprecated
  26603. var array = [];
  26604. for ( var j = 0; j < data.materials.length; j ++ ) {
  26605. array.push( loader.parse( data.materials[ j ] ) );
  26606. }
  26607. materials[ data.uuid ] = array;
  26608. } else {
  26609. materials[ data.uuid ] = loader.parse( data );
  26610. }
  26611. }
  26612. }
  26613. return materials;
  26614. },
  26615. parseAnimations: function ( json ) {
  26616. var animations = [];
  26617. for ( var i = 0; i < json.length; i ++ ) {
  26618. var clip = AnimationClip.parse( json[ i ] );
  26619. animations.push( clip );
  26620. }
  26621. return animations;
  26622. },
  26623. parseImages: function ( json, onLoad ) {
  26624. var scope = this;
  26625. var images = {};
  26626. function loadImage( url ) {
  26627. scope.manager.itemStart( url );
  26628. return loader.load( url, function () {
  26629. scope.manager.itemEnd( url );
  26630. }, undefined, function () {
  26631. scope.manager.itemEnd( url );
  26632. scope.manager.itemError( url );
  26633. } );
  26634. }
  26635. if ( json !== undefined && json.length > 0 ) {
  26636. var manager = new LoadingManager( onLoad );
  26637. var loader = new ImageLoader( manager );
  26638. loader.setCrossOrigin( this.crossOrigin );
  26639. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26640. var image = json[ i ];
  26641. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  26642. images[ image.uuid ] = loadImage( path );
  26643. }
  26644. }
  26645. return images;
  26646. },
  26647. parseTextures: function ( json, images ) {
  26648. function parseConstant( value, type ) {
  26649. if ( typeof value === 'number' ) return value;
  26650. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  26651. return type[ value ];
  26652. }
  26653. var textures = {};
  26654. if ( json !== undefined ) {
  26655. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26656. var data = json[ i ];
  26657. if ( data.image === undefined ) {
  26658. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  26659. }
  26660. if ( images[ data.image ] === undefined ) {
  26661. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  26662. }
  26663. var texture = new Texture( images[ data.image ] );
  26664. texture.needsUpdate = true;
  26665. texture.uuid = data.uuid;
  26666. if ( data.name !== undefined ) texture.name = data.name;
  26667. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  26668. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  26669. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  26670. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  26671. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  26672. if ( data.wrap !== undefined ) {
  26673. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  26674. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  26675. }
  26676. if ( data.format !== undefined ) texture.format = data.format;
  26677. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  26678. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  26679. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  26680. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  26681. textures[ data.uuid ] = texture;
  26682. }
  26683. }
  26684. return textures;
  26685. },
  26686. parseObject: function ( data, geometries, materials ) {
  26687. var object;
  26688. function getGeometry( name ) {
  26689. if ( geometries[ name ] === undefined ) {
  26690. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  26691. }
  26692. return geometries[ name ];
  26693. }
  26694. function getMaterial( name ) {
  26695. if ( name === undefined ) return undefined;
  26696. if ( Array.isArray( name ) ) {
  26697. var array = [];
  26698. for ( var i = 0, l = name.length; i < l; i ++ ) {
  26699. var uuid = name[ i ];
  26700. if ( materials[ uuid ] === undefined ) {
  26701. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  26702. }
  26703. array.push( materials[ uuid ] );
  26704. }
  26705. return array;
  26706. }
  26707. if ( materials[ name ] === undefined ) {
  26708. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  26709. }
  26710. return materials[ name ];
  26711. }
  26712. switch ( data.type ) {
  26713. case 'Scene':
  26714. object = new Scene();
  26715. if ( data.background !== undefined ) {
  26716. if ( Number.isInteger( data.background ) ) {
  26717. object.background = new Color( data.background );
  26718. }
  26719. }
  26720. if ( data.fog !== undefined ) {
  26721. if ( data.fog.type === 'Fog' ) {
  26722. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  26723. } else if ( data.fog.type === 'FogExp2' ) {
  26724. object.fog = new FogExp2( data.fog.color, data.fog.density );
  26725. }
  26726. }
  26727. break;
  26728. case 'PerspectiveCamera':
  26729. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  26730. if ( data.focus !== undefined ) object.focus = data.focus;
  26731. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26732. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  26733. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  26734. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26735. break;
  26736. case 'OrthographicCamera':
  26737. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  26738. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26739. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26740. break;
  26741. case 'AmbientLight':
  26742. object = new AmbientLight( data.color, data.intensity );
  26743. break;
  26744. case 'DirectionalLight':
  26745. object = new DirectionalLight( data.color, data.intensity );
  26746. break;
  26747. case 'PointLight':
  26748. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  26749. break;
  26750. case 'RectAreaLight':
  26751. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  26752. break;
  26753. case 'SpotLight':
  26754. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  26755. break;
  26756. case 'HemisphereLight':
  26757. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  26758. break;
  26759. case 'SkinnedMesh':
  26760. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  26761. case 'Mesh':
  26762. var geometry = getGeometry( data.geometry );
  26763. var material = getMaterial( data.material );
  26764. if ( geometry.bones && geometry.bones.length > 0 ) {
  26765. object = new SkinnedMesh( geometry, material );
  26766. } else {
  26767. object = new Mesh( geometry, material );
  26768. }
  26769. break;
  26770. case 'LOD':
  26771. object = new LOD();
  26772. break;
  26773. case 'Line':
  26774. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  26775. break;
  26776. case 'LineLoop':
  26777. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  26778. break;
  26779. case 'LineSegments':
  26780. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  26781. break;
  26782. case 'PointCloud':
  26783. case 'Points':
  26784. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  26785. break;
  26786. case 'Sprite':
  26787. object = new Sprite( getMaterial( data.material ) );
  26788. break;
  26789. case 'Group':
  26790. object = new Group();
  26791. break;
  26792. default:
  26793. object = new Object3D();
  26794. }
  26795. object.uuid = data.uuid;
  26796. if ( data.name !== undefined ) object.name = data.name;
  26797. if ( data.matrix !== undefined ) {
  26798. object.matrix.fromArray( data.matrix );
  26799. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  26800. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  26801. } else {
  26802. if ( data.position !== undefined ) object.position.fromArray( data.position );
  26803. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  26804. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  26805. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  26806. }
  26807. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  26808. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  26809. if ( data.shadow ) {
  26810. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  26811. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  26812. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26813. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26814. }
  26815. if ( data.visible !== undefined ) object.visible = data.visible;
  26816. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  26817. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  26818. if ( data.userData !== undefined ) object.userData = data.userData;
  26819. if ( data.children !== undefined ) {
  26820. var children = data.children;
  26821. for ( var i = 0; i < children.length; i ++ ) {
  26822. object.add( this.parseObject( children[ i ], geometries, materials ) );
  26823. }
  26824. }
  26825. if ( data.type === 'LOD' ) {
  26826. var levels = data.levels;
  26827. for ( var l = 0; l < levels.length; l ++ ) {
  26828. var level = levels[ l ];
  26829. var child = object.getObjectByProperty( 'uuid', level.object );
  26830. if ( child !== undefined ) {
  26831. object.addLevel( child, level.distance );
  26832. }
  26833. }
  26834. }
  26835. return object;
  26836. }
  26837. } );
  26838. var TEXTURE_MAPPING = {
  26839. UVMapping: UVMapping,
  26840. CubeReflectionMapping: CubeReflectionMapping,
  26841. CubeRefractionMapping: CubeRefractionMapping,
  26842. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26843. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26844. SphericalReflectionMapping: SphericalReflectionMapping,
  26845. CubeUVReflectionMapping: CubeUVReflectionMapping,
  26846. CubeUVRefractionMapping: CubeUVRefractionMapping
  26847. };
  26848. var TEXTURE_WRAPPING = {
  26849. RepeatWrapping: RepeatWrapping,
  26850. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26851. MirroredRepeatWrapping: MirroredRepeatWrapping
  26852. };
  26853. var TEXTURE_FILTER = {
  26854. NearestFilter: NearestFilter,
  26855. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  26856. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  26857. LinearFilter: LinearFilter,
  26858. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  26859. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  26860. };
  26861. /**
  26862. * @author thespite / http://clicktorelease.com/
  26863. */
  26864. function ImageBitmapLoader( manager ) {
  26865. if ( typeof createImageBitmap === 'undefined' ) {
  26866. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26867. }
  26868. if ( typeof fetch === 'undefined' ) {
  26869. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26870. }
  26871. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  26872. this.options = undefined;
  26873. }
  26874. ImageBitmapLoader.prototype = {
  26875. constructor: ImageBitmapLoader,
  26876. setOptions: function setOptions( options ) {
  26877. this.options = options;
  26878. return this;
  26879. },
  26880. load: function load( url, onLoad, onProgress, onError ) {
  26881. if ( url === undefined ) url = '';
  26882. if ( this.path !== undefined ) url = this.path + url;
  26883. var scope = this;
  26884. var cached = Cache.get( url );
  26885. if ( cached !== undefined ) {
  26886. scope.manager.itemStart( url );
  26887. setTimeout( function () {
  26888. if ( onLoad ) onLoad( cached );
  26889. scope.manager.itemEnd( url );
  26890. }, 0 );
  26891. return cached;
  26892. }
  26893. fetch( url ).then( function ( res ) {
  26894. return res.blob();
  26895. } ).then( function ( blob ) {
  26896. return createImageBitmap( blob, scope.options );
  26897. } ).then( function ( imageBitmap ) {
  26898. Cache.add( url, imageBitmap );
  26899. if ( onLoad ) onLoad( imageBitmap );
  26900. scope.manager.itemEnd( url );
  26901. } ).catch( function ( e ) {
  26902. if ( onError ) onError( e );
  26903. scope.manager.itemEnd( url );
  26904. scope.manager.itemError( url );
  26905. } );
  26906. },
  26907. setCrossOrigin: function ( /* value */ ) {
  26908. return this;
  26909. },
  26910. setPath: function ( value ) {
  26911. this.path = value;
  26912. return this;
  26913. }
  26914. };
  26915. /**
  26916. * @author zz85 / http://www.lab4games.net/zz85/blog
  26917. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  26918. **/
  26919. function ShapePath() {
  26920. this.type = 'ShapePath';
  26921. this.color = new Color();
  26922. this.subPaths = [];
  26923. this.currentPath = null;
  26924. }
  26925. Object.assign( ShapePath.prototype, {
  26926. moveTo: function ( x, y ) {
  26927. this.currentPath = new Path();
  26928. this.subPaths.push( this.currentPath );
  26929. this.currentPath.moveTo( x, y );
  26930. },
  26931. lineTo: function ( x, y ) {
  26932. this.currentPath.lineTo( x, y );
  26933. },
  26934. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  26935. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  26936. },
  26937. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  26938. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  26939. },
  26940. splineThru: function ( pts ) {
  26941. this.currentPath.splineThru( pts );
  26942. },
  26943. toShapes: function ( isCCW, noHoles ) {
  26944. function toShapesNoHoles( inSubpaths ) {
  26945. var shapes = [];
  26946. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  26947. var tmpPath = inSubpaths[ i ];
  26948. var tmpShape = new Shape();
  26949. tmpShape.curves = tmpPath.curves;
  26950. shapes.push( tmpShape );
  26951. }
  26952. return shapes;
  26953. }
  26954. function isPointInsidePolygon( inPt, inPolygon ) {
  26955. var polyLen = inPolygon.length;
  26956. // inPt on polygon contour => immediate success or
  26957. // toggling of inside/outside at every single! intersection point of an edge
  26958. // with the horizontal line through inPt, left of inPt
  26959. // not counting lowerY endpoints of edges and whole edges on that line
  26960. var inside = false;
  26961. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  26962. var edgeLowPt = inPolygon[ p ];
  26963. var edgeHighPt = inPolygon[ q ];
  26964. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  26965. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  26966. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  26967. // not parallel
  26968. if ( edgeDy < 0 ) {
  26969. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  26970. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  26971. }
  26972. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  26973. if ( inPt.y === edgeLowPt.y ) {
  26974. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  26975. // continue; // no intersection or edgeLowPt => doesn't count !!!
  26976. } else {
  26977. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  26978. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  26979. if ( perpEdge < 0 ) continue;
  26980. inside = ! inside; // true intersection left of inPt
  26981. }
  26982. } else {
  26983. // parallel or collinear
  26984. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  26985. // edge lies on the same horizontal line as inPt
  26986. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  26987. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  26988. // continue;
  26989. }
  26990. }
  26991. return inside;
  26992. }
  26993. var isClockWise = ShapeUtils.isClockWise;
  26994. var subPaths = this.subPaths;
  26995. if ( subPaths.length === 0 ) return [];
  26996. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  26997. var solid, tmpPath, tmpShape, shapes = [];
  26998. if ( subPaths.length === 1 ) {
  26999. tmpPath = subPaths[ 0 ];
  27000. tmpShape = new Shape();
  27001. tmpShape.curves = tmpPath.curves;
  27002. shapes.push( tmpShape );
  27003. return shapes;
  27004. }
  27005. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  27006. holesFirst = isCCW ? ! holesFirst : holesFirst;
  27007. // console.log("Holes first", holesFirst);
  27008. var betterShapeHoles = [];
  27009. var newShapes = [];
  27010. var newShapeHoles = [];
  27011. var mainIdx = 0;
  27012. var tmpPoints;
  27013. newShapes[ mainIdx ] = undefined;
  27014. newShapeHoles[ mainIdx ] = [];
  27015. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  27016. tmpPath = subPaths[ i ];
  27017. tmpPoints = tmpPath.getPoints();
  27018. solid = isClockWise( tmpPoints );
  27019. solid = isCCW ? ! solid : solid;
  27020. if ( solid ) {
  27021. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  27022. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  27023. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  27024. if ( holesFirst ) mainIdx ++;
  27025. newShapeHoles[ mainIdx ] = [];
  27026. //console.log('cw', i);
  27027. } else {
  27028. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  27029. //console.log('ccw', i);
  27030. }
  27031. }
  27032. // only Holes? -> probably all Shapes with wrong orientation
  27033. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  27034. if ( newShapes.length > 1 ) {
  27035. var ambiguous = false;
  27036. var toChange = [];
  27037. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  27038. betterShapeHoles[ sIdx ] = [];
  27039. }
  27040. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  27041. var sho = newShapeHoles[ sIdx ];
  27042. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  27043. var ho = sho[ hIdx ];
  27044. var hole_unassigned = true;
  27045. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  27046. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  27047. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  27048. if ( hole_unassigned ) {
  27049. hole_unassigned = false;
  27050. betterShapeHoles[ s2Idx ].push( ho );
  27051. } else {
  27052. ambiguous = true;
  27053. }
  27054. }
  27055. }
  27056. if ( hole_unassigned ) {
  27057. betterShapeHoles[ sIdx ].push( ho );
  27058. }
  27059. }
  27060. }
  27061. // console.log("ambiguous: ", ambiguous);
  27062. if ( toChange.length > 0 ) {
  27063. // console.log("to change: ", toChange);
  27064. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  27065. }
  27066. }
  27067. var tmpHoles;
  27068. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  27069. tmpShape = newShapes[ i ].s;
  27070. shapes.push( tmpShape );
  27071. tmpHoles = newShapeHoles[ i ];
  27072. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  27073. tmpShape.holes.push( tmpHoles[ j ].h );
  27074. }
  27075. }
  27076. //console.log("shape", shapes);
  27077. return shapes;
  27078. }
  27079. } );
  27080. /**
  27081. * @author zz85 / http://www.lab4games.net/zz85/blog
  27082. * @author mrdoob / http://mrdoob.com/
  27083. */
  27084. function Font( data ) {
  27085. this.type = 'Font';
  27086. this.data = data;
  27087. }
  27088. Object.assign( Font.prototype, {
  27089. isFont: true,
  27090. generateShapes: function ( text, size, divisions ) {
  27091. if ( size === undefined ) size = 100;
  27092. if ( divisions === undefined ) divisions = 4;
  27093. var shapes = [];
  27094. var paths = createPaths( text, size, divisions, this.data );
  27095. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  27096. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  27097. }
  27098. return shapes;
  27099. }
  27100. } );
  27101. function createPaths( text, size, divisions, data ) {
  27102. var chars = String( text ).split( '' );
  27103. var scale = size / data.resolution;
  27104. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  27105. var paths = [];
  27106. var offsetX = 0, offsetY = 0;
  27107. for ( var i = 0; i < chars.length; i ++ ) {
  27108. var char = chars[ i ];
  27109. if ( char === '\n' ) {
  27110. offsetX = 0;
  27111. offsetY -= line_height;
  27112. } else {
  27113. var ret = createPath( char, divisions, scale, offsetX, offsetY, data );
  27114. offsetX += ret.offsetX;
  27115. paths.push( ret.path );
  27116. }
  27117. }
  27118. return paths;
  27119. }
  27120. function createPath( char, divisions, scale, offsetX, offsetY, data ) {
  27121. var glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  27122. if ( ! glyph ) return;
  27123. var path = new ShapePath();
  27124. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  27125. if ( glyph.o ) {
  27126. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  27127. for ( var i = 0, l = outline.length; i < l; ) {
  27128. var action = outline[ i ++ ];
  27129. switch ( action ) {
  27130. case 'm': // moveTo
  27131. x = outline[ i ++ ] * scale + offsetX;
  27132. y = outline[ i ++ ] * scale + offsetY;
  27133. path.moveTo( x, y );
  27134. break;
  27135. case 'l': // lineTo
  27136. x = outline[ i ++ ] * scale + offsetX;
  27137. y = outline[ i ++ ] * scale + offsetY;
  27138. path.lineTo( x, y );
  27139. break;
  27140. case 'q': // quadraticCurveTo
  27141. cpx = outline[ i ++ ] * scale + offsetX;
  27142. cpy = outline[ i ++ ] * scale + offsetY;
  27143. cpx1 = outline[ i ++ ] * scale + offsetX;
  27144. cpy1 = outline[ i ++ ] * scale + offsetY;
  27145. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  27146. break;
  27147. case 'b': // bezierCurveTo
  27148. cpx = outline[ i ++ ] * scale + offsetX;
  27149. cpy = outline[ i ++ ] * scale + offsetY;
  27150. cpx1 = outline[ i ++ ] * scale + offsetX;
  27151. cpy1 = outline[ i ++ ] * scale + offsetY;
  27152. cpx2 = outline[ i ++ ] * scale + offsetX;
  27153. cpy2 = outline[ i ++ ] * scale + offsetY;
  27154. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  27155. break;
  27156. }
  27157. }
  27158. }
  27159. return { offsetX: glyph.ha * scale, path: path };
  27160. }
  27161. /**
  27162. * @author mrdoob / http://mrdoob.com/
  27163. */
  27164. function FontLoader( manager ) {
  27165. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27166. }
  27167. Object.assign( FontLoader.prototype, {
  27168. load: function ( url, onLoad, onProgress, onError ) {
  27169. var scope = this;
  27170. var loader = new FileLoader( this.manager );
  27171. loader.setPath( this.path );
  27172. loader.load( url, function ( text ) {
  27173. var json;
  27174. try {
  27175. json = JSON.parse( text );
  27176. } catch ( e ) {
  27177. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  27178. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  27179. }
  27180. var font = scope.parse( json );
  27181. if ( onLoad ) onLoad( font );
  27182. }, onProgress, onError );
  27183. },
  27184. parse: function ( json ) {
  27185. return new Font( json );
  27186. },
  27187. setPath: function ( value ) {
  27188. this.path = value;
  27189. return this;
  27190. }
  27191. } );
  27192. /**
  27193. * @author mrdoob / http://mrdoob.com/
  27194. */
  27195. var context;
  27196. var AudioContext = {
  27197. getContext: function () {
  27198. if ( context === undefined ) {
  27199. context = new ( window.AudioContext || window.webkitAudioContext )();
  27200. }
  27201. return context;
  27202. },
  27203. setContext: function ( value ) {
  27204. context = value;
  27205. }
  27206. };
  27207. /**
  27208. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  27209. */
  27210. function AudioLoader( manager ) {
  27211. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27212. }
  27213. Object.assign( AudioLoader.prototype, {
  27214. load: function ( url, onLoad, onProgress, onError ) {
  27215. var loader = new FileLoader( this.manager );
  27216. loader.setResponseType( 'arraybuffer' );
  27217. loader.load( url, function ( buffer ) {
  27218. var context = AudioContext.getContext();
  27219. context.decodeAudioData( buffer, function ( audioBuffer ) {
  27220. onLoad( audioBuffer );
  27221. } );
  27222. }, onProgress, onError );
  27223. }
  27224. } );
  27225. /**
  27226. * @author mrdoob / http://mrdoob.com/
  27227. */
  27228. function StereoCamera() {
  27229. this.type = 'StereoCamera';
  27230. this.aspect = 1;
  27231. this.eyeSep = 0.064;
  27232. this.cameraL = new PerspectiveCamera();
  27233. this.cameraL.layers.enable( 1 );
  27234. this.cameraL.matrixAutoUpdate = false;
  27235. this.cameraR = new PerspectiveCamera();
  27236. this.cameraR.layers.enable( 2 );
  27237. this.cameraR.matrixAutoUpdate = false;
  27238. }
  27239. Object.assign( StereoCamera.prototype, {
  27240. update: ( function () {
  27241. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  27242. var eyeRight = new Matrix4();
  27243. var eyeLeft = new Matrix4();
  27244. return function update( camera ) {
  27245. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  27246. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  27247. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  27248. if ( needsUpdate ) {
  27249. instance = this;
  27250. focus = camera.focus;
  27251. fov = camera.fov;
  27252. aspect = camera.aspect * this.aspect;
  27253. near = camera.near;
  27254. far = camera.far;
  27255. zoom = camera.zoom;
  27256. // Off-axis stereoscopic effect based on
  27257. // http://paulbourke.net/stereographics/stereorender/
  27258. var projectionMatrix = camera.projectionMatrix.clone();
  27259. eyeSep = this.eyeSep / 2;
  27260. var eyeSepOnProjection = eyeSep * near / focus;
  27261. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  27262. var xmin, xmax;
  27263. // translate xOffset
  27264. eyeLeft.elements[ 12 ] = - eyeSep;
  27265. eyeRight.elements[ 12 ] = eyeSep;
  27266. // for left eye
  27267. xmin = - ymax * aspect + eyeSepOnProjection;
  27268. xmax = ymax * aspect + eyeSepOnProjection;
  27269. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  27270. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27271. this.cameraL.projectionMatrix.copy( projectionMatrix );
  27272. // for right eye
  27273. xmin = - ymax * aspect - eyeSepOnProjection;
  27274. xmax = ymax * aspect - eyeSepOnProjection;
  27275. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  27276. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27277. this.cameraR.projectionMatrix.copy( projectionMatrix );
  27278. }
  27279. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  27280. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  27281. };
  27282. } )()
  27283. } );
  27284. /**
  27285. * Camera for rendering cube maps
  27286. * - renders scene into axis-aligned cube
  27287. *
  27288. * @author alteredq / http://alteredqualia.com/
  27289. */
  27290. function CubeCamera( near, far, cubeResolution ) {
  27291. Object3D.call( this );
  27292. this.type = 'CubeCamera';
  27293. var fov = 90, aspect = 1;
  27294. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  27295. cameraPX.up.set( 0, - 1, 0 );
  27296. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  27297. this.add( cameraPX );
  27298. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  27299. cameraNX.up.set( 0, - 1, 0 );
  27300. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  27301. this.add( cameraNX );
  27302. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  27303. cameraPY.up.set( 0, 0, 1 );
  27304. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  27305. this.add( cameraPY );
  27306. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  27307. cameraNY.up.set( 0, 0, - 1 );
  27308. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  27309. this.add( cameraNY );
  27310. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  27311. cameraPZ.up.set( 0, - 1, 0 );
  27312. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  27313. this.add( cameraPZ );
  27314. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  27315. cameraNZ.up.set( 0, - 1, 0 );
  27316. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  27317. this.add( cameraNZ );
  27318. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  27319. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  27320. this.renderTarget.texture.name = "CubeCamera";
  27321. this.update = function ( renderer, scene ) {
  27322. if ( this.parent === null ) this.updateMatrixWorld();
  27323. var renderTarget = this.renderTarget;
  27324. var generateMipmaps = renderTarget.texture.generateMipmaps;
  27325. renderTarget.texture.generateMipmaps = false;
  27326. renderTarget.activeCubeFace = 0;
  27327. renderer.render( scene, cameraPX, renderTarget );
  27328. renderTarget.activeCubeFace = 1;
  27329. renderer.render( scene, cameraNX, renderTarget );
  27330. renderTarget.activeCubeFace = 2;
  27331. renderer.render( scene, cameraPY, renderTarget );
  27332. renderTarget.activeCubeFace = 3;
  27333. renderer.render( scene, cameraNY, renderTarget );
  27334. renderTarget.activeCubeFace = 4;
  27335. renderer.render( scene, cameraPZ, renderTarget );
  27336. renderTarget.texture.generateMipmaps = generateMipmaps;
  27337. renderTarget.activeCubeFace = 5;
  27338. renderer.render( scene, cameraNZ, renderTarget );
  27339. renderer.setRenderTarget( null );
  27340. };
  27341. this.clear = function ( renderer, color, depth, stencil ) {
  27342. var renderTarget = this.renderTarget;
  27343. for ( var i = 0; i < 6; i ++ ) {
  27344. renderTarget.activeCubeFace = i;
  27345. renderer.setRenderTarget( renderTarget );
  27346. renderer.clear( color, depth, stencil );
  27347. }
  27348. renderer.setRenderTarget( null );
  27349. };
  27350. }
  27351. CubeCamera.prototype = Object.create( Object3D.prototype );
  27352. CubeCamera.prototype.constructor = CubeCamera;
  27353. /**
  27354. * @author mrdoob / http://mrdoob.com/
  27355. */
  27356. function AudioListener() {
  27357. Object3D.call( this );
  27358. this.type = 'AudioListener';
  27359. this.context = AudioContext.getContext();
  27360. this.gain = this.context.createGain();
  27361. this.gain.connect( this.context.destination );
  27362. this.filter = null;
  27363. }
  27364. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  27365. constructor: AudioListener,
  27366. getInput: function () {
  27367. return this.gain;
  27368. },
  27369. removeFilter: function ( ) {
  27370. if ( this.filter !== null ) {
  27371. this.gain.disconnect( this.filter );
  27372. this.filter.disconnect( this.context.destination );
  27373. this.gain.connect( this.context.destination );
  27374. this.filter = null;
  27375. }
  27376. },
  27377. getFilter: function () {
  27378. return this.filter;
  27379. },
  27380. setFilter: function ( value ) {
  27381. if ( this.filter !== null ) {
  27382. this.gain.disconnect( this.filter );
  27383. this.filter.disconnect( this.context.destination );
  27384. } else {
  27385. this.gain.disconnect( this.context.destination );
  27386. }
  27387. this.filter = value;
  27388. this.gain.connect( this.filter );
  27389. this.filter.connect( this.context.destination );
  27390. },
  27391. getMasterVolume: function () {
  27392. return this.gain.gain.value;
  27393. },
  27394. setMasterVolume: function ( value ) {
  27395. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  27396. },
  27397. updateMatrixWorld: ( function () {
  27398. var position = new Vector3();
  27399. var quaternion = new Quaternion();
  27400. var scale = new Vector3();
  27401. var orientation = new Vector3();
  27402. return function updateMatrixWorld( force ) {
  27403. Object3D.prototype.updateMatrixWorld.call( this, force );
  27404. var listener = this.context.listener;
  27405. var up = this.up;
  27406. this.matrixWorld.decompose( position, quaternion, scale );
  27407. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  27408. if ( listener.positionX ) {
  27409. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  27410. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  27411. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  27412. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  27413. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  27414. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  27415. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  27416. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  27417. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  27418. } else {
  27419. listener.setPosition( position.x, position.y, position.z );
  27420. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  27421. }
  27422. };
  27423. } )()
  27424. } );
  27425. /**
  27426. * @author mrdoob / http://mrdoob.com/
  27427. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  27428. */
  27429. function Audio( listener ) {
  27430. Object3D.call( this );
  27431. this.type = 'Audio';
  27432. this.context = listener.context;
  27433. this.gain = this.context.createGain();
  27434. this.gain.connect( listener.getInput() );
  27435. this.autoplay = false;
  27436. this.buffer = null;
  27437. this.loop = false;
  27438. this.startTime = 0;
  27439. this.offset = 0;
  27440. this.playbackRate = 1;
  27441. this.isPlaying = false;
  27442. this.hasPlaybackControl = true;
  27443. this.sourceType = 'empty';
  27444. this.filters = [];
  27445. }
  27446. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  27447. constructor: Audio,
  27448. getOutput: function () {
  27449. return this.gain;
  27450. },
  27451. setNodeSource: function ( audioNode ) {
  27452. this.hasPlaybackControl = false;
  27453. this.sourceType = 'audioNode';
  27454. this.source = audioNode;
  27455. this.connect();
  27456. return this;
  27457. },
  27458. setBuffer: function ( audioBuffer ) {
  27459. this.buffer = audioBuffer;
  27460. this.sourceType = 'buffer';
  27461. if ( this.autoplay ) this.play();
  27462. return this;
  27463. },
  27464. play: function () {
  27465. if ( this.isPlaying === true ) {
  27466. console.warn( 'THREE.Audio: Audio is already playing.' );
  27467. return;
  27468. }
  27469. if ( this.hasPlaybackControl === false ) {
  27470. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27471. return;
  27472. }
  27473. var source = this.context.createBufferSource();
  27474. source.buffer = this.buffer;
  27475. source.loop = this.loop;
  27476. source.onended = this.onEnded.bind( this );
  27477. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  27478. this.startTime = this.context.currentTime;
  27479. source.start( this.startTime, this.offset );
  27480. this.isPlaying = true;
  27481. this.source = source;
  27482. return this.connect();
  27483. },
  27484. pause: function () {
  27485. if ( this.hasPlaybackControl === false ) {
  27486. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27487. return;
  27488. }
  27489. if ( this.isPlaying === true ) {
  27490. this.source.stop();
  27491. this.offset += ( this.context.currentTime - this.startTime ) * this.playbackRate;
  27492. this.isPlaying = false;
  27493. }
  27494. return this;
  27495. },
  27496. stop: function () {
  27497. if ( this.hasPlaybackControl === false ) {
  27498. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27499. return;
  27500. }
  27501. this.source.stop();
  27502. this.offset = 0;
  27503. this.isPlaying = false;
  27504. return this;
  27505. },
  27506. connect: function () {
  27507. if ( this.filters.length > 0 ) {
  27508. this.source.connect( this.filters[ 0 ] );
  27509. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  27510. this.filters[ i - 1 ].connect( this.filters[ i ] );
  27511. }
  27512. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  27513. } else {
  27514. this.source.connect( this.getOutput() );
  27515. }
  27516. return this;
  27517. },
  27518. disconnect: function () {
  27519. if ( this.filters.length > 0 ) {
  27520. this.source.disconnect( this.filters[ 0 ] );
  27521. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  27522. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  27523. }
  27524. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  27525. } else {
  27526. this.source.disconnect( this.getOutput() );
  27527. }
  27528. return this;
  27529. },
  27530. getFilters: function () {
  27531. return this.filters;
  27532. },
  27533. setFilters: function ( value ) {
  27534. if ( ! value ) value = [];
  27535. if ( this.isPlaying === true ) {
  27536. this.disconnect();
  27537. this.filters = value;
  27538. this.connect();
  27539. } else {
  27540. this.filters = value;
  27541. }
  27542. return this;
  27543. },
  27544. getFilter: function () {
  27545. return this.getFilters()[ 0 ];
  27546. },
  27547. setFilter: function ( filter ) {
  27548. return this.setFilters( filter ? [ filter ] : [] );
  27549. },
  27550. setPlaybackRate: function ( value ) {
  27551. if ( this.hasPlaybackControl === false ) {
  27552. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27553. return;
  27554. }
  27555. this.playbackRate = value;
  27556. if ( this.isPlaying === true ) {
  27557. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  27558. }
  27559. return this;
  27560. },
  27561. getPlaybackRate: function () {
  27562. return this.playbackRate;
  27563. },
  27564. onEnded: function () {
  27565. this.isPlaying = false;
  27566. },
  27567. getLoop: function () {
  27568. if ( this.hasPlaybackControl === false ) {
  27569. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27570. return false;
  27571. }
  27572. return this.loop;
  27573. },
  27574. setLoop: function ( value ) {
  27575. if ( this.hasPlaybackControl === false ) {
  27576. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27577. return;
  27578. }
  27579. this.loop = value;
  27580. if ( this.isPlaying === true ) {
  27581. this.source.loop = this.loop;
  27582. }
  27583. return this;
  27584. },
  27585. getVolume: function () {
  27586. return this.gain.gain.value;
  27587. },
  27588. setVolume: function ( value ) {
  27589. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  27590. return this;
  27591. }
  27592. } );
  27593. /**
  27594. * @author mrdoob / http://mrdoob.com/
  27595. */
  27596. function PositionalAudio( listener ) {
  27597. Audio.call( this, listener );
  27598. this.panner = this.context.createPanner();
  27599. this.panner.connect( this.gain );
  27600. }
  27601. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  27602. constructor: PositionalAudio,
  27603. getOutput: function () {
  27604. return this.panner;
  27605. },
  27606. getRefDistance: function () {
  27607. return this.panner.refDistance;
  27608. },
  27609. setRefDistance: function ( value ) {
  27610. this.panner.refDistance = value;
  27611. },
  27612. getRolloffFactor: function () {
  27613. return this.panner.rolloffFactor;
  27614. },
  27615. setRolloffFactor: function ( value ) {
  27616. this.panner.rolloffFactor = value;
  27617. },
  27618. getDistanceModel: function () {
  27619. return this.panner.distanceModel;
  27620. },
  27621. setDistanceModel: function ( value ) {
  27622. this.panner.distanceModel = value;
  27623. },
  27624. getMaxDistance: function () {
  27625. return this.panner.maxDistance;
  27626. },
  27627. setMaxDistance: function ( value ) {
  27628. this.panner.maxDistance = value;
  27629. },
  27630. updateMatrixWorld: ( function () {
  27631. var position = new Vector3();
  27632. return function updateMatrixWorld( force ) {
  27633. Object3D.prototype.updateMatrixWorld.call( this, force );
  27634. position.setFromMatrixPosition( this.matrixWorld );
  27635. this.panner.setPosition( position.x, position.y, position.z );
  27636. };
  27637. } )()
  27638. } );
  27639. /**
  27640. * @author mrdoob / http://mrdoob.com/
  27641. */
  27642. function AudioAnalyser( audio, fftSize ) {
  27643. this.analyser = audio.context.createAnalyser();
  27644. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  27645. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  27646. audio.getOutput().connect( this.analyser );
  27647. }
  27648. Object.assign( AudioAnalyser.prototype, {
  27649. getFrequencyData: function () {
  27650. this.analyser.getByteFrequencyData( this.data );
  27651. return this.data;
  27652. },
  27653. getAverageFrequency: function () {
  27654. var value = 0, data = this.getFrequencyData();
  27655. for ( var i = 0; i < data.length; i ++ ) {
  27656. value += data[ i ];
  27657. }
  27658. return value / data.length;
  27659. }
  27660. } );
  27661. /**
  27662. *
  27663. * Buffered scene graph property that allows weighted accumulation.
  27664. *
  27665. *
  27666. * @author Ben Houston / http://clara.io/
  27667. * @author David Sarno / http://lighthaus.us/
  27668. * @author tschw
  27669. */
  27670. function PropertyMixer( binding, typeName, valueSize ) {
  27671. this.binding = binding;
  27672. this.valueSize = valueSize;
  27673. var bufferType = Float64Array,
  27674. mixFunction;
  27675. switch ( typeName ) {
  27676. case 'quaternion':
  27677. mixFunction = this._slerp;
  27678. break;
  27679. case 'string':
  27680. case 'bool':
  27681. bufferType = Array;
  27682. mixFunction = this._select;
  27683. break;
  27684. default:
  27685. mixFunction = this._lerp;
  27686. }
  27687. this.buffer = new bufferType( valueSize * 4 );
  27688. // layout: [ incoming | accu0 | accu1 | orig ]
  27689. //
  27690. // interpolators can use .buffer as their .result
  27691. // the data then goes to 'incoming'
  27692. //
  27693. // 'accu0' and 'accu1' are used frame-interleaved for
  27694. // the cumulative result and are compared to detect
  27695. // changes
  27696. //
  27697. // 'orig' stores the original state of the property
  27698. this._mixBufferRegion = mixFunction;
  27699. this.cumulativeWeight = 0;
  27700. this.useCount = 0;
  27701. this.referenceCount = 0;
  27702. }
  27703. Object.assign( PropertyMixer.prototype, {
  27704. // accumulate data in the 'incoming' region into 'accu<i>'
  27705. accumulate: function ( accuIndex, weight ) {
  27706. // note: happily accumulating nothing when weight = 0, the caller knows
  27707. // the weight and shouldn't have made the call in the first place
  27708. var buffer = this.buffer,
  27709. stride = this.valueSize,
  27710. offset = accuIndex * stride + stride,
  27711. currentWeight = this.cumulativeWeight;
  27712. if ( currentWeight === 0 ) {
  27713. // accuN := incoming * weight
  27714. for ( var i = 0; i !== stride; ++ i ) {
  27715. buffer[ offset + i ] = buffer[ i ];
  27716. }
  27717. currentWeight = weight;
  27718. } else {
  27719. // accuN := accuN + incoming * weight
  27720. currentWeight += weight;
  27721. var mix = weight / currentWeight;
  27722. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  27723. }
  27724. this.cumulativeWeight = currentWeight;
  27725. },
  27726. // apply the state of 'accu<i>' to the binding when accus differ
  27727. apply: function ( accuIndex ) {
  27728. var stride = this.valueSize,
  27729. buffer = this.buffer,
  27730. offset = accuIndex * stride + stride,
  27731. weight = this.cumulativeWeight,
  27732. binding = this.binding;
  27733. this.cumulativeWeight = 0;
  27734. if ( weight < 1 ) {
  27735. // accuN := accuN + original * ( 1 - cumulativeWeight )
  27736. var originalValueOffset = stride * 3;
  27737. this._mixBufferRegion(
  27738. buffer, offset, originalValueOffset, 1 - weight, stride );
  27739. }
  27740. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  27741. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  27742. // value has changed -> update scene graph
  27743. binding.setValue( buffer, offset );
  27744. break;
  27745. }
  27746. }
  27747. },
  27748. // remember the state of the bound property and copy it to both accus
  27749. saveOriginalState: function () {
  27750. var binding = this.binding;
  27751. var buffer = this.buffer,
  27752. stride = this.valueSize,
  27753. originalValueOffset = stride * 3;
  27754. binding.getValue( buffer, originalValueOffset );
  27755. // accu[0..1] := orig -- initially detect changes against the original
  27756. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  27757. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  27758. }
  27759. this.cumulativeWeight = 0;
  27760. },
  27761. // apply the state previously taken via 'saveOriginalState' to the binding
  27762. restoreOriginalState: function () {
  27763. var originalValueOffset = this.valueSize * 3;
  27764. this.binding.setValue( this.buffer, originalValueOffset );
  27765. },
  27766. // mix functions
  27767. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  27768. if ( t >= 0.5 ) {
  27769. for ( var i = 0; i !== stride; ++ i ) {
  27770. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  27771. }
  27772. }
  27773. },
  27774. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  27775. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  27776. },
  27777. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  27778. var s = 1 - t;
  27779. for ( var i = 0; i !== stride; ++ i ) {
  27780. var j = dstOffset + i;
  27781. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  27782. }
  27783. }
  27784. } );
  27785. /**
  27786. *
  27787. * A reference to a real property in the scene graph.
  27788. *
  27789. *
  27790. * @author Ben Houston / http://clara.io/
  27791. * @author David Sarno / http://lighthaus.us/
  27792. * @author tschw
  27793. */
  27794. // Characters [].:/ are reserved for track binding syntax.
  27795. var RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  27796. function Composite( targetGroup, path, optionalParsedPath ) {
  27797. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  27798. this._targetGroup = targetGroup;
  27799. this._bindings = targetGroup.subscribe_( path, parsedPath );
  27800. }
  27801. Object.assign( Composite.prototype, {
  27802. getValue: function ( array, offset ) {
  27803. this.bind(); // bind all binding
  27804. var firstValidIndex = this._targetGroup.nCachedObjects_,
  27805. binding = this._bindings[ firstValidIndex ];
  27806. // and only call .getValue on the first
  27807. if ( binding !== undefined ) binding.getValue( array, offset );
  27808. },
  27809. setValue: function ( array, offset ) {
  27810. var bindings = this._bindings;
  27811. for ( var i = this._targetGroup.nCachedObjects_,
  27812. n = bindings.length; i !== n; ++ i ) {
  27813. bindings[ i ].setValue( array, offset );
  27814. }
  27815. },
  27816. bind: function () {
  27817. var bindings = this._bindings;
  27818. for ( var i = this._targetGroup.nCachedObjects_,
  27819. n = bindings.length; i !== n; ++ i ) {
  27820. bindings[ i ].bind();
  27821. }
  27822. },
  27823. unbind: function () {
  27824. var bindings = this._bindings;
  27825. for ( var i = this._targetGroup.nCachedObjects_,
  27826. n = bindings.length; i !== n; ++ i ) {
  27827. bindings[ i ].unbind();
  27828. }
  27829. }
  27830. } );
  27831. function PropertyBinding( rootNode, path, parsedPath ) {
  27832. this.path = path;
  27833. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  27834. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  27835. this.rootNode = rootNode;
  27836. }
  27837. Object.assign( PropertyBinding, {
  27838. Composite: Composite,
  27839. create: function ( root, path, parsedPath ) {
  27840. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  27841. return new PropertyBinding( root, path, parsedPath );
  27842. } else {
  27843. return new PropertyBinding.Composite( root, path, parsedPath );
  27844. }
  27845. },
  27846. /**
  27847. * Replaces spaces with underscores and removes unsupported characters from
  27848. * node names, to ensure compatibility with parseTrackName().
  27849. *
  27850. * @param {string} name Node name to be sanitized.
  27851. * @return {string}
  27852. */
  27853. sanitizeNodeName: ( function () {
  27854. var reservedRe = new RegExp( '[' + RESERVED_CHARS_RE + ']', 'g' );
  27855. return function sanitizeNodeName( name ) {
  27856. return name.replace( /\s/g, '_' ).replace( reservedRe, '' );
  27857. };
  27858. }() ),
  27859. parseTrackName: function () {
  27860. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  27861. // only latin characters, and the unicode \p{L} is not yet supported. So
  27862. // instead, we exclude reserved characters and match everything else.
  27863. var wordChar = '[^' + RESERVED_CHARS_RE + ']';
  27864. var wordCharOrDot = '[^' + RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  27865. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  27866. // be matched to parse the rest of the track name.
  27867. var directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', wordChar );
  27868. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  27869. var nodeRe = /(WCOD+)?/.source.replace( 'WCOD', wordCharOrDot );
  27870. // Object on target node, and accessor. May not contain reserved
  27871. // characters. Accessor may contain any character except closing bracket.
  27872. var objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', wordChar );
  27873. // Property and accessor. May not contain reserved characters. Accessor may
  27874. // contain any non-bracket characters.
  27875. var propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', wordChar );
  27876. var trackRe = new RegExp( ''
  27877. + '^'
  27878. + directoryRe
  27879. + nodeRe
  27880. + objectRe
  27881. + propertyRe
  27882. + '$'
  27883. );
  27884. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  27885. return function parseTrackName( trackName ) {
  27886. var matches = trackRe.exec( trackName );
  27887. if ( ! matches ) {
  27888. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  27889. }
  27890. var results = {
  27891. // directoryName: matches[ 1 ], // (tschw) currently unused
  27892. nodeName: matches[ 2 ],
  27893. objectName: matches[ 3 ],
  27894. objectIndex: matches[ 4 ],
  27895. propertyName: matches[ 5 ], // required
  27896. propertyIndex: matches[ 6 ]
  27897. };
  27898. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  27899. if ( lastDot !== undefined && lastDot !== - 1 ) {
  27900. var objectName = results.nodeName.substring( lastDot + 1 );
  27901. // Object names must be checked against a whitelist. Otherwise, there
  27902. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  27903. // 'bar' could be the objectName, or part of a nodeName (which can
  27904. // include '.' characters).
  27905. if ( supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  27906. results.nodeName = results.nodeName.substring( 0, lastDot );
  27907. results.objectName = objectName;
  27908. }
  27909. }
  27910. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  27911. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  27912. }
  27913. return results;
  27914. };
  27915. }(),
  27916. findNode: function ( root, nodeName ) {
  27917. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  27918. return root;
  27919. }
  27920. // search into skeleton bones.
  27921. if ( root.skeleton ) {
  27922. var bone = root.skeleton.getBoneByName( nodeName );
  27923. if ( bone !== undefined ) {
  27924. return bone;
  27925. }
  27926. }
  27927. // search into node subtree.
  27928. if ( root.children ) {
  27929. var searchNodeSubtree = function ( children ) {
  27930. for ( var i = 0; i < children.length; i ++ ) {
  27931. var childNode = children[ i ];
  27932. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27933. return childNode;
  27934. }
  27935. var result = searchNodeSubtree( childNode.children );
  27936. if ( result ) return result;
  27937. }
  27938. return null;
  27939. };
  27940. var subTreeNode = searchNodeSubtree( root.children );
  27941. if ( subTreeNode ) {
  27942. return subTreeNode;
  27943. }
  27944. }
  27945. return null;
  27946. }
  27947. } );
  27948. Object.assign( PropertyBinding.prototype, { // prototype, continued
  27949. // these are used to "bind" a nonexistent property
  27950. _getValue_unavailable: function () {},
  27951. _setValue_unavailable: function () {},
  27952. BindingType: {
  27953. Direct: 0,
  27954. EntireArray: 1,
  27955. ArrayElement: 2,
  27956. HasFromToArray: 3
  27957. },
  27958. Versioning: {
  27959. None: 0,
  27960. NeedsUpdate: 1,
  27961. MatrixWorldNeedsUpdate: 2
  27962. },
  27963. GetterByBindingType: [
  27964. function getValue_direct( buffer, offset ) {
  27965. buffer[ offset ] = this.node[ this.propertyName ];
  27966. },
  27967. function getValue_array( buffer, offset ) {
  27968. var source = this.resolvedProperty;
  27969. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  27970. buffer[ offset ++ ] = source[ i ];
  27971. }
  27972. },
  27973. function getValue_arrayElement( buffer, offset ) {
  27974. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27975. },
  27976. function getValue_toArray( buffer, offset ) {
  27977. this.resolvedProperty.toArray( buffer, offset );
  27978. }
  27979. ],
  27980. SetterByBindingTypeAndVersioning: [
  27981. [
  27982. // Direct
  27983. function setValue_direct( buffer, offset ) {
  27984. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27985. },
  27986. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  27987. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27988. this.targetObject.needsUpdate = true;
  27989. },
  27990. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27991. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27992. this.targetObject.matrixWorldNeedsUpdate = true;
  27993. }
  27994. ], [
  27995. // EntireArray
  27996. function setValue_array( buffer, offset ) {
  27997. var dest = this.resolvedProperty;
  27998. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  27999. dest[ i ] = buffer[ offset ++ ];
  28000. }
  28001. },
  28002. function setValue_array_setNeedsUpdate( buffer, offset ) {
  28003. var dest = this.resolvedProperty;
  28004. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  28005. dest[ i ] = buffer[ offset ++ ];
  28006. }
  28007. this.targetObject.needsUpdate = true;
  28008. },
  28009. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28010. var dest = this.resolvedProperty;
  28011. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  28012. dest[ i ] = buffer[ offset ++ ];
  28013. }
  28014. this.targetObject.matrixWorldNeedsUpdate = true;
  28015. }
  28016. ], [
  28017. // ArrayElement
  28018. function setValue_arrayElement( buffer, offset ) {
  28019. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28020. },
  28021. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  28022. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28023. this.targetObject.needsUpdate = true;
  28024. },
  28025. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28026. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28027. this.targetObject.matrixWorldNeedsUpdate = true;
  28028. }
  28029. ], [
  28030. // HasToFromArray
  28031. function setValue_fromArray( buffer, offset ) {
  28032. this.resolvedProperty.fromArray( buffer, offset );
  28033. },
  28034. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  28035. this.resolvedProperty.fromArray( buffer, offset );
  28036. this.targetObject.needsUpdate = true;
  28037. },
  28038. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28039. this.resolvedProperty.fromArray( buffer, offset );
  28040. this.targetObject.matrixWorldNeedsUpdate = true;
  28041. }
  28042. ]
  28043. ],
  28044. getValue: function getValue_unbound( targetArray, offset ) {
  28045. this.bind();
  28046. this.getValue( targetArray, offset );
  28047. // Note: This class uses a State pattern on a per-method basis:
  28048. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  28049. // prototype version of these methods with one that represents
  28050. // the bound state. When the property is not found, the methods
  28051. // become no-ops.
  28052. },
  28053. setValue: function getValue_unbound( sourceArray, offset ) {
  28054. this.bind();
  28055. this.setValue( sourceArray, offset );
  28056. },
  28057. // create getter / setter pair for a property in the scene graph
  28058. bind: function () {
  28059. var targetObject = this.node,
  28060. parsedPath = this.parsedPath,
  28061. objectName = parsedPath.objectName,
  28062. propertyName = parsedPath.propertyName,
  28063. propertyIndex = parsedPath.propertyIndex;
  28064. if ( ! targetObject ) {
  28065. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  28066. this.node = targetObject;
  28067. }
  28068. // set fail state so we can just 'return' on error
  28069. this.getValue = this._getValue_unavailable;
  28070. this.setValue = this._setValue_unavailable;
  28071. // ensure there is a value node
  28072. if ( ! targetObject ) {
  28073. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  28074. return;
  28075. }
  28076. if ( objectName ) {
  28077. var objectIndex = parsedPath.objectIndex;
  28078. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  28079. switch ( objectName ) {
  28080. case 'materials':
  28081. if ( ! targetObject.material ) {
  28082. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28083. return;
  28084. }
  28085. if ( ! targetObject.material.materials ) {
  28086. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  28087. return;
  28088. }
  28089. targetObject = targetObject.material.materials;
  28090. break;
  28091. case 'bones':
  28092. if ( ! targetObject.skeleton ) {
  28093. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  28094. return;
  28095. }
  28096. // potential future optimization: skip this if propertyIndex is already an integer
  28097. // and convert the integer string to a true integer.
  28098. targetObject = targetObject.skeleton.bones;
  28099. // support resolving morphTarget names into indices.
  28100. for ( var i = 0; i < targetObject.length; i ++ ) {
  28101. if ( targetObject[ i ].name === objectIndex ) {
  28102. objectIndex = i;
  28103. break;
  28104. }
  28105. }
  28106. break;
  28107. default:
  28108. if ( targetObject[ objectName ] === undefined ) {
  28109. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  28110. return;
  28111. }
  28112. targetObject = targetObject[ objectName ];
  28113. }
  28114. if ( objectIndex !== undefined ) {
  28115. if ( targetObject[ objectIndex ] === undefined ) {
  28116. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  28117. return;
  28118. }
  28119. targetObject = targetObject[ objectIndex ];
  28120. }
  28121. }
  28122. // resolve property
  28123. var nodeProperty = targetObject[ propertyName ];
  28124. if ( nodeProperty === undefined ) {
  28125. var nodeName = parsedPath.nodeName;
  28126. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  28127. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  28128. return;
  28129. }
  28130. // determine versioning scheme
  28131. var versioning = this.Versioning.None;
  28132. if ( targetObject.needsUpdate !== undefined ) { // material
  28133. versioning = this.Versioning.NeedsUpdate;
  28134. this.targetObject = targetObject;
  28135. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  28136. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  28137. this.targetObject = targetObject;
  28138. }
  28139. // determine how the property gets bound
  28140. var bindingType = this.BindingType.Direct;
  28141. if ( propertyIndex !== undefined ) {
  28142. // access a sub element of the property array (only primitives are supported right now)
  28143. if ( propertyName === "morphTargetInfluences" ) {
  28144. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  28145. // support resolving morphTarget names into indices.
  28146. if ( ! targetObject.geometry ) {
  28147. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  28148. return;
  28149. }
  28150. if ( targetObject.geometry.isBufferGeometry ) {
  28151. if ( ! targetObject.geometry.morphAttributes ) {
  28152. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  28153. return;
  28154. }
  28155. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  28156. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  28157. propertyIndex = i;
  28158. break;
  28159. }
  28160. }
  28161. } else {
  28162. if ( ! targetObject.geometry.morphTargets ) {
  28163. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  28164. return;
  28165. }
  28166. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  28167. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  28168. propertyIndex = i;
  28169. break;
  28170. }
  28171. }
  28172. }
  28173. }
  28174. bindingType = this.BindingType.ArrayElement;
  28175. this.resolvedProperty = nodeProperty;
  28176. this.propertyIndex = propertyIndex;
  28177. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  28178. // must use copy for Object3D.Euler/Quaternion
  28179. bindingType = this.BindingType.HasFromToArray;
  28180. this.resolvedProperty = nodeProperty;
  28181. } else if ( Array.isArray( nodeProperty ) ) {
  28182. bindingType = this.BindingType.EntireArray;
  28183. this.resolvedProperty = nodeProperty;
  28184. } else {
  28185. this.propertyName = propertyName;
  28186. }
  28187. // select getter / setter
  28188. this.getValue = this.GetterByBindingType[ bindingType ];
  28189. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  28190. },
  28191. unbind: function () {
  28192. this.node = null;
  28193. // back to the prototype version of getValue / setValue
  28194. // note: avoiding to mutate the shape of 'this' via 'delete'
  28195. this.getValue = this._getValue_unbound;
  28196. this.setValue = this._setValue_unbound;
  28197. }
  28198. } );
  28199. //!\ DECLARE ALIAS AFTER assign prototype !
  28200. Object.assign( PropertyBinding.prototype, {
  28201. // initial state of these methods that calls 'bind'
  28202. _getValue_unbound: PropertyBinding.prototype.getValue,
  28203. _setValue_unbound: PropertyBinding.prototype.setValue,
  28204. } );
  28205. /**
  28206. *
  28207. * A group of objects that receives a shared animation state.
  28208. *
  28209. * Usage:
  28210. *
  28211. * - Add objects you would otherwise pass as 'root' to the
  28212. * constructor or the .clipAction method of AnimationMixer.
  28213. *
  28214. * - Instead pass this object as 'root'.
  28215. *
  28216. * - You can also add and remove objects later when the mixer
  28217. * is running.
  28218. *
  28219. * Note:
  28220. *
  28221. * Objects of this class appear as one object to the mixer,
  28222. * so cache control of the individual objects must be done
  28223. * on the group.
  28224. *
  28225. * Limitation:
  28226. *
  28227. * - The animated properties must be compatible among the
  28228. * all objects in the group.
  28229. *
  28230. * - A single property can either be controlled through a
  28231. * target group or directly, but not both.
  28232. *
  28233. * @author tschw
  28234. */
  28235. function AnimationObjectGroup() {
  28236. this.uuid = _Math.generateUUID();
  28237. // cached objects followed by the active ones
  28238. this._objects = Array.prototype.slice.call( arguments );
  28239. this.nCachedObjects_ = 0; // threshold
  28240. // note: read by PropertyBinding.Composite
  28241. var indices = {};
  28242. this._indicesByUUID = indices; // for bookkeeping
  28243. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28244. indices[ arguments[ i ].uuid ] = i;
  28245. }
  28246. this._paths = []; // inside: string
  28247. this._parsedPaths = []; // inside: { we don't care, here }
  28248. this._bindings = []; // inside: Array< PropertyBinding >
  28249. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  28250. var scope = this;
  28251. this.stats = {
  28252. objects: {
  28253. get total() {
  28254. return scope._objects.length;
  28255. },
  28256. get inUse() {
  28257. return this.total - scope.nCachedObjects_;
  28258. }
  28259. },
  28260. get bindingsPerObject() {
  28261. return scope._bindings.length;
  28262. }
  28263. };
  28264. }
  28265. Object.assign( AnimationObjectGroup.prototype, {
  28266. isAnimationObjectGroup: true,
  28267. add: function () {
  28268. var objects = this._objects,
  28269. nObjects = objects.length,
  28270. nCachedObjects = this.nCachedObjects_,
  28271. indicesByUUID = this._indicesByUUID,
  28272. paths = this._paths,
  28273. parsedPaths = this._parsedPaths,
  28274. bindings = this._bindings,
  28275. nBindings = bindings.length,
  28276. knownObject = undefined;
  28277. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28278. var object = arguments[ i ],
  28279. uuid = object.uuid,
  28280. index = indicesByUUID[ uuid ];
  28281. if ( index === undefined ) {
  28282. // unknown object -> add it to the ACTIVE region
  28283. index = nObjects ++;
  28284. indicesByUUID[ uuid ] = index;
  28285. objects.push( object );
  28286. // accounting is done, now do the same for all bindings
  28287. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28288. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  28289. }
  28290. } else if ( index < nCachedObjects ) {
  28291. knownObject = objects[ index ];
  28292. // move existing object to the ACTIVE region
  28293. var firstActiveIndex = -- nCachedObjects,
  28294. lastCachedObject = objects[ firstActiveIndex ];
  28295. indicesByUUID[ lastCachedObject.uuid ] = index;
  28296. objects[ index ] = lastCachedObject;
  28297. indicesByUUID[ uuid ] = firstActiveIndex;
  28298. objects[ firstActiveIndex ] = object;
  28299. // accounting is done, now do the same for all bindings
  28300. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28301. var bindingsForPath = bindings[ j ],
  28302. lastCached = bindingsForPath[ firstActiveIndex ],
  28303. binding = bindingsForPath[ index ];
  28304. bindingsForPath[ index ] = lastCached;
  28305. if ( binding === undefined ) {
  28306. // since we do not bother to create new bindings
  28307. // for objects that are cached, the binding may
  28308. // or may not exist
  28309. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  28310. }
  28311. bindingsForPath[ firstActiveIndex ] = binding;
  28312. }
  28313. } else if ( objects[ index ] !== knownObject ) {
  28314. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  28315. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  28316. } // else the object is already where we want it to be
  28317. } // for arguments
  28318. this.nCachedObjects_ = nCachedObjects;
  28319. },
  28320. remove: function () {
  28321. var objects = this._objects,
  28322. nCachedObjects = this.nCachedObjects_,
  28323. indicesByUUID = this._indicesByUUID,
  28324. bindings = this._bindings,
  28325. nBindings = bindings.length;
  28326. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28327. var object = arguments[ i ],
  28328. uuid = object.uuid,
  28329. index = indicesByUUID[ uuid ];
  28330. if ( index !== undefined && index >= nCachedObjects ) {
  28331. // move existing object into the CACHED region
  28332. var lastCachedIndex = nCachedObjects ++,
  28333. firstActiveObject = objects[ lastCachedIndex ];
  28334. indicesByUUID[ firstActiveObject.uuid ] = index;
  28335. objects[ index ] = firstActiveObject;
  28336. indicesByUUID[ uuid ] = lastCachedIndex;
  28337. objects[ lastCachedIndex ] = object;
  28338. // accounting is done, now do the same for all bindings
  28339. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28340. var bindingsForPath = bindings[ j ],
  28341. firstActive = bindingsForPath[ lastCachedIndex ],
  28342. binding = bindingsForPath[ index ];
  28343. bindingsForPath[ index ] = firstActive;
  28344. bindingsForPath[ lastCachedIndex ] = binding;
  28345. }
  28346. }
  28347. } // for arguments
  28348. this.nCachedObjects_ = nCachedObjects;
  28349. },
  28350. // remove & forget
  28351. uncache: function () {
  28352. var objects = this._objects,
  28353. nObjects = objects.length,
  28354. nCachedObjects = this.nCachedObjects_,
  28355. indicesByUUID = this._indicesByUUID,
  28356. bindings = this._bindings,
  28357. nBindings = bindings.length;
  28358. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28359. var object = arguments[ i ],
  28360. uuid = object.uuid,
  28361. index = indicesByUUID[ uuid ];
  28362. if ( index !== undefined ) {
  28363. delete indicesByUUID[ uuid ];
  28364. if ( index < nCachedObjects ) {
  28365. // object is cached, shrink the CACHED region
  28366. var firstActiveIndex = -- nCachedObjects,
  28367. lastCachedObject = objects[ firstActiveIndex ],
  28368. lastIndex = -- nObjects,
  28369. lastObject = objects[ lastIndex ];
  28370. // last cached object takes this object's place
  28371. indicesByUUID[ lastCachedObject.uuid ] = index;
  28372. objects[ index ] = lastCachedObject;
  28373. // last object goes to the activated slot and pop
  28374. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  28375. objects[ firstActiveIndex ] = lastObject;
  28376. objects.pop();
  28377. // accounting is done, now do the same for all bindings
  28378. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28379. var bindingsForPath = bindings[ j ],
  28380. lastCached = bindingsForPath[ firstActiveIndex ],
  28381. last = bindingsForPath[ lastIndex ];
  28382. bindingsForPath[ index ] = lastCached;
  28383. bindingsForPath[ firstActiveIndex ] = last;
  28384. bindingsForPath.pop();
  28385. }
  28386. } else {
  28387. // object is active, just swap with the last and pop
  28388. var lastIndex = -- nObjects,
  28389. lastObject = objects[ lastIndex ];
  28390. indicesByUUID[ lastObject.uuid ] = index;
  28391. objects[ index ] = lastObject;
  28392. objects.pop();
  28393. // accounting is done, now do the same for all bindings
  28394. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28395. var bindingsForPath = bindings[ j ];
  28396. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  28397. bindingsForPath.pop();
  28398. }
  28399. } // cached or active
  28400. } // if object is known
  28401. } // for arguments
  28402. this.nCachedObjects_ = nCachedObjects;
  28403. },
  28404. // Internal interface used by befriended PropertyBinding.Composite:
  28405. subscribe_: function ( path, parsedPath ) {
  28406. // returns an array of bindings for the given path that is changed
  28407. // according to the contained objects in the group
  28408. var indicesByPath = this._bindingsIndicesByPath,
  28409. index = indicesByPath[ path ],
  28410. bindings = this._bindings;
  28411. if ( index !== undefined ) return bindings[ index ];
  28412. var paths = this._paths,
  28413. parsedPaths = this._parsedPaths,
  28414. objects = this._objects,
  28415. nObjects = objects.length,
  28416. nCachedObjects = this.nCachedObjects_,
  28417. bindingsForPath = new Array( nObjects );
  28418. index = bindings.length;
  28419. indicesByPath[ path ] = index;
  28420. paths.push( path );
  28421. parsedPaths.push( parsedPath );
  28422. bindings.push( bindingsForPath );
  28423. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  28424. var object = objects[ i ];
  28425. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  28426. }
  28427. return bindingsForPath;
  28428. },
  28429. unsubscribe_: function ( path ) {
  28430. // tells the group to forget about a property path and no longer
  28431. // update the array previously obtained with 'subscribe_'
  28432. var indicesByPath = this._bindingsIndicesByPath,
  28433. index = indicesByPath[ path ];
  28434. if ( index !== undefined ) {
  28435. var paths = this._paths,
  28436. parsedPaths = this._parsedPaths,
  28437. bindings = this._bindings,
  28438. lastBindingsIndex = bindings.length - 1,
  28439. lastBindings = bindings[ lastBindingsIndex ],
  28440. lastBindingsPath = path[ lastBindingsIndex ];
  28441. indicesByPath[ lastBindingsPath ] = index;
  28442. bindings[ index ] = lastBindings;
  28443. bindings.pop();
  28444. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  28445. parsedPaths.pop();
  28446. paths[ index ] = paths[ lastBindingsIndex ];
  28447. paths.pop();
  28448. }
  28449. }
  28450. } );
  28451. /**
  28452. *
  28453. * Action provided by AnimationMixer for scheduling clip playback on specific
  28454. * objects.
  28455. *
  28456. * @author Ben Houston / http://clara.io/
  28457. * @author David Sarno / http://lighthaus.us/
  28458. * @author tschw
  28459. *
  28460. */
  28461. function AnimationAction( mixer, clip, localRoot ) {
  28462. this._mixer = mixer;
  28463. this._clip = clip;
  28464. this._localRoot = localRoot || null;
  28465. var tracks = clip.tracks,
  28466. nTracks = tracks.length,
  28467. interpolants = new Array( nTracks );
  28468. var interpolantSettings = {
  28469. endingStart: ZeroCurvatureEnding,
  28470. endingEnd: ZeroCurvatureEnding
  28471. };
  28472. for ( var i = 0; i !== nTracks; ++ i ) {
  28473. var interpolant = tracks[ i ].createInterpolant( null );
  28474. interpolants[ i ] = interpolant;
  28475. interpolant.settings = interpolantSettings;
  28476. }
  28477. this._interpolantSettings = interpolantSettings;
  28478. this._interpolants = interpolants; // bound by the mixer
  28479. // inside: PropertyMixer (managed by the mixer)
  28480. this._propertyBindings = new Array( nTracks );
  28481. this._cacheIndex = null; // for the memory manager
  28482. this._byClipCacheIndex = null; // for the memory manager
  28483. this._timeScaleInterpolant = null;
  28484. this._weightInterpolant = null;
  28485. this.loop = LoopRepeat;
  28486. this._loopCount = - 1;
  28487. // global mixer time when the action is to be started
  28488. // it's set back to 'null' upon start of the action
  28489. this._startTime = null;
  28490. // scaled local time of the action
  28491. // gets clamped or wrapped to 0..clip.duration according to loop
  28492. this.time = 0;
  28493. this.timeScale = 1;
  28494. this._effectiveTimeScale = 1;
  28495. this.weight = 1;
  28496. this._effectiveWeight = 1;
  28497. this.repetitions = Infinity; // no. of repetitions when looping
  28498. this.paused = false; // true -> zero effective time scale
  28499. this.enabled = true; // false -> zero effective weight
  28500. this.clampWhenFinished = false; // keep feeding the last frame?
  28501. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  28502. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  28503. }
  28504. Object.assign( AnimationAction.prototype, {
  28505. // State & Scheduling
  28506. play: function () {
  28507. this._mixer._activateAction( this );
  28508. return this;
  28509. },
  28510. stop: function () {
  28511. this._mixer._deactivateAction( this );
  28512. return this.reset();
  28513. },
  28514. reset: function () {
  28515. this.paused = false;
  28516. this.enabled = true;
  28517. this.time = 0; // restart clip
  28518. this._loopCount = - 1; // forget previous loops
  28519. this._startTime = null; // forget scheduling
  28520. return this.stopFading().stopWarping();
  28521. },
  28522. isRunning: function () {
  28523. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  28524. this._startTime === null && this._mixer._isActiveAction( this );
  28525. },
  28526. // return true when play has been called
  28527. isScheduled: function () {
  28528. return this._mixer._isActiveAction( this );
  28529. },
  28530. startAt: function ( time ) {
  28531. this._startTime = time;
  28532. return this;
  28533. },
  28534. setLoop: function ( mode, repetitions ) {
  28535. this.loop = mode;
  28536. this.repetitions = repetitions;
  28537. return this;
  28538. },
  28539. // Weight
  28540. // set the weight stopping any scheduled fading
  28541. // although .enabled = false yields an effective weight of zero, this
  28542. // method does *not* change .enabled, because it would be confusing
  28543. setEffectiveWeight: function ( weight ) {
  28544. this.weight = weight;
  28545. // note: same logic as when updated at runtime
  28546. this._effectiveWeight = this.enabled ? weight : 0;
  28547. return this.stopFading();
  28548. },
  28549. // return the weight considering fading and .enabled
  28550. getEffectiveWeight: function () {
  28551. return this._effectiveWeight;
  28552. },
  28553. fadeIn: function ( duration ) {
  28554. return this._scheduleFading( duration, 0, 1 );
  28555. },
  28556. fadeOut: function ( duration ) {
  28557. return this._scheduleFading( duration, 1, 0 );
  28558. },
  28559. crossFadeFrom: function ( fadeOutAction, duration, warp ) {
  28560. fadeOutAction.fadeOut( duration );
  28561. this.fadeIn( duration );
  28562. if ( warp ) {
  28563. var fadeInDuration = this._clip.duration,
  28564. fadeOutDuration = fadeOutAction._clip.duration,
  28565. startEndRatio = fadeOutDuration / fadeInDuration,
  28566. endStartRatio = fadeInDuration / fadeOutDuration;
  28567. fadeOutAction.warp( 1.0, startEndRatio, duration );
  28568. this.warp( endStartRatio, 1.0, duration );
  28569. }
  28570. return this;
  28571. },
  28572. crossFadeTo: function ( fadeInAction, duration, warp ) {
  28573. return fadeInAction.crossFadeFrom( this, duration, warp );
  28574. },
  28575. stopFading: function () {
  28576. var weightInterpolant = this._weightInterpolant;
  28577. if ( weightInterpolant !== null ) {
  28578. this._weightInterpolant = null;
  28579. this._mixer._takeBackControlInterpolant( weightInterpolant );
  28580. }
  28581. return this;
  28582. },
  28583. // Time Scale Control
  28584. // set the time scale stopping any scheduled warping
  28585. // although .paused = true yields an effective time scale of zero, this
  28586. // method does *not* change .paused, because it would be confusing
  28587. setEffectiveTimeScale: function ( timeScale ) {
  28588. this.timeScale = timeScale;
  28589. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  28590. return this.stopWarping();
  28591. },
  28592. // return the time scale considering warping and .paused
  28593. getEffectiveTimeScale: function () {
  28594. return this._effectiveTimeScale;
  28595. },
  28596. setDuration: function ( duration ) {
  28597. this.timeScale = this._clip.duration / duration;
  28598. return this.stopWarping();
  28599. },
  28600. syncWith: function ( action ) {
  28601. this.time = action.time;
  28602. this.timeScale = action.timeScale;
  28603. return this.stopWarping();
  28604. },
  28605. halt: function ( duration ) {
  28606. return this.warp( this._effectiveTimeScale, 0, duration );
  28607. },
  28608. warp: function ( startTimeScale, endTimeScale, duration ) {
  28609. var mixer = this._mixer, now = mixer.time,
  28610. interpolant = this._timeScaleInterpolant,
  28611. timeScale = this.timeScale;
  28612. if ( interpolant === null ) {
  28613. interpolant = mixer._lendControlInterpolant();
  28614. this._timeScaleInterpolant = interpolant;
  28615. }
  28616. var times = interpolant.parameterPositions,
  28617. values = interpolant.sampleValues;
  28618. times[ 0 ] = now;
  28619. times[ 1 ] = now + duration;
  28620. values[ 0 ] = startTimeScale / timeScale;
  28621. values[ 1 ] = endTimeScale / timeScale;
  28622. return this;
  28623. },
  28624. stopWarping: function () {
  28625. var timeScaleInterpolant = this._timeScaleInterpolant;
  28626. if ( timeScaleInterpolant !== null ) {
  28627. this._timeScaleInterpolant = null;
  28628. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  28629. }
  28630. return this;
  28631. },
  28632. // Object Accessors
  28633. getMixer: function () {
  28634. return this._mixer;
  28635. },
  28636. getClip: function () {
  28637. return this._clip;
  28638. },
  28639. getRoot: function () {
  28640. return this._localRoot || this._mixer._root;
  28641. },
  28642. // Interna
  28643. _update: function ( time, deltaTime, timeDirection, accuIndex ) {
  28644. // called by the mixer
  28645. if ( ! this.enabled ) {
  28646. // call ._updateWeight() to update ._effectiveWeight
  28647. this._updateWeight( time );
  28648. return;
  28649. }
  28650. var startTime = this._startTime;
  28651. if ( startTime !== null ) {
  28652. // check for scheduled start of action
  28653. var timeRunning = ( time - startTime ) * timeDirection;
  28654. if ( timeRunning < 0 || timeDirection === 0 ) {
  28655. return; // yet to come / don't decide when delta = 0
  28656. }
  28657. // start
  28658. this._startTime = null; // unschedule
  28659. deltaTime = timeDirection * timeRunning;
  28660. }
  28661. // apply time scale and advance time
  28662. deltaTime *= this._updateTimeScale( time );
  28663. var clipTime = this._updateTime( deltaTime );
  28664. // note: _updateTime may disable the action resulting in
  28665. // an effective weight of 0
  28666. var weight = this._updateWeight( time );
  28667. if ( weight > 0 ) {
  28668. var interpolants = this._interpolants;
  28669. var propertyMixers = this._propertyBindings;
  28670. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  28671. interpolants[ j ].evaluate( clipTime );
  28672. propertyMixers[ j ].accumulate( accuIndex, weight );
  28673. }
  28674. }
  28675. },
  28676. _updateWeight: function ( time ) {
  28677. var weight = 0;
  28678. if ( this.enabled ) {
  28679. weight = this.weight;
  28680. var interpolant = this._weightInterpolant;
  28681. if ( interpolant !== null ) {
  28682. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  28683. weight *= interpolantValue;
  28684. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28685. this.stopFading();
  28686. if ( interpolantValue === 0 ) {
  28687. // faded out, disable
  28688. this.enabled = false;
  28689. }
  28690. }
  28691. }
  28692. }
  28693. this._effectiveWeight = weight;
  28694. return weight;
  28695. },
  28696. _updateTimeScale: function ( time ) {
  28697. var timeScale = 0;
  28698. if ( ! this.paused ) {
  28699. timeScale = this.timeScale;
  28700. var interpolant = this._timeScaleInterpolant;
  28701. if ( interpolant !== null ) {
  28702. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  28703. timeScale *= interpolantValue;
  28704. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28705. this.stopWarping();
  28706. if ( timeScale === 0 ) {
  28707. // motion has halted, pause
  28708. this.paused = true;
  28709. } else {
  28710. // warp done - apply final time scale
  28711. this.timeScale = timeScale;
  28712. }
  28713. }
  28714. }
  28715. }
  28716. this._effectiveTimeScale = timeScale;
  28717. return timeScale;
  28718. },
  28719. _updateTime: function ( deltaTime ) {
  28720. var time = this.time + deltaTime;
  28721. if ( deltaTime === 0 ) return time;
  28722. var duration = this._clip.duration,
  28723. loop = this.loop,
  28724. loopCount = this._loopCount;
  28725. if ( loop === LoopOnce ) {
  28726. if ( loopCount === - 1 ) {
  28727. // just started
  28728. this._loopCount = 0;
  28729. this._setEndings( true, true, false );
  28730. }
  28731. handle_stop: {
  28732. if ( time >= duration ) {
  28733. time = duration;
  28734. } else if ( time < 0 ) {
  28735. time = 0;
  28736. } else break handle_stop;
  28737. if ( this.clampWhenFinished ) this.paused = true;
  28738. else this.enabled = false;
  28739. this._mixer.dispatchEvent( {
  28740. type: 'finished', action: this,
  28741. direction: deltaTime < 0 ? - 1 : 1
  28742. } );
  28743. }
  28744. } else { // repetitive Repeat or PingPong
  28745. var pingPong = ( loop === LoopPingPong );
  28746. if ( loopCount === - 1 ) {
  28747. // just started
  28748. if ( deltaTime >= 0 ) {
  28749. loopCount = 0;
  28750. this._setEndings( true, this.repetitions === 0, pingPong );
  28751. } else {
  28752. // when looping in reverse direction, the initial
  28753. // transition through zero counts as a repetition,
  28754. // so leave loopCount at -1
  28755. this._setEndings( this.repetitions === 0, true, pingPong );
  28756. }
  28757. }
  28758. if ( time >= duration || time < 0 ) {
  28759. // wrap around
  28760. var loopDelta = Math.floor( time / duration ); // signed
  28761. time -= duration * loopDelta;
  28762. loopCount += Math.abs( loopDelta );
  28763. var pending = this.repetitions - loopCount;
  28764. if ( pending <= 0 ) {
  28765. // have to stop (switch state, clamp time, fire event)
  28766. if ( this.clampWhenFinished ) this.paused = true;
  28767. else this.enabled = false;
  28768. time = deltaTime > 0 ? duration : 0;
  28769. this._mixer.dispatchEvent( {
  28770. type: 'finished', action: this,
  28771. direction: deltaTime > 0 ? 1 : - 1
  28772. } );
  28773. } else {
  28774. // keep running
  28775. if ( pending === 1 ) {
  28776. // entering the last round
  28777. var atStart = deltaTime < 0;
  28778. this._setEndings( atStart, ! atStart, pingPong );
  28779. } else {
  28780. this._setEndings( false, false, pingPong );
  28781. }
  28782. this._loopCount = loopCount;
  28783. this._mixer.dispatchEvent( {
  28784. type: 'loop', action: this, loopDelta: loopDelta
  28785. } );
  28786. }
  28787. }
  28788. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  28789. // invert time for the "pong round"
  28790. this.time = time;
  28791. return duration - time;
  28792. }
  28793. }
  28794. this.time = time;
  28795. return time;
  28796. },
  28797. _setEndings: function ( atStart, atEnd, pingPong ) {
  28798. var settings = this._interpolantSettings;
  28799. if ( pingPong ) {
  28800. settings.endingStart = ZeroSlopeEnding;
  28801. settings.endingEnd = ZeroSlopeEnding;
  28802. } else {
  28803. // assuming for LoopOnce atStart == atEnd == true
  28804. if ( atStart ) {
  28805. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28806. } else {
  28807. settings.endingStart = WrapAroundEnding;
  28808. }
  28809. if ( atEnd ) {
  28810. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28811. } else {
  28812. settings.endingEnd = WrapAroundEnding;
  28813. }
  28814. }
  28815. },
  28816. _scheduleFading: function ( duration, weightNow, weightThen ) {
  28817. var mixer = this._mixer, now = mixer.time,
  28818. interpolant = this._weightInterpolant;
  28819. if ( interpolant === null ) {
  28820. interpolant = mixer._lendControlInterpolant();
  28821. this._weightInterpolant = interpolant;
  28822. }
  28823. var times = interpolant.parameterPositions,
  28824. values = interpolant.sampleValues;
  28825. times[ 0 ] = now; values[ 0 ] = weightNow;
  28826. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  28827. return this;
  28828. }
  28829. } );
  28830. /**
  28831. *
  28832. * Player for AnimationClips.
  28833. *
  28834. *
  28835. * @author Ben Houston / http://clara.io/
  28836. * @author David Sarno / http://lighthaus.us/
  28837. * @author tschw
  28838. */
  28839. function AnimationMixer( root ) {
  28840. this._root = root;
  28841. this._initMemoryManager();
  28842. this._accuIndex = 0;
  28843. this.time = 0;
  28844. this.timeScale = 1.0;
  28845. }
  28846. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  28847. constructor: AnimationMixer,
  28848. _bindAction: function ( action, prototypeAction ) {
  28849. var root = action._localRoot || this._root,
  28850. tracks = action._clip.tracks,
  28851. nTracks = tracks.length,
  28852. bindings = action._propertyBindings,
  28853. interpolants = action._interpolants,
  28854. rootUuid = root.uuid,
  28855. bindingsByRoot = this._bindingsByRootAndName,
  28856. bindingsByName = bindingsByRoot[ rootUuid ];
  28857. if ( bindingsByName === undefined ) {
  28858. bindingsByName = {};
  28859. bindingsByRoot[ rootUuid ] = bindingsByName;
  28860. }
  28861. for ( var i = 0; i !== nTracks; ++ i ) {
  28862. var track = tracks[ i ],
  28863. trackName = track.name,
  28864. binding = bindingsByName[ trackName ];
  28865. if ( binding !== undefined ) {
  28866. bindings[ i ] = binding;
  28867. } else {
  28868. binding = bindings[ i ];
  28869. if ( binding !== undefined ) {
  28870. // existing binding, make sure the cache knows
  28871. if ( binding._cacheIndex === null ) {
  28872. ++ binding.referenceCount;
  28873. this._addInactiveBinding( binding, rootUuid, trackName );
  28874. }
  28875. continue;
  28876. }
  28877. var path = prototypeAction && prototypeAction.
  28878. _propertyBindings[ i ].binding.parsedPath;
  28879. binding = new PropertyMixer(
  28880. PropertyBinding.create( root, trackName, path ),
  28881. track.ValueTypeName, track.getValueSize() );
  28882. ++ binding.referenceCount;
  28883. this._addInactiveBinding( binding, rootUuid, trackName );
  28884. bindings[ i ] = binding;
  28885. }
  28886. interpolants[ i ].resultBuffer = binding.buffer;
  28887. }
  28888. },
  28889. _activateAction: function ( action ) {
  28890. if ( ! this._isActiveAction( action ) ) {
  28891. if ( action._cacheIndex === null ) {
  28892. // this action has been forgotten by the cache, but the user
  28893. // appears to be still using it -> rebind
  28894. var rootUuid = ( action._localRoot || this._root ).uuid,
  28895. clipUuid = action._clip.uuid,
  28896. actionsForClip = this._actionsByClip[ clipUuid ];
  28897. this._bindAction( action,
  28898. actionsForClip && actionsForClip.knownActions[ 0 ] );
  28899. this._addInactiveAction( action, clipUuid, rootUuid );
  28900. }
  28901. var bindings = action._propertyBindings;
  28902. // increment reference counts / sort out state
  28903. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  28904. var binding = bindings[ i ];
  28905. if ( binding.useCount ++ === 0 ) {
  28906. this._lendBinding( binding );
  28907. binding.saveOriginalState();
  28908. }
  28909. }
  28910. this._lendAction( action );
  28911. }
  28912. },
  28913. _deactivateAction: function ( action ) {
  28914. if ( this._isActiveAction( action ) ) {
  28915. var bindings = action._propertyBindings;
  28916. // decrement reference counts / sort out state
  28917. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  28918. var binding = bindings[ i ];
  28919. if ( -- binding.useCount === 0 ) {
  28920. binding.restoreOriginalState();
  28921. this._takeBackBinding( binding );
  28922. }
  28923. }
  28924. this._takeBackAction( action );
  28925. }
  28926. },
  28927. // Memory manager
  28928. _initMemoryManager: function () {
  28929. this._actions = []; // 'nActiveActions' followed by inactive ones
  28930. this._nActiveActions = 0;
  28931. this._actionsByClip = {};
  28932. // inside:
  28933. // {
  28934. // knownActions: Array< AnimationAction > - used as prototypes
  28935. // actionByRoot: AnimationAction - lookup
  28936. // }
  28937. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28938. this._nActiveBindings = 0;
  28939. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28940. this._controlInterpolants = []; // same game as above
  28941. this._nActiveControlInterpolants = 0;
  28942. var scope = this;
  28943. this.stats = {
  28944. actions: {
  28945. get total() {
  28946. return scope._actions.length;
  28947. },
  28948. get inUse() {
  28949. return scope._nActiveActions;
  28950. }
  28951. },
  28952. bindings: {
  28953. get total() {
  28954. return scope._bindings.length;
  28955. },
  28956. get inUse() {
  28957. return scope._nActiveBindings;
  28958. }
  28959. },
  28960. controlInterpolants: {
  28961. get total() {
  28962. return scope._controlInterpolants.length;
  28963. },
  28964. get inUse() {
  28965. return scope._nActiveControlInterpolants;
  28966. }
  28967. }
  28968. };
  28969. },
  28970. // Memory management for AnimationAction objects
  28971. _isActiveAction: function ( action ) {
  28972. var index = action._cacheIndex;
  28973. return index !== null && index < this._nActiveActions;
  28974. },
  28975. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  28976. var actions = this._actions,
  28977. actionsByClip = this._actionsByClip,
  28978. actionsForClip = actionsByClip[ clipUuid ];
  28979. if ( actionsForClip === undefined ) {
  28980. actionsForClip = {
  28981. knownActions: [ action ],
  28982. actionByRoot: {}
  28983. };
  28984. action._byClipCacheIndex = 0;
  28985. actionsByClip[ clipUuid ] = actionsForClip;
  28986. } else {
  28987. var knownActions = actionsForClip.knownActions;
  28988. action._byClipCacheIndex = knownActions.length;
  28989. knownActions.push( action );
  28990. }
  28991. action._cacheIndex = actions.length;
  28992. actions.push( action );
  28993. actionsForClip.actionByRoot[ rootUuid ] = action;
  28994. },
  28995. _removeInactiveAction: function ( action ) {
  28996. var actions = this._actions,
  28997. lastInactiveAction = actions[ actions.length - 1 ],
  28998. cacheIndex = action._cacheIndex;
  28999. lastInactiveAction._cacheIndex = cacheIndex;
  29000. actions[ cacheIndex ] = lastInactiveAction;
  29001. actions.pop();
  29002. action._cacheIndex = null;
  29003. var clipUuid = action._clip.uuid,
  29004. actionsByClip = this._actionsByClip,
  29005. actionsForClip = actionsByClip[ clipUuid ],
  29006. knownActionsForClip = actionsForClip.knownActions,
  29007. lastKnownAction =
  29008. knownActionsForClip[ knownActionsForClip.length - 1 ],
  29009. byClipCacheIndex = action._byClipCacheIndex;
  29010. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  29011. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  29012. knownActionsForClip.pop();
  29013. action._byClipCacheIndex = null;
  29014. var actionByRoot = actionsForClip.actionByRoot,
  29015. rootUuid = ( action._localRoot || this._root ).uuid;
  29016. delete actionByRoot[ rootUuid ];
  29017. if ( knownActionsForClip.length === 0 ) {
  29018. delete actionsByClip[ clipUuid ];
  29019. }
  29020. this._removeInactiveBindingsForAction( action );
  29021. },
  29022. _removeInactiveBindingsForAction: function ( action ) {
  29023. var bindings = action._propertyBindings;
  29024. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  29025. var binding = bindings[ i ];
  29026. if ( -- binding.referenceCount === 0 ) {
  29027. this._removeInactiveBinding( binding );
  29028. }
  29029. }
  29030. },
  29031. _lendAction: function ( action ) {
  29032. // [ active actions | inactive actions ]
  29033. // [ active actions >| inactive actions ]
  29034. // s a
  29035. // <-swap->
  29036. // a s
  29037. var actions = this._actions,
  29038. prevIndex = action._cacheIndex,
  29039. lastActiveIndex = this._nActiveActions ++,
  29040. firstInactiveAction = actions[ lastActiveIndex ];
  29041. action._cacheIndex = lastActiveIndex;
  29042. actions[ lastActiveIndex ] = action;
  29043. firstInactiveAction._cacheIndex = prevIndex;
  29044. actions[ prevIndex ] = firstInactiveAction;
  29045. },
  29046. _takeBackAction: function ( action ) {
  29047. // [ active actions | inactive actions ]
  29048. // [ active actions |< inactive actions ]
  29049. // a s
  29050. // <-swap->
  29051. // s a
  29052. var actions = this._actions,
  29053. prevIndex = action._cacheIndex,
  29054. firstInactiveIndex = -- this._nActiveActions,
  29055. lastActiveAction = actions[ firstInactiveIndex ];
  29056. action._cacheIndex = firstInactiveIndex;
  29057. actions[ firstInactiveIndex ] = action;
  29058. lastActiveAction._cacheIndex = prevIndex;
  29059. actions[ prevIndex ] = lastActiveAction;
  29060. },
  29061. // Memory management for PropertyMixer objects
  29062. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  29063. var bindingsByRoot = this._bindingsByRootAndName,
  29064. bindingByName = bindingsByRoot[ rootUuid ],
  29065. bindings = this._bindings;
  29066. if ( bindingByName === undefined ) {
  29067. bindingByName = {};
  29068. bindingsByRoot[ rootUuid ] = bindingByName;
  29069. }
  29070. bindingByName[ trackName ] = binding;
  29071. binding._cacheIndex = bindings.length;
  29072. bindings.push( binding );
  29073. },
  29074. _removeInactiveBinding: function ( binding ) {
  29075. var bindings = this._bindings,
  29076. propBinding = binding.binding,
  29077. rootUuid = propBinding.rootNode.uuid,
  29078. trackName = propBinding.path,
  29079. bindingsByRoot = this._bindingsByRootAndName,
  29080. bindingByName = bindingsByRoot[ rootUuid ],
  29081. lastInactiveBinding = bindings[ bindings.length - 1 ],
  29082. cacheIndex = binding._cacheIndex;
  29083. lastInactiveBinding._cacheIndex = cacheIndex;
  29084. bindings[ cacheIndex ] = lastInactiveBinding;
  29085. bindings.pop();
  29086. delete bindingByName[ trackName ];
  29087. remove_empty_map: {
  29088. for ( var _ in bindingByName ) break remove_empty_map; // eslint-disable-line no-unused-vars
  29089. delete bindingsByRoot[ rootUuid ];
  29090. }
  29091. },
  29092. _lendBinding: function ( binding ) {
  29093. var bindings = this._bindings,
  29094. prevIndex = binding._cacheIndex,
  29095. lastActiveIndex = this._nActiveBindings ++,
  29096. firstInactiveBinding = bindings[ lastActiveIndex ];
  29097. binding._cacheIndex = lastActiveIndex;
  29098. bindings[ lastActiveIndex ] = binding;
  29099. firstInactiveBinding._cacheIndex = prevIndex;
  29100. bindings[ prevIndex ] = firstInactiveBinding;
  29101. },
  29102. _takeBackBinding: function ( binding ) {
  29103. var bindings = this._bindings,
  29104. prevIndex = binding._cacheIndex,
  29105. firstInactiveIndex = -- this._nActiveBindings,
  29106. lastActiveBinding = bindings[ firstInactiveIndex ];
  29107. binding._cacheIndex = firstInactiveIndex;
  29108. bindings[ firstInactiveIndex ] = binding;
  29109. lastActiveBinding._cacheIndex = prevIndex;
  29110. bindings[ prevIndex ] = lastActiveBinding;
  29111. },
  29112. // Memory management of Interpolants for weight and time scale
  29113. _lendControlInterpolant: function () {
  29114. var interpolants = this._controlInterpolants,
  29115. lastActiveIndex = this._nActiveControlInterpolants ++,
  29116. interpolant = interpolants[ lastActiveIndex ];
  29117. if ( interpolant === undefined ) {
  29118. interpolant = new LinearInterpolant(
  29119. new Float32Array( 2 ), new Float32Array( 2 ),
  29120. 1, this._controlInterpolantsResultBuffer );
  29121. interpolant.__cacheIndex = lastActiveIndex;
  29122. interpolants[ lastActiveIndex ] = interpolant;
  29123. }
  29124. return interpolant;
  29125. },
  29126. _takeBackControlInterpolant: function ( interpolant ) {
  29127. var interpolants = this._controlInterpolants,
  29128. prevIndex = interpolant.__cacheIndex,
  29129. firstInactiveIndex = -- this._nActiveControlInterpolants,
  29130. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  29131. interpolant.__cacheIndex = firstInactiveIndex;
  29132. interpolants[ firstInactiveIndex ] = interpolant;
  29133. lastActiveInterpolant.__cacheIndex = prevIndex;
  29134. interpolants[ prevIndex ] = lastActiveInterpolant;
  29135. },
  29136. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  29137. // return an action for a clip optionally using a custom root target
  29138. // object (this method allocates a lot of dynamic memory in case a
  29139. // previously unknown clip/root combination is specified)
  29140. clipAction: function ( clip, optionalRoot ) {
  29141. var root = optionalRoot || this._root,
  29142. rootUuid = root.uuid,
  29143. clipObject = typeof clip === 'string' ?
  29144. AnimationClip.findByName( root, clip ) : clip,
  29145. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  29146. actionsForClip = this._actionsByClip[ clipUuid ],
  29147. prototypeAction = null;
  29148. if ( actionsForClip !== undefined ) {
  29149. var existingAction =
  29150. actionsForClip.actionByRoot[ rootUuid ];
  29151. if ( existingAction !== undefined ) {
  29152. return existingAction;
  29153. }
  29154. // we know the clip, so we don't have to parse all
  29155. // the bindings again but can just copy
  29156. prototypeAction = actionsForClip.knownActions[ 0 ];
  29157. // also, take the clip from the prototype action
  29158. if ( clipObject === null )
  29159. clipObject = prototypeAction._clip;
  29160. }
  29161. // clip must be known when specified via string
  29162. if ( clipObject === null ) return null;
  29163. // allocate all resources required to run it
  29164. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  29165. this._bindAction( newAction, prototypeAction );
  29166. // and make the action known to the memory manager
  29167. this._addInactiveAction( newAction, clipUuid, rootUuid );
  29168. return newAction;
  29169. },
  29170. // get an existing action
  29171. existingAction: function ( clip, optionalRoot ) {
  29172. var root = optionalRoot || this._root,
  29173. rootUuid = root.uuid,
  29174. clipObject = typeof clip === 'string' ?
  29175. AnimationClip.findByName( root, clip ) : clip,
  29176. clipUuid = clipObject ? clipObject.uuid : clip,
  29177. actionsForClip = this._actionsByClip[ clipUuid ];
  29178. if ( actionsForClip !== undefined ) {
  29179. return actionsForClip.actionByRoot[ rootUuid ] || null;
  29180. }
  29181. return null;
  29182. },
  29183. // deactivates all previously scheduled actions
  29184. stopAllAction: function () {
  29185. var actions = this._actions,
  29186. nActions = this._nActiveActions,
  29187. bindings = this._bindings,
  29188. nBindings = this._nActiveBindings;
  29189. this._nActiveActions = 0;
  29190. this._nActiveBindings = 0;
  29191. for ( var i = 0; i !== nActions; ++ i ) {
  29192. actions[ i ].reset();
  29193. }
  29194. for ( var i = 0; i !== nBindings; ++ i ) {
  29195. bindings[ i ].useCount = 0;
  29196. }
  29197. return this;
  29198. },
  29199. // advance the time and update apply the animation
  29200. update: function ( deltaTime ) {
  29201. deltaTime *= this.timeScale;
  29202. var actions = this._actions,
  29203. nActions = this._nActiveActions,
  29204. time = this.time += deltaTime,
  29205. timeDirection = Math.sign( deltaTime ),
  29206. accuIndex = this._accuIndex ^= 1;
  29207. // run active actions
  29208. for ( var i = 0; i !== nActions; ++ i ) {
  29209. var action = actions[ i ];
  29210. action._update( time, deltaTime, timeDirection, accuIndex );
  29211. }
  29212. // update scene graph
  29213. var bindings = this._bindings,
  29214. nBindings = this._nActiveBindings;
  29215. for ( var i = 0; i !== nBindings; ++ i ) {
  29216. bindings[ i ].apply( accuIndex );
  29217. }
  29218. return this;
  29219. },
  29220. // return this mixer's root target object
  29221. getRoot: function () {
  29222. return this._root;
  29223. },
  29224. // free all resources specific to a particular clip
  29225. uncacheClip: function ( clip ) {
  29226. var actions = this._actions,
  29227. clipUuid = clip.uuid,
  29228. actionsByClip = this._actionsByClip,
  29229. actionsForClip = actionsByClip[ clipUuid ];
  29230. if ( actionsForClip !== undefined ) {
  29231. // note: just calling _removeInactiveAction would mess up the
  29232. // iteration state and also require updating the state we can
  29233. // just throw away
  29234. var actionsToRemove = actionsForClip.knownActions;
  29235. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  29236. var action = actionsToRemove[ i ];
  29237. this._deactivateAction( action );
  29238. var cacheIndex = action._cacheIndex,
  29239. lastInactiveAction = actions[ actions.length - 1 ];
  29240. action._cacheIndex = null;
  29241. action._byClipCacheIndex = null;
  29242. lastInactiveAction._cacheIndex = cacheIndex;
  29243. actions[ cacheIndex ] = lastInactiveAction;
  29244. actions.pop();
  29245. this._removeInactiveBindingsForAction( action );
  29246. }
  29247. delete actionsByClip[ clipUuid ];
  29248. }
  29249. },
  29250. // free all resources specific to a particular root target object
  29251. uncacheRoot: function ( root ) {
  29252. var rootUuid = root.uuid,
  29253. actionsByClip = this._actionsByClip;
  29254. for ( var clipUuid in actionsByClip ) {
  29255. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  29256. action = actionByRoot[ rootUuid ];
  29257. if ( action !== undefined ) {
  29258. this._deactivateAction( action );
  29259. this._removeInactiveAction( action );
  29260. }
  29261. }
  29262. var bindingsByRoot = this._bindingsByRootAndName,
  29263. bindingByName = bindingsByRoot[ rootUuid ];
  29264. if ( bindingByName !== undefined ) {
  29265. for ( var trackName in bindingByName ) {
  29266. var binding = bindingByName[ trackName ];
  29267. binding.restoreOriginalState();
  29268. this._removeInactiveBinding( binding );
  29269. }
  29270. }
  29271. },
  29272. // remove a targeted clip from the cache
  29273. uncacheAction: function ( clip, optionalRoot ) {
  29274. var action = this.existingAction( clip, optionalRoot );
  29275. if ( action !== null ) {
  29276. this._deactivateAction( action );
  29277. this._removeInactiveAction( action );
  29278. }
  29279. }
  29280. } );
  29281. /**
  29282. * @author mrdoob / http://mrdoob.com/
  29283. */
  29284. function Uniform( value ) {
  29285. if ( typeof value === 'string' ) {
  29286. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  29287. value = arguments[ 1 ];
  29288. }
  29289. this.value = value;
  29290. }
  29291. Uniform.prototype.clone = function () {
  29292. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  29293. };
  29294. /**
  29295. * @author benaadams / https://twitter.com/ben_a_adams
  29296. */
  29297. function InstancedBufferGeometry() {
  29298. BufferGeometry.call( this );
  29299. this.type = 'InstancedBufferGeometry';
  29300. this.maxInstancedCount = undefined;
  29301. }
  29302. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  29303. constructor: InstancedBufferGeometry,
  29304. isInstancedBufferGeometry: true,
  29305. copy: function ( source ) {
  29306. BufferGeometry.prototype.copy.call( this, source );
  29307. this.maxInstancedCount = source.maxInstancedCount;
  29308. return this;
  29309. },
  29310. clone: function () {
  29311. return new this.constructor().copy( this );
  29312. }
  29313. } );
  29314. /**
  29315. * @author benaadams / https://twitter.com/ben_a_adams
  29316. */
  29317. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  29318. this.data = interleavedBuffer;
  29319. this.itemSize = itemSize;
  29320. this.offset = offset;
  29321. this.normalized = normalized === true;
  29322. }
  29323. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  29324. count: {
  29325. get: function () {
  29326. return this.data.count;
  29327. }
  29328. },
  29329. array: {
  29330. get: function () {
  29331. return this.data.array;
  29332. }
  29333. }
  29334. } );
  29335. Object.assign( InterleavedBufferAttribute.prototype, {
  29336. isInterleavedBufferAttribute: true,
  29337. setX: function ( index, x ) {
  29338. this.data.array[ index * this.data.stride + this.offset ] = x;
  29339. return this;
  29340. },
  29341. setY: function ( index, y ) {
  29342. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  29343. return this;
  29344. },
  29345. setZ: function ( index, z ) {
  29346. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  29347. return this;
  29348. },
  29349. setW: function ( index, w ) {
  29350. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  29351. return this;
  29352. },
  29353. getX: function ( index ) {
  29354. return this.data.array[ index * this.data.stride + this.offset ];
  29355. },
  29356. getY: function ( index ) {
  29357. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  29358. },
  29359. getZ: function ( index ) {
  29360. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  29361. },
  29362. getW: function ( index ) {
  29363. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  29364. },
  29365. setXY: function ( index, x, y ) {
  29366. index = index * this.data.stride + this.offset;
  29367. this.data.array[ index + 0 ] = x;
  29368. this.data.array[ index + 1 ] = y;
  29369. return this;
  29370. },
  29371. setXYZ: function ( index, x, y, z ) {
  29372. index = index * this.data.stride + this.offset;
  29373. this.data.array[ index + 0 ] = x;
  29374. this.data.array[ index + 1 ] = y;
  29375. this.data.array[ index + 2 ] = z;
  29376. return this;
  29377. },
  29378. setXYZW: function ( index, x, y, z, w ) {
  29379. index = index * this.data.stride + this.offset;
  29380. this.data.array[ index + 0 ] = x;
  29381. this.data.array[ index + 1 ] = y;
  29382. this.data.array[ index + 2 ] = z;
  29383. this.data.array[ index + 3 ] = w;
  29384. return this;
  29385. }
  29386. } );
  29387. /**
  29388. * @author benaadams / https://twitter.com/ben_a_adams
  29389. */
  29390. function InterleavedBuffer( array, stride ) {
  29391. this.array = array;
  29392. this.stride = stride;
  29393. this.count = array !== undefined ? array.length / stride : 0;
  29394. this.dynamic = false;
  29395. this.updateRange = { offset: 0, count: - 1 };
  29396. this.version = 0;
  29397. }
  29398. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  29399. set: function ( value ) {
  29400. if ( value === true ) this.version ++;
  29401. }
  29402. } );
  29403. Object.assign( InterleavedBuffer.prototype, {
  29404. isInterleavedBuffer: true,
  29405. onUploadCallback: function () {},
  29406. setArray: function ( array ) {
  29407. if ( Array.isArray( array ) ) {
  29408. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  29409. }
  29410. this.count = array !== undefined ? array.length / this.stride : 0;
  29411. this.array = array;
  29412. return this;
  29413. },
  29414. setDynamic: function ( value ) {
  29415. this.dynamic = value;
  29416. return this;
  29417. },
  29418. copy: function ( source ) {
  29419. this.array = new source.array.constructor( source.array );
  29420. this.count = source.count;
  29421. this.stride = source.stride;
  29422. this.dynamic = source.dynamic;
  29423. return this;
  29424. },
  29425. copyAt: function ( index1, attribute, index2 ) {
  29426. index1 *= this.stride;
  29427. index2 *= attribute.stride;
  29428. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  29429. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  29430. }
  29431. return this;
  29432. },
  29433. set: function ( value, offset ) {
  29434. if ( offset === undefined ) offset = 0;
  29435. this.array.set( value, offset );
  29436. return this;
  29437. },
  29438. clone: function () {
  29439. return new this.constructor().copy( this );
  29440. },
  29441. onUpload: function ( callback ) {
  29442. this.onUploadCallback = callback;
  29443. return this;
  29444. }
  29445. } );
  29446. /**
  29447. * @author benaadams / https://twitter.com/ben_a_adams
  29448. */
  29449. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  29450. InterleavedBuffer.call( this, array, stride );
  29451. this.meshPerAttribute = meshPerAttribute || 1;
  29452. }
  29453. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  29454. constructor: InstancedInterleavedBuffer,
  29455. isInstancedInterleavedBuffer: true,
  29456. copy: function ( source ) {
  29457. InterleavedBuffer.prototype.copy.call( this, source );
  29458. this.meshPerAttribute = source.meshPerAttribute;
  29459. return this;
  29460. }
  29461. } );
  29462. /**
  29463. * @author benaadams / https://twitter.com/ben_a_adams
  29464. */
  29465. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  29466. BufferAttribute.call( this, array, itemSize );
  29467. this.meshPerAttribute = meshPerAttribute || 1;
  29468. }
  29469. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  29470. constructor: InstancedBufferAttribute,
  29471. isInstancedBufferAttribute: true,
  29472. copy: function ( source ) {
  29473. BufferAttribute.prototype.copy.call( this, source );
  29474. this.meshPerAttribute = source.meshPerAttribute;
  29475. return this;
  29476. }
  29477. } );
  29478. /**
  29479. * @author mrdoob / http://mrdoob.com/
  29480. * @author bhouston / http://clara.io/
  29481. * @author stephomi / http://stephaneginier.com/
  29482. */
  29483. function Raycaster( origin, direction, near, far ) {
  29484. this.ray = new Ray( origin, direction );
  29485. // direction is assumed to be normalized (for accurate distance calculations)
  29486. this.near = near || 0;
  29487. this.far = far || Infinity;
  29488. this.params = {
  29489. Mesh: {},
  29490. Line: {},
  29491. LOD: {},
  29492. Points: { threshold: 1 },
  29493. Sprite: {}
  29494. };
  29495. Object.defineProperties( this.params, {
  29496. PointCloud: {
  29497. get: function () {
  29498. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  29499. return this.Points;
  29500. }
  29501. }
  29502. } );
  29503. }
  29504. function ascSort( a, b ) {
  29505. return a.distance - b.distance;
  29506. }
  29507. function intersectObject( object, raycaster, intersects, recursive ) {
  29508. if ( object.visible === false ) return;
  29509. object.raycast( raycaster, intersects );
  29510. if ( recursive === true ) {
  29511. var children = object.children;
  29512. for ( var i = 0, l = children.length; i < l; i ++ ) {
  29513. intersectObject( children[ i ], raycaster, intersects, true );
  29514. }
  29515. }
  29516. }
  29517. Object.assign( Raycaster.prototype, {
  29518. linePrecision: 1,
  29519. set: function ( origin, direction ) {
  29520. // direction is assumed to be normalized (for accurate distance calculations)
  29521. this.ray.set( origin, direction );
  29522. },
  29523. setFromCamera: function ( coords, camera ) {
  29524. if ( ( camera && camera.isPerspectiveCamera ) ) {
  29525. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  29526. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  29527. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  29528. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  29529. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  29530. } else {
  29531. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  29532. }
  29533. },
  29534. intersectObject: function ( object, recursive, optionalTarget ) {
  29535. var intersects = optionalTarget || [];
  29536. intersectObject( object, this, intersects, recursive );
  29537. intersects.sort( ascSort );
  29538. return intersects;
  29539. },
  29540. intersectObjects: function ( objects, recursive, optionalTarget ) {
  29541. var intersects = optionalTarget || [];
  29542. if ( Array.isArray( objects ) === false ) {
  29543. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  29544. return intersects;
  29545. }
  29546. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  29547. intersectObject( objects[ i ], this, intersects, recursive );
  29548. }
  29549. intersects.sort( ascSort );
  29550. return intersects;
  29551. }
  29552. } );
  29553. /**
  29554. * @author alteredq / http://alteredqualia.com/
  29555. */
  29556. function Clock( autoStart ) {
  29557. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  29558. this.startTime = 0;
  29559. this.oldTime = 0;
  29560. this.elapsedTime = 0;
  29561. this.running = false;
  29562. }
  29563. Object.assign( Clock.prototype, {
  29564. start: function () {
  29565. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  29566. this.oldTime = this.startTime;
  29567. this.elapsedTime = 0;
  29568. this.running = true;
  29569. },
  29570. stop: function () {
  29571. this.getElapsedTime();
  29572. this.running = false;
  29573. this.autoStart = false;
  29574. },
  29575. getElapsedTime: function () {
  29576. this.getDelta();
  29577. return this.elapsedTime;
  29578. },
  29579. getDelta: function () {
  29580. var diff = 0;
  29581. if ( this.autoStart && ! this.running ) {
  29582. this.start();
  29583. return 0;
  29584. }
  29585. if ( this.running ) {
  29586. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  29587. diff = ( newTime - this.oldTime ) / 1000;
  29588. this.oldTime = newTime;
  29589. this.elapsedTime += diff;
  29590. }
  29591. return diff;
  29592. }
  29593. } );
  29594. /**
  29595. * @author bhouston / http://clara.io
  29596. * @author WestLangley / http://github.com/WestLangley
  29597. *
  29598. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  29599. *
  29600. * The poles (phi) are at the positive and negative y axis.
  29601. * The equator starts at positive z.
  29602. */
  29603. function Spherical( radius, phi, theta ) {
  29604. this.radius = ( radius !== undefined ) ? radius : 1.0;
  29605. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  29606. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  29607. return this;
  29608. }
  29609. Object.assign( Spherical.prototype, {
  29610. set: function ( radius, phi, theta ) {
  29611. this.radius = radius;
  29612. this.phi = phi;
  29613. this.theta = theta;
  29614. return this;
  29615. },
  29616. clone: function () {
  29617. return new this.constructor().copy( this );
  29618. },
  29619. copy: function ( other ) {
  29620. this.radius = other.radius;
  29621. this.phi = other.phi;
  29622. this.theta = other.theta;
  29623. return this;
  29624. },
  29625. // restrict phi to be betwee EPS and PI-EPS
  29626. makeSafe: function () {
  29627. var EPS = 0.000001;
  29628. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  29629. return this;
  29630. },
  29631. setFromVector3: function ( vec3 ) {
  29632. this.radius = vec3.length();
  29633. if ( this.radius === 0 ) {
  29634. this.theta = 0;
  29635. this.phi = 0;
  29636. } else {
  29637. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  29638. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  29639. }
  29640. return this;
  29641. }
  29642. } );
  29643. /**
  29644. * @author Mugen87 / https://github.com/Mugen87
  29645. *
  29646. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  29647. *
  29648. */
  29649. function Cylindrical( radius, theta, y ) {
  29650. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  29651. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  29652. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  29653. return this;
  29654. }
  29655. Object.assign( Cylindrical.prototype, {
  29656. set: function ( radius, theta, y ) {
  29657. this.radius = radius;
  29658. this.theta = theta;
  29659. this.y = y;
  29660. return this;
  29661. },
  29662. clone: function () {
  29663. return new this.constructor().copy( this );
  29664. },
  29665. copy: function ( other ) {
  29666. this.radius = other.radius;
  29667. this.theta = other.theta;
  29668. this.y = other.y;
  29669. return this;
  29670. },
  29671. setFromVector3: function ( vec3 ) {
  29672. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  29673. this.theta = Math.atan2( vec3.x, vec3.z );
  29674. this.y = vec3.y;
  29675. return this;
  29676. }
  29677. } );
  29678. /**
  29679. * @author bhouston / http://clara.io
  29680. */
  29681. function Box2( min, max ) {
  29682. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  29683. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  29684. }
  29685. Object.assign( Box2.prototype, {
  29686. set: function ( min, max ) {
  29687. this.min.copy( min );
  29688. this.max.copy( max );
  29689. return this;
  29690. },
  29691. setFromPoints: function ( points ) {
  29692. this.makeEmpty();
  29693. for ( var i = 0, il = points.length; i < il; i ++ ) {
  29694. this.expandByPoint( points[ i ] );
  29695. }
  29696. return this;
  29697. },
  29698. setFromCenterAndSize: function () {
  29699. var v1 = new Vector2();
  29700. return function setFromCenterAndSize( center, size ) {
  29701. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  29702. this.min.copy( center ).sub( halfSize );
  29703. this.max.copy( center ).add( halfSize );
  29704. return this;
  29705. };
  29706. }(),
  29707. clone: function () {
  29708. return new this.constructor().copy( this );
  29709. },
  29710. copy: function ( box ) {
  29711. this.min.copy( box.min );
  29712. this.max.copy( box.max );
  29713. return this;
  29714. },
  29715. makeEmpty: function () {
  29716. this.min.x = this.min.y = + Infinity;
  29717. this.max.x = this.max.y = - Infinity;
  29718. return this;
  29719. },
  29720. isEmpty: function () {
  29721. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  29722. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  29723. },
  29724. getCenter: function ( target ) {
  29725. if ( target === undefined ) {
  29726. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  29727. target = new Vector2();
  29728. }
  29729. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  29730. },
  29731. getSize: function ( target ) {
  29732. if ( target === undefined ) {
  29733. console.warn( 'THREE.Box2: .getSize() target is now required' );
  29734. target = new Vector2();
  29735. }
  29736. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  29737. },
  29738. expandByPoint: function ( point ) {
  29739. this.min.min( point );
  29740. this.max.max( point );
  29741. return this;
  29742. },
  29743. expandByVector: function ( vector ) {
  29744. this.min.sub( vector );
  29745. this.max.add( vector );
  29746. return this;
  29747. },
  29748. expandByScalar: function ( scalar ) {
  29749. this.min.addScalar( - scalar );
  29750. this.max.addScalar( scalar );
  29751. return this;
  29752. },
  29753. containsPoint: function ( point ) {
  29754. return point.x < this.min.x || point.x > this.max.x ||
  29755. point.y < this.min.y || point.y > this.max.y ? false : true;
  29756. },
  29757. containsBox: function ( box ) {
  29758. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  29759. this.min.y <= box.min.y && box.max.y <= this.max.y;
  29760. },
  29761. getParameter: function ( point, target ) {
  29762. // This can potentially have a divide by zero if the box
  29763. // has a size dimension of 0.
  29764. if ( target === undefined ) {
  29765. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  29766. target = new Vector2();
  29767. }
  29768. return target.set(
  29769. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  29770. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  29771. );
  29772. },
  29773. intersectsBox: function ( box ) {
  29774. // using 4 splitting planes to rule out intersections
  29775. return box.max.x < this.min.x || box.min.x > this.max.x ||
  29776. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  29777. },
  29778. clampPoint: function ( point, target ) {
  29779. if ( target === undefined ) {
  29780. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  29781. target = new Vector2();
  29782. }
  29783. return target.copy( point ).clamp( this.min, this.max );
  29784. },
  29785. distanceToPoint: function () {
  29786. var v1 = new Vector2();
  29787. return function distanceToPoint( point ) {
  29788. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  29789. return clampedPoint.sub( point ).length();
  29790. };
  29791. }(),
  29792. intersect: function ( box ) {
  29793. this.min.max( box.min );
  29794. this.max.min( box.max );
  29795. return this;
  29796. },
  29797. union: function ( box ) {
  29798. this.min.min( box.min );
  29799. this.max.max( box.max );
  29800. return this;
  29801. },
  29802. translate: function ( offset ) {
  29803. this.min.add( offset );
  29804. this.max.add( offset );
  29805. return this;
  29806. },
  29807. equals: function ( box ) {
  29808. return box.min.equals( this.min ) && box.max.equals( this.max );
  29809. }
  29810. } );
  29811. /**
  29812. * @author alteredq / http://alteredqualia.com/
  29813. */
  29814. function ImmediateRenderObject( material ) {
  29815. Object3D.call( this );
  29816. this.material = material;
  29817. this.render = function ( /* renderCallback */ ) {};
  29818. }
  29819. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  29820. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  29821. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  29822. /**
  29823. * @author mrdoob / http://mrdoob.com/
  29824. * @author WestLangley / http://github.com/WestLangley
  29825. */
  29826. function VertexNormalsHelper( object, size, hex, linewidth ) {
  29827. this.object = object;
  29828. this.size = ( size !== undefined ) ? size : 1;
  29829. var color = ( hex !== undefined ) ? hex : 0xff0000;
  29830. var width = ( linewidth !== undefined ) ? linewidth : 1;
  29831. //
  29832. var nNormals = 0;
  29833. var objGeometry = this.object.geometry;
  29834. if ( objGeometry && objGeometry.isGeometry ) {
  29835. nNormals = objGeometry.faces.length * 3;
  29836. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  29837. nNormals = objGeometry.attributes.normal.count;
  29838. }
  29839. //
  29840. var geometry = new BufferGeometry();
  29841. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  29842. geometry.addAttribute( 'position', positions );
  29843. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  29844. //
  29845. this.matrixAutoUpdate = false;
  29846. this.update();
  29847. }
  29848. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  29849. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  29850. VertexNormalsHelper.prototype.update = ( function () {
  29851. var v1 = new Vector3();
  29852. var v2 = new Vector3();
  29853. var normalMatrix = new Matrix3();
  29854. return function update() {
  29855. var keys = [ 'a', 'b', 'c' ];
  29856. this.object.updateMatrixWorld( true );
  29857. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  29858. var matrixWorld = this.object.matrixWorld;
  29859. var position = this.geometry.attributes.position;
  29860. //
  29861. var objGeometry = this.object.geometry;
  29862. if ( objGeometry && objGeometry.isGeometry ) {
  29863. var vertices = objGeometry.vertices;
  29864. var faces = objGeometry.faces;
  29865. var idx = 0;
  29866. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  29867. var face = faces[ i ];
  29868. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  29869. var vertex = vertices[ face[ keys[ j ] ] ];
  29870. var normal = face.vertexNormals[ j ];
  29871. v1.copy( vertex ).applyMatrix4( matrixWorld );
  29872. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  29873. position.setXYZ( idx, v1.x, v1.y, v1.z );
  29874. idx = idx + 1;
  29875. position.setXYZ( idx, v2.x, v2.y, v2.z );
  29876. idx = idx + 1;
  29877. }
  29878. }
  29879. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  29880. var objPos = objGeometry.attributes.position;
  29881. var objNorm = objGeometry.attributes.normal;
  29882. var idx = 0;
  29883. // for simplicity, ignore index and drawcalls, and render every normal
  29884. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  29885. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  29886. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  29887. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  29888. position.setXYZ( idx, v1.x, v1.y, v1.z );
  29889. idx = idx + 1;
  29890. position.setXYZ( idx, v2.x, v2.y, v2.z );
  29891. idx = idx + 1;
  29892. }
  29893. }
  29894. position.needsUpdate = true;
  29895. };
  29896. }() );
  29897. /**
  29898. * @author alteredq / http://alteredqualia.com/
  29899. * @author mrdoob / http://mrdoob.com/
  29900. * @author WestLangley / http://github.com/WestLangley
  29901. */
  29902. function SpotLightHelper( light, color ) {
  29903. Object3D.call( this );
  29904. this.light = light;
  29905. this.light.updateMatrixWorld();
  29906. this.matrix = light.matrixWorld;
  29907. this.matrixAutoUpdate = false;
  29908. this.color = color;
  29909. var geometry = new BufferGeometry();
  29910. var positions = [
  29911. 0, 0, 0, 0, 0, 1,
  29912. 0, 0, 0, 1, 0, 1,
  29913. 0, 0, 0, - 1, 0, 1,
  29914. 0, 0, 0, 0, 1, 1,
  29915. 0, 0, 0, 0, - 1, 1
  29916. ];
  29917. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  29918. var p1 = ( i / l ) * Math.PI * 2;
  29919. var p2 = ( j / l ) * Math.PI * 2;
  29920. positions.push(
  29921. Math.cos( p1 ), Math.sin( p1 ), 1,
  29922. Math.cos( p2 ), Math.sin( p2 ), 1
  29923. );
  29924. }
  29925. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29926. var material = new LineBasicMaterial( { fog: false } );
  29927. this.cone = new LineSegments( geometry, material );
  29928. this.add( this.cone );
  29929. this.update();
  29930. }
  29931. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  29932. SpotLightHelper.prototype.constructor = SpotLightHelper;
  29933. SpotLightHelper.prototype.dispose = function () {
  29934. this.cone.geometry.dispose();
  29935. this.cone.material.dispose();
  29936. };
  29937. SpotLightHelper.prototype.update = function () {
  29938. var vector = new Vector3();
  29939. var vector2 = new Vector3();
  29940. return function update() {
  29941. this.light.updateMatrixWorld();
  29942. var coneLength = this.light.distance ? this.light.distance : 1000;
  29943. var coneWidth = coneLength * Math.tan( this.light.angle );
  29944. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  29945. vector.setFromMatrixPosition( this.light.matrixWorld );
  29946. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  29947. this.cone.lookAt( vector2.sub( vector ) );
  29948. if ( this.color !== undefined ) {
  29949. this.cone.material.color.set( this.color );
  29950. } else {
  29951. this.cone.material.color.copy( this.light.color );
  29952. }
  29953. };
  29954. }();
  29955. /**
  29956. * @author Sean Griffin / http://twitter.com/sgrif
  29957. * @author Michael Guerrero / http://realitymeltdown.com
  29958. * @author mrdoob / http://mrdoob.com/
  29959. * @author ikerr / http://verold.com
  29960. * @author Mugen87 / https://github.com/Mugen87
  29961. */
  29962. function getBoneList( object ) {
  29963. var boneList = [];
  29964. if ( object && object.isBone ) {
  29965. boneList.push( object );
  29966. }
  29967. for ( var i = 0; i < object.children.length; i ++ ) {
  29968. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  29969. }
  29970. return boneList;
  29971. }
  29972. function SkeletonHelper( object ) {
  29973. var bones = getBoneList( object );
  29974. var geometry = new BufferGeometry();
  29975. var vertices = [];
  29976. var colors = [];
  29977. var color1 = new Color( 0, 0, 1 );
  29978. var color2 = new Color( 0, 1, 0 );
  29979. for ( var i = 0; i < bones.length; i ++ ) {
  29980. var bone = bones[ i ];
  29981. if ( bone.parent && bone.parent.isBone ) {
  29982. vertices.push( 0, 0, 0 );
  29983. vertices.push( 0, 0, 0 );
  29984. colors.push( color1.r, color1.g, color1.b );
  29985. colors.push( color2.r, color2.g, color2.b );
  29986. }
  29987. }
  29988. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29989. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29990. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  29991. LineSegments.call( this, geometry, material );
  29992. this.root = object;
  29993. this.bones = bones;
  29994. this.matrix = object.matrixWorld;
  29995. this.matrixAutoUpdate = false;
  29996. }
  29997. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  29998. SkeletonHelper.prototype.constructor = SkeletonHelper;
  29999. SkeletonHelper.prototype.updateMatrixWorld = function () {
  30000. var vector = new Vector3();
  30001. var boneMatrix = new Matrix4();
  30002. var matrixWorldInv = new Matrix4();
  30003. return function updateMatrixWorld( force ) {
  30004. var bones = this.bones;
  30005. var geometry = this.geometry;
  30006. var position = geometry.getAttribute( 'position' );
  30007. matrixWorldInv.getInverse( this.root.matrixWorld );
  30008. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  30009. var bone = bones[ i ];
  30010. if ( bone.parent && bone.parent.isBone ) {
  30011. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  30012. vector.setFromMatrixPosition( boneMatrix );
  30013. position.setXYZ( j, vector.x, vector.y, vector.z );
  30014. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  30015. vector.setFromMatrixPosition( boneMatrix );
  30016. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  30017. j += 2;
  30018. }
  30019. }
  30020. geometry.getAttribute( 'position' ).needsUpdate = true;
  30021. Object3D.prototype.updateMatrixWorld.call( this, force );
  30022. };
  30023. }();
  30024. /**
  30025. * @author alteredq / http://alteredqualia.com/
  30026. * @author mrdoob / http://mrdoob.com/
  30027. */
  30028. function PointLightHelper( light, sphereSize, color ) {
  30029. this.light = light;
  30030. this.light.updateMatrixWorld();
  30031. this.color = color;
  30032. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  30033. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  30034. Mesh.call( this, geometry, material );
  30035. this.matrix = this.light.matrixWorld;
  30036. this.matrixAutoUpdate = false;
  30037. this.update();
  30038. /*
  30039. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  30040. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  30041. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  30042. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  30043. var d = light.distance;
  30044. if ( d === 0.0 ) {
  30045. this.lightDistance.visible = false;
  30046. } else {
  30047. this.lightDistance.scale.set( d, d, d );
  30048. }
  30049. this.add( this.lightDistance );
  30050. */
  30051. }
  30052. PointLightHelper.prototype = Object.create( Mesh.prototype );
  30053. PointLightHelper.prototype.constructor = PointLightHelper;
  30054. PointLightHelper.prototype.dispose = function () {
  30055. this.geometry.dispose();
  30056. this.material.dispose();
  30057. };
  30058. PointLightHelper.prototype.update = function () {
  30059. if ( this.color !== undefined ) {
  30060. this.material.color.set( this.color );
  30061. } else {
  30062. this.material.color.copy( this.light.color );
  30063. }
  30064. /*
  30065. var d = this.light.distance;
  30066. if ( d === 0.0 ) {
  30067. this.lightDistance.visible = false;
  30068. } else {
  30069. this.lightDistance.visible = true;
  30070. this.lightDistance.scale.set( d, d, d );
  30071. }
  30072. */
  30073. };
  30074. /**
  30075. * @author abelnation / http://github.com/abelnation
  30076. * @author Mugen87 / http://github.com/Mugen87
  30077. * @author WestLangley / http://github.com/WestLangley
  30078. */
  30079. function RectAreaLightHelper( light, color ) {
  30080. Object3D.call( this );
  30081. this.light = light;
  30082. this.light.updateMatrixWorld();
  30083. this.matrix = light.matrixWorld;
  30084. this.matrixAutoUpdate = false;
  30085. this.color = color;
  30086. var material = new LineBasicMaterial( { fog: false } );
  30087. var geometry = new BufferGeometry();
  30088. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  30089. this.line = new Line( geometry, material );
  30090. this.add( this.line );
  30091. this.update();
  30092. }
  30093. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  30094. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  30095. RectAreaLightHelper.prototype.dispose = function () {
  30096. this.children[ 0 ].geometry.dispose();
  30097. this.children[ 0 ].material.dispose();
  30098. };
  30099. RectAreaLightHelper.prototype.update = function () {
  30100. // calculate new dimensions of the helper
  30101. var hx = this.light.width * 0.5;
  30102. var hy = this.light.height * 0.5;
  30103. var position = this.line.geometry.attributes.position;
  30104. var array = position.array;
  30105. // update vertices
  30106. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  30107. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  30108. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  30109. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  30110. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  30111. position.needsUpdate = true;
  30112. if ( this.color !== undefined ) {
  30113. this.line.material.color.set( this.color );
  30114. } else {
  30115. this.line.material.color.copy( this.light.color );
  30116. }
  30117. };
  30118. /**
  30119. * @author alteredq / http://alteredqualia.com/
  30120. * @author mrdoob / http://mrdoob.com/
  30121. * @author Mugen87 / https://github.com/Mugen87
  30122. */
  30123. function HemisphereLightHelper( light, size, color ) {
  30124. Object3D.call( this );
  30125. this.light = light;
  30126. this.light.updateMatrixWorld();
  30127. this.matrix = light.matrixWorld;
  30128. this.matrixAutoUpdate = false;
  30129. this.color = color;
  30130. var geometry = new OctahedronBufferGeometry( size );
  30131. geometry.rotateY( Math.PI * 0.5 );
  30132. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  30133. if ( this.color === undefined ) this.material.vertexColors = VertexColors;
  30134. var position = geometry.getAttribute( 'position' );
  30135. var colors = new Float32Array( position.count * 3 );
  30136. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  30137. this.add( new Mesh( geometry, this.material ) );
  30138. this.update();
  30139. }
  30140. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  30141. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  30142. HemisphereLightHelper.prototype.dispose = function () {
  30143. this.children[ 0 ].geometry.dispose();
  30144. this.children[ 0 ].material.dispose();
  30145. };
  30146. HemisphereLightHelper.prototype.update = function () {
  30147. var vector = new Vector3();
  30148. var color1 = new Color();
  30149. var color2 = new Color();
  30150. return function update() {
  30151. var mesh = this.children[ 0 ];
  30152. if ( this.color !== undefined ) {
  30153. this.material.color.set( this.color );
  30154. } else {
  30155. var colors = mesh.geometry.getAttribute( 'color' );
  30156. color1.copy( this.light.color );
  30157. color2.copy( this.light.groundColor );
  30158. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  30159. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  30160. colors.setXYZ( i, color.r, color.g, color.b );
  30161. }
  30162. colors.needsUpdate = true;
  30163. }
  30164. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  30165. };
  30166. }();
  30167. /**
  30168. * @author mrdoob / http://mrdoob.com/
  30169. */
  30170. function GridHelper( size, divisions, color1, color2 ) {
  30171. size = size || 10;
  30172. divisions = divisions || 10;
  30173. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  30174. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  30175. var center = divisions / 2;
  30176. var step = size / divisions;
  30177. var halfSize = size / 2;
  30178. var vertices = [], colors = [];
  30179. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  30180. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  30181. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  30182. var color = i === center ? color1 : color2;
  30183. color.toArray( colors, j ); j += 3;
  30184. color.toArray( colors, j ); j += 3;
  30185. color.toArray( colors, j ); j += 3;
  30186. color.toArray( colors, j ); j += 3;
  30187. }
  30188. var geometry = new BufferGeometry();
  30189. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30190. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30191. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  30192. LineSegments.call( this, geometry, material );
  30193. }
  30194. GridHelper.prototype = Object.create( LineSegments.prototype );
  30195. GridHelper.prototype.constructor = GridHelper;
  30196. /**
  30197. * @author mrdoob / http://mrdoob.com/
  30198. * @author Mugen87 / http://github.com/Mugen87
  30199. * @author Hectate / http://www.github.com/Hectate
  30200. */
  30201. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  30202. radius = radius || 10;
  30203. radials = radials || 16;
  30204. circles = circles || 8;
  30205. divisions = divisions || 64;
  30206. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  30207. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  30208. var vertices = [];
  30209. var colors = [];
  30210. var x, z;
  30211. var v, i, j, r, color;
  30212. // create the radials
  30213. for ( i = 0; i <= radials; i ++ ) {
  30214. v = ( i / radials ) * ( Math.PI * 2 );
  30215. x = Math.sin( v ) * radius;
  30216. z = Math.cos( v ) * radius;
  30217. vertices.push( 0, 0, 0 );
  30218. vertices.push( x, 0, z );
  30219. color = ( i & 1 ) ? color1 : color2;
  30220. colors.push( color.r, color.g, color.b );
  30221. colors.push( color.r, color.g, color.b );
  30222. }
  30223. // create the circles
  30224. for ( i = 0; i <= circles; i ++ ) {
  30225. color = ( i & 1 ) ? color1 : color2;
  30226. r = radius - ( radius / circles * i );
  30227. for ( j = 0; j < divisions; j ++ ) {
  30228. // first vertex
  30229. v = ( j / divisions ) * ( Math.PI * 2 );
  30230. x = Math.sin( v ) * r;
  30231. z = Math.cos( v ) * r;
  30232. vertices.push( x, 0, z );
  30233. colors.push( color.r, color.g, color.b );
  30234. // second vertex
  30235. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  30236. x = Math.sin( v ) * r;
  30237. z = Math.cos( v ) * r;
  30238. vertices.push( x, 0, z );
  30239. colors.push( color.r, color.g, color.b );
  30240. }
  30241. }
  30242. var geometry = new BufferGeometry();
  30243. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30244. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30245. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  30246. LineSegments.call( this, geometry, material );
  30247. }
  30248. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  30249. PolarGridHelper.prototype.constructor = PolarGridHelper;
  30250. /**
  30251. * @author mrdoob / http://mrdoob.com/
  30252. * @author WestLangley / http://github.com/WestLangley
  30253. */
  30254. function FaceNormalsHelper( object, size, hex, linewidth ) {
  30255. // FaceNormalsHelper only supports THREE.Geometry
  30256. this.object = object;
  30257. this.size = ( size !== undefined ) ? size : 1;
  30258. var color = ( hex !== undefined ) ? hex : 0xffff00;
  30259. var width = ( linewidth !== undefined ) ? linewidth : 1;
  30260. //
  30261. var nNormals = 0;
  30262. var objGeometry = this.object.geometry;
  30263. if ( objGeometry && objGeometry.isGeometry ) {
  30264. nNormals = objGeometry.faces.length;
  30265. } else {
  30266. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  30267. }
  30268. //
  30269. var geometry = new BufferGeometry();
  30270. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  30271. geometry.addAttribute( 'position', positions );
  30272. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  30273. //
  30274. this.matrixAutoUpdate = false;
  30275. this.update();
  30276. }
  30277. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  30278. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  30279. FaceNormalsHelper.prototype.update = ( function () {
  30280. var v1 = new Vector3();
  30281. var v2 = new Vector3();
  30282. var normalMatrix = new Matrix3();
  30283. return function update() {
  30284. this.object.updateMatrixWorld( true );
  30285. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  30286. var matrixWorld = this.object.matrixWorld;
  30287. var position = this.geometry.attributes.position;
  30288. //
  30289. var objGeometry = this.object.geometry;
  30290. var vertices = objGeometry.vertices;
  30291. var faces = objGeometry.faces;
  30292. var idx = 0;
  30293. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  30294. var face = faces[ i ];
  30295. var normal = face.normal;
  30296. v1.copy( vertices[ face.a ] )
  30297. .add( vertices[ face.b ] )
  30298. .add( vertices[ face.c ] )
  30299. .divideScalar( 3 )
  30300. .applyMatrix4( matrixWorld );
  30301. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  30302. position.setXYZ( idx, v1.x, v1.y, v1.z );
  30303. idx = idx + 1;
  30304. position.setXYZ( idx, v2.x, v2.y, v2.z );
  30305. idx = idx + 1;
  30306. }
  30307. position.needsUpdate = true;
  30308. };
  30309. }() );
  30310. /**
  30311. * @author alteredq / http://alteredqualia.com/
  30312. * @author mrdoob / http://mrdoob.com/
  30313. * @author WestLangley / http://github.com/WestLangley
  30314. */
  30315. function DirectionalLightHelper( light, size, color ) {
  30316. Object3D.call( this );
  30317. this.light = light;
  30318. this.light.updateMatrixWorld();
  30319. this.matrix = light.matrixWorld;
  30320. this.matrixAutoUpdate = false;
  30321. this.color = color;
  30322. if ( size === undefined ) size = 1;
  30323. var geometry = new BufferGeometry();
  30324. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  30325. - size, size, 0,
  30326. size, size, 0,
  30327. size, - size, 0,
  30328. - size, - size, 0,
  30329. - size, size, 0
  30330. ], 3 ) );
  30331. var material = new LineBasicMaterial( { fog: false } );
  30332. this.lightPlane = new Line( geometry, material );
  30333. this.add( this.lightPlane );
  30334. geometry = new BufferGeometry();
  30335. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  30336. this.targetLine = new Line( geometry, material );
  30337. this.add( this.targetLine );
  30338. this.update();
  30339. }
  30340. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  30341. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  30342. DirectionalLightHelper.prototype.dispose = function () {
  30343. this.lightPlane.geometry.dispose();
  30344. this.lightPlane.material.dispose();
  30345. this.targetLine.geometry.dispose();
  30346. this.targetLine.material.dispose();
  30347. };
  30348. DirectionalLightHelper.prototype.update = function () {
  30349. var v1 = new Vector3();
  30350. var v2 = new Vector3();
  30351. var v3 = new Vector3();
  30352. return function update() {
  30353. v1.setFromMatrixPosition( this.light.matrixWorld );
  30354. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  30355. v3.subVectors( v2, v1 );
  30356. this.lightPlane.lookAt( v3 );
  30357. if ( this.color !== undefined ) {
  30358. this.lightPlane.material.color.set( this.color );
  30359. this.targetLine.material.color.set( this.color );
  30360. } else {
  30361. this.lightPlane.material.color.copy( this.light.color );
  30362. this.targetLine.material.color.copy( this.light.color );
  30363. }
  30364. this.targetLine.lookAt( v3 );
  30365. this.targetLine.scale.z = v3.length();
  30366. };
  30367. }();
  30368. /**
  30369. * @author alteredq / http://alteredqualia.com/
  30370. * @author Mugen87 / https://github.com/Mugen87
  30371. *
  30372. * - shows frustum, line of sight and up of the camera
  30373. * - suitable for fast updates
  30374. * - based on frustum visualization in lightgl.js shadowmap example
  30375. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  30376. */
  30377. function CameraHelper( camera ) {
  30378. var geometry = new BufferGeometry();
  30379. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  30380. var vertices = [];
  30381. var colors = [];
  30382. var pointMap = {};
  30383. // colors
  30384. var colorFrustum = new Color( 0xffaa00 );
  30385. var colorCone = new Color( 0xff0000 );
  30386. var colorUp = new Color( 0x00aaff );
  30387. var colorTarget = new Color( 0xffffff );
  30388. var colorCross = new Color( 0x333333 );
  30389. // near
  30390. addLine( 'n1', 'n2', colorFrustum );
  30391. addLine( 'n2', 'n4', colorFrustum );
  30392. addLine( 'n4', 'n3', colorFrustum );
  30393. addLine( 'n3', 'n1', colorFrustum );
  30394. // far
  30395. addLine( 'f1', 'f2', colorFrustum );
  30396. addLine( 'f2', 'f4', colorFrustum );
  30397. addLine( 'f4', 'f3', colorFrustum );
  30398. addLine( 'f3', 'f1', colorFrustum );
  30399. // sides
  30400. addLine( 'n1', 'f1', colorFrustum );
  30401. addLine( 'n2', 'f2', colorFrustum );
  30402. addLine( 'n3', 'f3', colorFrustum );
  30403. addLine( 'n4', 'f4', colorFrustum );
  30404. // cone
  30405. addLine( 'p', 'n1', colorCone );
  30406. addLine( 'p', 'n2', colorCone );
  30407. addLine( 'p', 'n3', colorCone );
  30408. addLine( 'p', 'n4', colorCone );
  30409. // up
  30410. addLine( 'u1', 'u2', colorUp );
  30411. addLine( 'u2', 'u3', colorUp );
  30412. addLine( 'u3', 'u1', colorUp );
  30413. // target
  30414. addLine( 'c', 't', colorTarget );
  30415. addLine( 'p', 'c', colorCross );
  30416. // cross
  30417. addLine( 'cn1', 'cn2', colorCross );
  30418. addLine( 'cn3', 'cn4', colorCross );
  30419. addLine( 'cf1', 'cf2', colorCross );
  30420. addLine( 'cf3', 'cf4', colorCross );
  30421. function addLine( a, b, color ) {
  30422. addPoint( a, color );
  30423. addPoint( b, color );
  30424. }
  30425. function addPoint( id, color ) {
  30426. vertices.push( 0, 0, 0 );
  30427. colors.push( color.r, color.g, color.b );
  30428. if ( pointMap[ id ] === undefined ) {
  30429. pointMap[ id ] = [];
  30430. }
  30431. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  30432. }
  30433. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30434. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30435. LineSegments.call( this, geometry, material );
  30436. this.camera = camera;
  30437. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  30438. this.matrix = camera.matrixWorld;
  30439. this.matrixAutoUpdate = false;
  30440. this.pointMap = pointMap;
  30441. this.update();
  30442. }
  30443. CameraHelper.prototype = Object.create( LineSegments.prototype );
  30444. CameraHelper.prototype.constructor = CameraHelper;
  30445. CameraHelper.prototype.update = function () {
  30446. var geometry, pointMap;
  30447. var vector = new Vector3();
  30448. var camera = new Camera();
  30449. function setPoint( point, x, y, z ) {
  30450. vector.set( x, y, z ).unproject( camera );
  30451. var points = pointMap[ point ];
  30452. if ( points !== undefined ) {
  30453. var position = geometry.getAttribute( 'position' );
  30454. for ( var i = 0, l = points.length; i < l; i ++ ) {
  30455. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  30456. }
  30457. }
  30458. }
  30459. return function update() {
  30460. geometry = this.geometry;
  30461. pointMap = this.pointMap;
  30462. var w = 1, h = 1;
  30463. // we need just camera projection matrix
  30464. // world matrix must be identity
  30465. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  30466. // center / target
  30467. setPoint( 'c', 0, 0, - 1 );
  30468. setPoint( 't', 0, 0, 1 );
  30469. // near
  30470. setPoint( 'n1', - w, - h, - 1 );
  30471. setPoint( 'n2', w, - h, - 1 );
  30472. setPoint( 'n3', - w, h, - 1 );
  30473. setPoint( 'n4', w, h, - 1 );
  30474. // far
  30475. setPoint( 'f1', - w, - h, 1 );
  30476. setPoint( 'f2', w, - h, 1 );
  30477. setPoint( 'f3', - w, h, 1 );
  30478. setPoint( 'f4', w, h, 1 );
  30479. // up
  30480. setPoint( 'u1', w * 0.7, h * 1.1, - 1 );
  30481. setPoint( 'u2', - w * 0.7, h * 1.1, - 1 );
  30482. setPoint( 'u3', 0, h * 2, - 1 );
  30483. // cross
  30484. setPoint( 'cf1', - w, 0, 1 );
  30485. setPoint( 'cf2', w, 0, 1 );
  30486. setPoint( 'cf3', 0, - h, 1 );
  30487. setPoint( 'cf4', 0, h, 1 );
  30488. setPoint( 'cn1', - w, 0, - 1 );
  30489. setPoint( 'cn2', w, 0, - 1 );
  30490. setPoint( 'cn3', 0, - h, - 1 );
  30491. setPoint( 'cn4', 0, h, - 1 );
  30492. geometry.getAttribute( 'position' ).needsUpdate = true;
  30493. };
  30494. }();
  30495. /**
  30496. * @author mrdoob / http://mrdoob.com/
  30497. * @author Mugen87 / http://github.com/Mugen87
  30498. */
  30499. function BoxHelper( object, color ) {
  30500. this.object = object;
  30501. if ( color === undefined ) color = 0xffff00;
  30502. 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 ] );
  30503. var positions = new Float32Array( 8 * 3 );
  30504. var geometry = new BufferGeometry();
  30505. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30506. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  30507. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  30508. this.matrixAutoUpdate = false;
  30509. this.update();
  30510. }
  30511. BoxHelper.prototype = Object.create( LineSegments.prototype );
  30512. BoxHelper.prototype.constructor = BoxHelper;
  30513. BoxHelper.prototype.update = ( function () {
  30514. var box = new Box3();
  30515. return function update( object ) {
  30516. if ( object !== undefined ) {
  30517. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  30518. }
  30519. if ( this.object !== undefined ) {
  30520. box.setFromObject( this.object );
  30521. }
  30522. if ( box.isEmpty() ) return;
  30523. var min = box.min;
  30524. var max = box.max;
  30525. /*
  30526. 5____4
  30527. 1/___0/|
  30528. | 6__|_7
  30529. 2/___3/
  30530. 0: max.x, max.y, max.z
  30531. 1: min.x, max.y, max.z
  30532. 2: min.x, min.y, max.z
  30533. 3: max.x, min.y, max.z
  30534. 4: max.x, max.y, min.z
  30535. 5: min.x, max.y, min.z
  30536. 6: min.x, min.y, min.z
  30537. 7: max.x, min.y, min.z
  30538. */
  30539. var position = this.geometry.attributes.position;
  30540. var array = position.array;
  30541. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  30542. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  30543. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  30544. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  30545. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  30546. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  30547. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  30548. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  30549. position.needsUpdate = true;
  30550. this.geometry.computeBoundingSphere();
  30551. };
  30552. } )();
  30553. BoxHelper.prototype.setFromObject = function ( object ) {
  30554. this.object = object;
  30555. this.update();
  30556. return this;
  30557. };
  30558. /**
  30559. * @author WestLangley / http://github.com/WestLangley
  30560. */
  30561. function Box3Helper( box, hex ) {
  30562. this.type = 'Box3Helper';
  30563. this.box = box;
  30564. var color = ( hex !== undefined ) ? hex : 0xffff00;
  30565. 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 ] );
  30566. 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 ];
  30567. var geometry = new BufferGeometry();
  30568. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30569. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30570. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  30571. this.geometry.computeBoundingSphere();
  30572. }
  30573. Box3Helper.prototype = Object.create( LineSegments.prototype );
  30574. Box3Helper.prototype.constructor = Box3Helper;
  30575. Box3Helper.prototype.updateMatrixWorld = function ( force ) {
  30576. var box = this.box;
  30577. if ( box.isEmpty() ) return;
  30578. box.getCenter( this.position );
  30579. box.getSize( this.scale );
  30580. this.scale.multiplyScalar( 0.5 );
  30581. Object3D.prototype.updateMatrixWorld.call( this, force );
  30582. };
  30583. /**
  30584. * @author WestLangley / http://github.com/WestLangley
  30585. */
  30586. function PlaneHelper( plane, size, hex ) {
  30587. this.type = 'PlaneHelper';
  30588. this.plane = plane;
  30589. this.size = ( size === undefined ) ? 1 : size;
  30590. var color = ( hex !== undefined ) ? hex : 0xffff00;
  30591. 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 ];
  30592. var geometry = new BufferGeometry();
  30593. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30594. geometry.computeBoundingSphere();
  30595. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  30596. //
  30597. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  30598. var geometry2 = new BufferGeometry();
  30599. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  30600. geometry2.computeBoundingSphere();
  30601. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  30602. }
  30603. PlaneHelper.prototype = Object.create( Line.prototype );
  30604. PlaneHelper.prototype.constructor = PlaneHelper;
  30605. PlaneHelper.prototype.updateMatrixWorld = function ( force ) {
  30606. var scale = - this.plane.constant;
  30607. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  30608. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  30609. this.lookAt( this.plane.normal );
  30610. Object3D.prototype.updateMatrixWorld.call( this, force );
  30611. };
  30612. /**
  30613. * @author WestLangley / http://github.com/WestLangley
  30614. * @author zz85 / http://github.com/zz85
  30615. * @author bhouston / http://clara.io
  30616. *
  30617. * Creates an arrow for visualizing directions
  30618. *
  30619. * Parameters:
  30620. * dir - Vector3
  30621. * origin - Vector3
  30622. * length - Number
  30623. * color - color in hex value
  30624. * headLength - Number
  30625. * headWidth - Number
  30626. */
  30627. var lineGeometry;
  30628. var coneGeometry;
  30629. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  30630. // dir is assumed to be normalized
  30631. Object3D.call( this );
  30632. if ( color === undefined ) color = 0xffff00;
  30633. if ( length === undefined ) length = 1;
  30634. if ( headLength === undefined ) headLength = 0.2 * length;
  30635. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  30636. if ( lineGeometry === undefined ) {
  30637. lineGeometry = new BufferGeometry();
  30638. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  30639. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  30640. coneGeometry.translate( 0, - 0.5, 0 );
  30641. }
  30642. this.position.copy( origin );
  30643. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  30644. this.line.matrixAutoUpdate = false;
  30645. this.add( this.line );
  30646. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  30647. this.cone.matrixAutoUpdate = false;
  30648. this.add( this.cone );
  30649. this.setDirection( dir );
  30650. this.setLength( length, headLength, headWidth );
  30651. }
  30652. ArrowHelper.prototype = Object.create( Object3D.prototype );
  30653. ArrowHelper.prototype.constructor = ArrowHelper;
  30654. ArrowHelper.prototype.setDirection = ( function () {
  30655. var axis = new Vector3();
  30656. var radians;
  30657. return function setDirection( dir ) {
  30658. // dir is assumed to be normalized
  30659. if ( dir.y > 0.99999 ) {
  30660. this.quaternion.set( 0, 0, 0, 1 );
  30661. } else if ( dir.y < - 0.99999 ) {
  30662. this.quaternion.set( 1, 0, 0, 0 );
  30663. } else {
  30664. axis.set( dir.z, 0, - dir.x ).normalize();
  30665. radians = Math.acos( dir.y );
  30666. this.quaternion.setFromAxisAngle( axis, radians );
  30667. }
  30668. };
  30669. }() );
  30670. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  30671. if ( headLength === undefined ) headLength = 0.2 * length;
  30672. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  30673. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  30674. this.line.updateMatrix();
  30675. this.cone.scale.set( headWidth, headLength, headWidth );
  30676. this.cone.position.y = length;
  30677. this.cone.updateMatrix();
  30678. };
  30679. ArrowHelper.prototype.setColor = function ( color ) {
  30680. this.line.material.color.copy( color );
  30681. this.cone.material.color.copy( color );
  30682. };
  30683. /**
  30684. * @author sroucheray / http://sroucheray.org/
  30685. * @author mrdoob / http://mrdoob.com/
  30686. */
  30687. function AxesHelper( size ) {
  30688. size = size || 1;
  30689. var vertices = [
  30690. 0, 0, 0, size, 0, 0,
  30691. 0, 0, 0, 0, size, 0,
  30692. 0, 0, 0, 0, 0, size
  30693. ];
  30694. var colors = [
  30695. 1, 0, 0, 1, 0.6, 0,
  30696. 0, 1, 0, 0.6, 1, 0,
  30697. 0, 0, 1, 0, 0.6, 1
  30698. ];
  30699. var geometry = new BufferGeometry();
  30700. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30701. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30702. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  30703. LineSegments.call( this, geometry, material );
  30704. }
  30705. AxesHelper.prototype = Object.create( LineSegments.prototype );
  30706. AxesHelper.prototype.constructor = AxesHelper;
  30707. /**
  30708. * @author mrdoob / http://mrdoob.com/
  30709. */
  30710. function Face4( a, b, c, d, normal, color, materialIndex ) {
  30711. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  30712. return new Face3( a, b, c, normal, color, materialIndex );
  30713. }
  30714. var LineStrip = 0;
  30715. var LinePieces = 1;
  30716. function MeshFaceMaterial( materials ) {
  30717. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  30718. return materials;
  30719. }
  30720. function MultiMaterial( materials ) {
  30721. if ( materials === undefined ) materials = [];
  30722. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  30723. materials.isMultiMaterial = true;
  30724. materials.materials = materials;
  30725. materials.clone = function () {
  30726. return materials.slice();
  30727. };
  30728. return materials;
  30729. }
  30730. function PointCloud( geometry, material ) {
  30731. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  30732. return new Points( geometry, material );
  30733. }
  30734. function Particle( material ) {
  30735. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  30736. return new Sprite( material );
  30737. }
  30738. function ParticleSystem( geometry, material ) {
  30739. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  30740. return new Points( geometry, material );
  30741. }
  30742. function PointCloudMaterial( parameters ) {
  30743. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  30744. return new PointsMaterial( parameters );
  30745. }
  30746. function ParticleBasicMaterial( parameters ) {
  30747. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  30748. return new PointsMaterial( parameters );
  30749. }
  30750. function ParticleSystemMaterial( parameters ) {
  30751. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  30752. return new PointsMaterial( parameters );
  30753. }
  30754. function Vertex( x, y, z ) {
  30755. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  30756. return new Vector3( x, y, z );
  30757. }
  30758. //
  30759. function DynamicBufferAttribute( array, itemSize ) {
  30760. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  30761. return new BufferAttribute( array, itemSize ).setDynamic( true );
  30762. }
  30763. function Int8Attribute( array, itemSize ) {
  30764. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  30765. return new Int8BufferAttribute( array, itemSize );
  30766. }
  30767. function Uint8Attribute( array, itemSize ) {
  30768. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  30769. return new Uint8BufferAttribute( array, itemSize );
  30770. }
  30771. function Uint8ClampedAttribute( array, itemSize ) {
  30772. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  30773. return new Uint8ClampedBufferAttribute( array, itemSize );
  30774. }
  30775. function Int16Attribute( array, itemSize ) {
  30776. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  30777. return new Int16BufferAttribute( array, itemSize );
  30778. }
  30779. function Uint16Attribute( array, itemSize ) {
  30780. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  30781. return new Uint16BufferAttribute( array, itemSize );
  30782. }
  30783. function Int32Attribute( array, itemSize ) {
  30784. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  30785. return new Int32BufferAttribute( array, itemSize );
  30786. }
  30787. function Uint32Attribute( array, itemSize ) {
  30788. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  30789. return new Uint32BufferAttribute( array, itemSize );
  30790. }
  30791. function Float32Attribute( array, itemSize ) {
  30792. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  30793. return new Float32BufferAttribute( array, itemSize );
  30794. }
  30795. function Float64Attribute( array, itemSize ) {
  30796. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  30797. return new Float64BufferAttribute( array, itemSize );
  30798. }
  30799. //
  30800. Curve.create = function ( construct, getPoint ) {
  30801. console.log( 'THREE.Curve.create() has been deprecated' );
  30802. construct.prototype = Object.create( Curve.prototype );
  30803. construct.prototype.constructor = construct;
  30804. construct.prototype.getPoint = getPoint;
  30805. return construct;
  30806. };
  30807. //
  30808. Object.assign( CurvePath.prototype, {
  30809. createPointsGeometry: function ( divisions ) {
  30810. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30811. // generate geometry from path points (for Line or Points objects)
  30812. var pts = this.getPoints( divisions );
  30813. return this.createGeometry( pts );
  30814. },
  30815. createSpacedPointsGeometry: function ( divisions ) {
  30816. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30817. // generate geometry from equidistant sampling along the path
  30818. var pts = this.getSpacedPoints( divisions );
  30819. return this.createGeometry( pts );
  30820. },
  30821. createGeometry: function ( points ) {
  30822. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30823. var geometry = new Geometry();
  30824. for ( var i = 0, l = points.length; i < l; i ++ ) {
  30825. var point = points[ i ];
  30826. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  30827. }
  30828. return geometry;
  30829. }
  30830. } );
  30831. //
  30832. Object.assign( Path.prototype, {
  30833. fromPoints: function ( points ) {
  30834. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  30835. this.setFromPoints( points );
  30836. }
  30837. } );
  30838. //
  30839. function ClosedSplineCurve3( points ) {
  30840. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30841. CatmullRomCurve3.call( this, points );
  30842. this.type = 'catmullrom';
  30843. this.closed = true;
  30844. }
  30845. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30846. //
  30847. function SplineCurve3( points ) {
  30848. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30849. CatmullRomCurve3.call( this, points );
  30850. this.type = 'catmullrom';
  30851. }
  30852. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30853. //
  30854. function Spline( points ) {
  30855. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  30856. CatmullRomCurve3.call( this, points );
  30857. this.type = 'catmullrom';
  30858. }
  30859. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  30860. Object.assign( Spline.prototype, {
  30861. initFromArray: function ( /* a */ ) {
  30862. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  30863. },
  30864. getControlPointsArray: function ( /* optionalTarget */ ) {
  30865. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  30866. },
  30867. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  30868. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  30869. }
  30870. } );
  30871. //
  30872. function AxisHelper( size ) {
  30873. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  30874. return new AxesHelper( size );
  30875. }
  30876. function BoundingBoxHelper( object, color ) {
  30877. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  30878. return new BoxHelper( object, color );
  30879. }
  30880. function EdgesHelper( object, hex ) {
  30881. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  30882. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30883. }
  30884. GridHelper.prototype.setColors = function () {
  30885. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  30886. };
  30887. SkeletonHelper.prototype.update = function () {
  30888. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  30889. };
  30890. function WireframeHelper( object, hex ) {
  30891. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  30892. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30893. }
  30894. //
  30895. Object.assign( Loader.prototype, {
  30896. extractUrlBase: function ( url ) {
  30897. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  30898. return LoaderUtils.extractUrlBase( url );
  30899. }
  30900. } );
  30901. function XHRLoader( manager ) {
  30902. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  30903. return new FileLoader( manager );
  30904. }
  30905. function BinaryTextureLoader( manager ) {
  30906. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  30907. return new DataTextureLoader( manager );
  30908. }
  30909. //
  30910. Object.assign( Box2.prototype, {
  30911. center: function ( optionalTarget ) {
  30912. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  30913. return this.getCenter( optionalTarget );
  30914. },
  30915. empty: function () {
  30916. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  30917. return this.isEmpty();
  30918. },
  30919. isIntersectionBox: function ( box ) {
  30920. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30921. return this.intersectsBox( box );
  30922. },
  30923. size: function ( optionalTarget ) {
  30924. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  30925. return this.getSize( optionalTarget );
  30926. }
  30927. } );
  30928. Object.assign( Box3.prototype, {
  30929. center: function ( optionalTarget ) {
  30930. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  30931. return this.getCenter( optionalTarget );
  30932. },
  30933. empty: function () {
  30934. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  30935. return this.isEmpty();
  30936. },
  30937. isIntersectionBox: function ( box ) {
  30938. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30939. return this.intersectsBox( box );
  30940. },
  30941. isIntersectionSphere: function ( sphere ) {
  30942. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30943. return this.intersectsSphere( sphere );
  30944. },
  30945. size: function ( optionalTarget ) {
  30946. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  30947. return this.getSize( optionalTarget );
  30948. }
  30949. } );
  30950. Line3.prototype.center = function ( optionalTarget ) {
  30951. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  30952. return this.getCenter( optionalTarget );
  30953. };
  30954. Object.assign( _Math, {
  30955. random16: function () {
  30956. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  30957. return Math.random();
  30958. },
  30959. nearestPowerOfTwo: function ( value ) {
  30960. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  30961. return _Math.floorPowerOfTwo( value );
  30962. },
  30963. nextPowerOfTwo: function ( value ) {
  30964. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  30965. return _Math.ceilPowerOfTwo( value );
  30966. }
  30967. } );
  30968. Object.assign( Matrix3.prototype, {
  30969. flattenToArrayOffset: function ( array, offset ) {
  30970. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  30971. return this.toArray( array, offset );
  30972. },
  30973. multiplyVector3: function ( vector ) {
  30974. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  30975. return vector.applyMatrix3( this );
  30976. },
  30977. multiplyVector3Array: function ( /* a */ ) {
  30978. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  30979. },
  30980. applyToBuffer: function ( buffer /*, offset, length */ ) {
  30981. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  30982. return this.applyToBufferAttribute( buffer );
  30983. },
  30984. applyToVector3Array: function ( /* array, offset, length */ ) {
  30985. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  30986. }
  30987. } );
  30988. Object.assign( Matrix4.prototype, {
  30989. extractPosition: function ( m ) {
  30990. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  30991. return this.copyPosition( m );
  30992. },
  30993. flattenToArrayOffset: function ( array, offset ) {
  30994. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  30995. return this.toArray( array, offset );
  30996. },
  30997. getPosition: function () {
  30998. var v1;
  30999. return function getPosition() {
  31000. if ( v1 === undefined ) v1 = new Vector3();
  31001. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  31002. return v1.setFromMatrixColumn( this, 3 );
  31003. };
  31004. }(),
  31005. setRotationFromQuaternion: function ( q ) {
  31006. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  31007. return this.makeRotationFromQuaternion( q );
  31008. },
  31009. multiplyToArray: function () {
  31010. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  31011. },
  31012. multiplyVector3: function ( vector ) {
  31013. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  31014. return vector.applyMatrix4( this );
  31015. },
  31016. multiplyVector4: function ( vector ) {
  31017. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  31018. return vector.applyMatrix4( this );
  31019. },
  31020. multiplyVector3Array: function ( /* a */ ) {
  31021. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  31022. },
  31023. rotateAxis: function ( v ) {
  31024. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  31025. v.transformDirection( this );
  31026. },
  31027. crossVector: function ( vector ) {
  31028. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  31029. return vector.applyMatrix4( this );
  31030. },
  31031. translate: function () {
  31032. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  31033. },
  31034. rotateX: function () {
  31035. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  31036. },
  31037. rotateY: function () {
  31038. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  31039. },
  31040. rotateZ: function () {
  31041. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  31042. },
  31043. rotateByAxis: function () {
  31044. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  31045. },
  31046. applyToBuffer: function ( buffer /*, offset, length */ ) {
  31047. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  31048. return this.applyToBufferAttribute( buffer );
  31049. },
  31050. applyToVector3Array: function ( /* array, offset, length */ ) {
  31051. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  31052. },
  31053. makeFrustum: function ( left, right, bottom, top, near, far ) {
  31054. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  31055. return this.makePerspective( left, right, top, bottom, near, far );
  31056. }
  31057. } );
  31058. Plane.prototype.isIntersectionLine = function ( line ) {
  31059. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  31060. return this.intersectsLine( line );
  31061. };
  31062. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  31063. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  31064. return vector.applyQuaternion( this );
  31065. };
  31066. Object.assign( Ray.prototype, {
  31067. isIntersectionBox: function ( box ) {
  31068. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  31069. return this.intersectsBox( box );
  31070. },
  31071. isIntersectionPlane: function ( plane ) {
  31072. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  31073. return this.intersectsPlane( plane );
  31074. },
  31075. isIntersectionSphere: function ( sphere ) {
  31076. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  31077. return this.intersectsSphere( sphere );
  31078. }
  31079. } );
  31080. Object.assign( Triangle.prototype, {
  31081. area: function () {
  31082. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  31083. return this.getArea();
  31084. },
  31085. barycoordFromPoint: function ( point, target ) {
  31086. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  31087. return this.getBarycoord( point, target );
  31088. },
  31089. midpoint: function ( target ) {
  31090. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  31091. return this.getMidpoint( target );
  31092. },
  31093. normal: function ( target ) {
  31094. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  31095. return this.getNormal( target );
  31096. },
  31097. plane: function ( target ) {
  31098. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  31099. return this.getPlane( target );
  31100. }
  31101. } );
  31102. Object.assign( Triangle, {
  31103. barycoordFromPoint: function ( point, a, b, c, target ) {
  31104. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  31105. return Triangle.getBarycoord( point, a, b, c, target );
  31106. },
  31107. normal: function ( a, b, c, target ) {
  31108. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  31109. return Triangle.getNormal( a, b, c, target );
  31110. }
  31111. } );
  31112. Object.assign( Shape.prototype, {
  31113. extractAllPoints: function ( divisions ) {
  31114. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  31115. return this.extractPoints( divisions );
  31116. },
  31117. extrude: function ( options ) {
  31118. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  31119. return new ExtrudeGeometry( this, options );
  31120. },
  31121. makeGeometry: function ( options ) {
  31122. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  31123. return new ShapeGeometry( this, options );
  31124. }
  31125. } );
  31126. Object.assign( Vector2.prototype, {
  31127. fromAttribute: function ( attribute, index, offset ) {
  31128. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  31129. return this.fromBufferAttribute( attribute, index, offset );
  31130. },
  31131. distanceToManhattan: function ( v ) {
  31132. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  31133. return this.manhattanDistanceTo( v );
  31134. },
  31135. lengthManhattan: function () {
  31136. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  31137. return this.manhattanLength();
  31138. }
  31139. } );
  31140. Object.assign( Vector3.prototype, {
  31141. setEulerFromRotationMatrix: function () {
  31142. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  31143. },
  31144. setEulerFromQuaternion: function () {
  31145. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  31146. },
  31147. getPositionFromMatrix: function ( m ) {
  31148. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  31149. return this.setFromMatrixPosition( m );
  31150. },
  31151. getScaleFromMatrix: function ( m ) {
  31152. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  31153. return this.setFromMatrixScale( m );
  31154. },
  31155. getColumnFromMatrix: function ( index, matrix ) {
  31156. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  31157. return this.setFromMatrixColumn( matrix, index );
  31158. },
  31159. applyProjection: function ( m ) {
  31160. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  31161. return this.applyMatrix4( m );
  31162. },
  31163. fromAttribute: function ( attribute, index, offset ) {
  31164. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  31165. return this.fromBufferAttribute( attribute, index, offset );
  31166. },
  31167. distanceToManhattan: function ( v ) {
  31168. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  31169. return this.manhattanDistanceTo( v );
  31170. },
  31171. lengthManhattan: function () {
  31172. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  31173. return this.manhattanLength();
  31174. }
  31175. } );
  31176. Object.assign( Vector4.prototype, {
  31177. fromAttribute: function ( attribute, index, offset ) {
  31178. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  31179. return this.fromBufferAttribute( attribute, index, offset );
  31180. },
  31181. lengthManhattan: function () {
  31182. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  31183. return this.manhattanLength();
  31184. }
  31185. } );
  31186. //
  31187. Object.assign( Geometry.prototype, {
  31188. computeTangents: function () {
  31189. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  31190. },
  31191. computeLineDistances: function () {
  31192. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  31193. }
  31194. } );
  31195. Object.assign( Object3D.prototype, {
  31196. getChildByName: function ( name ) {
  31197. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  31198. return this.getObjectByName( name );
  31199. },
  31200. renderDepth: function () {
  31201. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  31202. },
  31203. translate: function ( distance, axis ) {
  31204. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  31205. return this.translateOnAxis( axis, distance );
  31206. },
  31207. getWorldRotation: function () {
  31208. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  31209. }
  31210. } );
  31211. Object.defineProperties( Object3D.prototype, {
  31212. eulerOrder: {
  31213. get: function () {
  31214. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  31215. return this.rotation.order;
  31216. },
  31217. set: function ( value ) {
  31218. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  31219. this.rotation.order = value;
  31220. }
  31221. },
  31222. useQuaternion: {
  31223. get: function () {
  31224. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  31225. },
  31226. set: function () {
  31227. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  31228. }
  31229. }
  31230. } );
  31231. Object.defineProperties( LOD.prototype, {
  31232. objects: {
  31233. get: function () {
  31234. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  31235. return this.levels;
  31236. }
  31237. }
  31238. } );
  31239. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  31240. get: function () {
  31241. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  31242. },
  31243. set: function () {
  31244. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  31245. }
  31246. } );
  31247. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  31248. get: function () {
  31249. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  31250. return this.arcLengthDivisions;
  31251. },
  31252. set: function ( value ) {
  31253. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  31254. this.arcLengthDivisions = value;
  31255. }
  31256. } );
  31257. //
  31258. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  31259. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  31260. "Use .setFocalLength and .filmGauge for a photographic setup." );
  31261. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  31262. this.setFocalLength( focalLength );
  31263. };
  31264. //
  31265. Object.defineProperties( Light.prototype, {
  31266. onlyShadow: {
  31267. set: function () {
  31268. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  31269. }
  31270. },
  31271. shadowCameraFov: {
  31272. set: function ( value ) {
  31273. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  31274. this.shadow.camera.fov = value;
  31275. }
  31276. },
  31277. shadowCameraLeft: {
  31278. set: function ( value ) {
  31279. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  31280. this.shadow.camera.left = value;
  31281. }
  31282. },
  31283. shadowCameraRight: {
  31284. set: function ( value ) {
  31285. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  31286. this.shadow.camera.right = value;
  31287. }
  31288. },
  31289. shadowCameraTop: {
  31290. set: function ( value ) {
  31291. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  31292. this.shadow.camera.top = value;
  31293. }
  31294. },
  31295. shadowCameraBottom: {
  31296. set: function ( value ) {
  31297. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  31298. this.shadow.camera.bottom = value;
  31299. }
  31300. },
  31301. shadowCameraNear: {
  31302. set: function ( value ) {
  31303. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  31304. this.shadow.camera.near = value;
  31305. }
  31306. },
  31307. shadowCameraFar: {
  31308. set: function ( value ) {
  31309. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  31310. this.shadow.camera.far = value;
  31311. }
  31312. },
  31313. shadowCameraVisible: {
  31314. set: function () {
  31315. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  31316. }
  31317. },
  31318. shadowBias: {
  31319. set: function ( value ) {
  31320. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  31321. this.shadow.bias = value;
  31322. }
  31323. },
  31324. shadowDarkness: {
  31325. set: function () {
  31326. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  31327. }
  31328. },
  31329. shadowMapWidth: {
  31330. set: function ( value ) {
  31331. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  31332. this.shadow.mapSize.width = value;
  31333. }
  31334. },
  31335. shadowMapHeight: {
  31336. set: function ( value ) {
  31337. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  31338. this.shadow.mapSize.height = value;
  31339. }
  31340. }
  31341. } );
  31342. //
  31343. Object.defineProperties( BufferAttribute.prototype, {
  31344. length: {
  31345. get: function () {
  31346. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  31347. return this.array.length;
  31348. }
  31349. },
  31350. copyIndicesArray: function ( /* indices */ ) {
  31351. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  31352. }
  31353. } );
  31354. Object.assign( BufferGeometry.prototype, {
  31355. addIndex: function ( index ) {
  31356. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  31357. this.setIndex( index );
  31358. },
  31359. addDrawCall: function ( start, count, indexOffset ) {
  31360. if ( indexOffset !== undefined ) {
  31361. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  31362. }
  31363. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  31364. this.addGroup( start, count );
  31365. },
  31366. clearDrawCalls: function () {
  31367. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  31368. this.clearGroups();
  31369. },
  31370. computeTangents: function () {
  31371. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  31372. },
  31373. computeOffsets: function () {
  31374. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  31375. }
  31376. } );
  31377. Object.defineProperties( BufferGeometry.prototype, {
  31378. drawcalls: {
  31379. get: function () {
  31380. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  31381. return this.groups;
  31382. }
  31383. },
  31384. offsets: {
  31385. get: function () {
  31386. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  31387. return this.groups;
  31388. }
  31389. }
  31390. } );
  31391. //
  31392. Object.assign( ExtrudeBufferGeometry.prototype, {
  31393. getArrays: function () {
  31394. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  31395. },
  31396. addShapeList: function () {
  31397. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  31398. },
  31399. addShape: function () {
  31400. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  31401. }
  31402. } );
  31403. //
  31404. Object.defineProperties( Uniform.prototype, {
  31405. dynamic: {
  31406. set: function () {
  31407. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  31408. }
  31409. },
  31410. onUpdate: {
  31411. value: function () {
  31412. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  31413. return this;
  31414. }
  31415. }
  31416. } );
  31417. //
  31418. Object.defineProperties( Material.prototype, {
  31419. wrapAround: {
  31420. get: function () {
  31421. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  31422. },
  31423. set: function () {
  31424. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  31425. }
  31426. },
  31427. wrapRGB: {
  31428. get: function () {
  31429. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  31430. return new Color();
  31431. }
  31432. },
  31433. shading: {
  31434. get: function () {
  31435. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  31436. },
  31437. set: function ( value ) {
  31438. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  31439. this.flatShading = ( value === FlatShading );
  31440. }
  31441. }
  31442. } );
  31443. Object.defineProperties( MeshPhongMaterial.prototype, {
  31444. metal: {
  31445. get: function () {
  31446. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  31447. return false;
  31448. },
  31449. set: function () {
  31450. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  31451. }
  31452. }
  31453. } );
  31454. Object.defineProperties( ShaderMaterial.prototype, {
  31455. derivatives: {
  31456. get: function () {
  31457. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  31458. return this.extensions.derivatives;
  31459. },
  31460. set: function ( value ) {
  31461. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  31462. this.extensions.derivatives = value;
  31463. }
  31464. }
  31465. } );
  31466. //
  31467. Object.assign( WebGLRenderer.prototype, {
  31468. getCurrentRenderTarget: function () {
  31469. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  31470. return this.getRenderTarget();
  31471. },
  31472. getMaxAnisotropy: function () {
  31473. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  31474. return this.capabilities.getMaxAnisotropy();
  31475. },
  31476. getPrecision: function () {
  31477. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  31478. return this.capabilities.precision;
  31479. },
  31480. resetGLState: function () {
  31481. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  31482. return this.state.reset();
  31483. },
  31484. supportsFloatTextures: function () {
  31485. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  31486. return this.extensions.get( 'OES_texture_float' );
  31487. },
  31488. supportsHalfFloatTextures: function () {
  31489. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  31490. return this.extensions.get( 'OES_texture_half_float' );
  31491. },
  31492. supportsStandardDerivatives: function () {
  31493. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  31494. return this.extensions.get( 'OES_standard_derivatives' );
  31495. },
  31496. supportsCompressedTextureS3TC: function () {
  31497. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  31498. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  31499. },
  31500. supportsCompressedTexturePVRTC: function () {
  31501. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  31502. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  31503. },
  31504. supportsBlendMinMax: function () {
  31505. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  31506. return this.extensions.get( 'EXT_blend_minmax' );
  31507. },
  31508. supportsVertexTextures: function () {
  31509. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  31510. return this.capabilities.vertexTextures;
  31511. },
  31512. supportsInstancedArrays: function () {
  31513. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  31514. return this.extensions.get( 'ANGLE_instanced_arrays' );
  31515. },
  31516. enableScissorTest: function ( boolean ) {
  31517. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  31518. this.setScissorTest( boolean );
  31519. },
  31520. initMaterial: function () {
  31521. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  31522. },
  31523. addPrePlugin: function () {
  31524. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  31525. },
  31526. addPostPlugin: function () {
  31527. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  31528. },
  31529. updateShadowMap: function () {
  31530. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  31531. },
  31532. setFaceCulling: function () {
  31533. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  31534. }
  31535. } );
  31536. Object.defineProperties( WebGLRenderer.prototype, {
  31537. shadowMapEnabled: {
  31538. get: function () {
  31539. return this.shadowMap.enabled;
  31540. },
  31541. set: function ( value ) {
  31542. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  31543. this.shadowMap.enabled = value;
  31544. }
  31545. },
  31546. shadowMapType: {
  31547. get: function () {
  31548. return this.shadowMap.type;
  31549. },
  31550. set: function ( value ) {
  31551. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  31552. this.shadowMap.type = value;
  31553. }
  31554. },
  31555. shadowMapCullFace: {
  31556. get: function () {
  31557. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  31558. return undefined;
  31559. },
  31560. set: function ( /* value */ ) {
  31561. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  31562. }
  31563. }
  31564. } );
  31565. Object.defineProperties( WebGLShadowMap.prototype, {
  31566. cullFace: {
  31567. get: function () {
  31568. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  31569. return undefined;
  31570. },
  31571. set: function ( /* cullFace */ ) {
  31572. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  31573. }
  31574. },
  31575. renderReverseSided: {
  31576. get: function () {
  31577. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  31578. return undefined;
  31579. },
  31580. set: function () {
  31581. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  31582. }
  31583. },
  31584. renderSingleSided: {
  31585. get: function () {
  31586. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  31587. return undefined;
  31588. },
  31589. set: function () {
  31590. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  31591. }
  31592. }
  31593. } );
  31594. //
  31595. Object.defineProperties( WebGLRenderTarget.prototype, {
  31596. wrapS: {
  31597. get: function () {
  31598. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31599. return this.texture.wrapS;
  31600. },
  31601. set: function ( value ) {
  31602. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31603. this.texture.wrapS = value;
  31604. }
  31605. },
  31606. wrapT: {
  31607. get: function () {
  31608. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31609. return this.texture.wrapT;
  31610. },
  31611. set: function ( value ) {
  31612. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31613. this.texture.wrapT = value;
  31614. }
  31615. },
  31616. magFilter: {
  31617. get: function () {
  31618. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31619. return this.texture.magFilter;
  31620. },
  31621. set: function ( value ) {
  31622. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31623. this.texture.magFilter = value;
  31624. }
  31625. },
  31626. minFilter: {
  31627. get: function () {
  31628. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31629. return this.texture.minFilter;
  31630. },
  31631. set: function ( value ) {
  31632. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31633. this.texture.minFilter = value;
  31634. }
  31635. },
  31636. anisotropy: {
  31637. get: function () {
  31638. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31639. return this.texture.anisotropy;
  31640. },
  31641. set: function ( value ) {
  31642. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31643. this.texture.anisotropy = value;
  31644. }
  31645. },
  31646. offset: {
  31647. get: function () {
  31648. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31649. return this.texture.offset;
  31650. },
  31651. set: function ( value ) {
  31652. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31653. this.texture.offset = value;
  31654. }
  31655. },
  31656. repeat: {
  31657. get: function () {
  31658. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31659. return this.texture.repeat;
  31660. },
  31661. set: function ( value ) {
  31662. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31663. this.texture.repeat = value;
  31664. }
  31665. },
  31666. format: {
  31667. get: function () {
  31668. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31669. return this.texture.format;
  31670. },
  31671. set: function ( value ) {
  31672. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31673. this.texture.format = value;
  31674. }
  31675. },
  31676. type: {
  31677. get: function () {
  31678. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31679. return this.texture.type;
  31680. },
  31681. set: function ( value ) {
  31682. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31683. this.texture.type = value;
  31684. }
  31685. },
  31686. generateMipmaps: {
  31687. get: function () {
  31688. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31689. return this.texture.generateMipmaps;
  31690. },
  31691. set: function ( value ) {
  31692. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31693. this.texture.generateMipmaps = value;
  31694. }
  31695. }
  31696. } );
  31697. //
  31698. Object.defineProperties( WebVRManager.prototype, {
  31699. standing: {
  31700. set: function ( /* value */ ) {
  31701. console.warn( 'THREE.WebVRManager: .standing has been removed.' );
  31702. }
  31703. }
  31704. } );
  31705. //
  31706. Audio.prototype.load = function ( file ) {
  31707. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  31708. var scope = this;
  31709. var audioLoader = new AudioLoader();
  31710. audioLoader.load( file, function ( buffer ) {
  31711. scope.setBuffer( buffer );
  31712. } );
  31713. return this;
  31714. };
  31715. AudioAnalyser.prototype.getData = function () {
  31716. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  31717. return this.getFrequencyData();
  31718. };
  31719. //
  31720. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  31721. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  31722. return this.update( renderer, scene );
  31723. };
  31724. //
  31725. var GeometryUtils = {
  31726. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  31727. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  31728. var matrix;
  31729. if ( geometry2.isMesh ) {
  31730. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  31731. matrix = geometry2.matrix;
  31732. geometry2 = geometry2.geometry;
  31733. }
  31734. geometry1.merge( geometry2, matrix, materialIndexOffset );
  31735. },
  31736. center: function ( geometry ) {
  31737. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  31738. return geometry.center();
  31739. }
  31740. };
  31741. var ImageUtils = {
  31742. crossOrigin: undefined,
  31743. loadTexture: function ( url, mapping, onLoad, onError ) {
  31744. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  31745. var loader = new TextureLoader();
  31746. loader.setCrossOrigin( this.crossOrigin );
  31747. var texture = loader.load( url, onLoad, undefined, onError );
  31748. if ( mapping ) texture.mapping = mapping;
  31749. return texture;
  31750. },
  31751. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  31752. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  31753. var loader = new CubeTextureLoader();
  31754. loader.setCrossOrigin( this.crossOrigin );
  31755. var texture = loader.load( urls, onLoad, undefined, onError );
  31756. if ( mapping ) texture.mapping = mapping;
  31757. return texture;
  31758. },
  31759. loadCompressedTexture: function () {
  31760. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  31761. },
  31762. loadCompressedTextureCube: function () {
  31763. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  31764. }
  31765. };
  31766. //
  31767. function Projector() {
  31768. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  31769. this.projectVector = function ( vector, camera ) {
  31770. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  31771. vector.project( camera );
  31772. };
  31773. this.unprojectVector = function ( vector, camera ) {
  31774. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  31775. vector.unproject( camera );
  31776. };
  31777. this.pickingRay = function () {
  31778. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  31779. };
  31780. }
  31781. //
  31782. function CanvasRenderer() {
  31783. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  31784. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  31785. this.clear = function () {};
  31786. this.render = function () {};
  31787. this.setClearColor = function () {};
  31788. this.setSize = function () {};
  31789. }
  31790. //
  31791. var SceneUtils = {
  31792. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  31793. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  31794. },
  31795. detach: function ( /* child, parent, scene */ ) {
  31796. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  31797. },
  31798. attach: function ( /* child, scene, parent */ ) {
  31799. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  31800. }
  31801. };
  31802. //
  31803. function LensFlare() {
  31804. console.error( 'THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js' );
  31805. }
  31806. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  31807. exports.WebGLRenderTarget = WebGLRenderTarget;
  31808. exports.WebGLRenderer = WebGLRenderer;
  31809. exports.ShaderLib = ShaderLib;
  31810. exports.UniformsLib = UniformsLib;
  31811. exports.UniformsUtils = UniformsUtils;
  31812. exports.ShaderChunk = ShaderChunk;
  31813. exports.FogExp2 = FogExp2;
  31814. exports.Fog = Fog;
  31815. exports.Scene = Scene;
  31816. exports.Sprite = Sprite;
  31817. exports.LOD = LOD;
  31818. exports.SkinnedMesh = SkinnedMesh;
  31819. exports.Skeleton = Skeleton;
  31820. exports.Bone = Bone;
  31821. exports.Mesh = Mesh;
  31822. exports.LineSegments = LineSegments;
  31823. exports.LineLoop = LineLoop;
  31824. exports.Line = Line;
  31825. exports.Points = Points;
  31826. exports.Group = Group;
  31827. exports.VideoTexture = VideoTexture;
  31828. exports.DataTexture = DataTexture;
  31829. exports.CompressedTexture = CompressedTexture;
  31830. exports.CubeTexture = CubeTexture;
  31831. exports.CanvasTexture = CanvasTexture;
  31832. exports.DepthTexture = DepthTexture;
  31833. exports.Texture = Texture;
  31834. exports.CompressedTextureLoader = CompressedTextureLoader;
  31835. exports.DataTextureLoader = DataTextureLoader;
  31836. exports.CubeTextureLoader = CubeTextureLoader;
  31837. exports.TextureLoader = TextureLoader;
  31838. exports.ObjectLoader = ObjectLoader;
  31839. exports.MaterialLoader = MaterialLoader;
  31840. exports.BufferGeometryLoader = BufferGeometryLoader;
  31841. exports.DefaultLoadingManager = DefaultLoadingManager;
  31842. exports.LoadingManager = LoadingManager;
  31843. exports.JSONLoader = JSONLoader;
  31844. exports.ImageLoader = ImageLoader;
  31845. exports.ImageBitmapLoader = ImageBitmapLoader;
  31846. exports.FontLoader = FontLoader;
  31847. exports.FileLoader = FileLoader;
  31848. exports.Loader = Loader;
  31849. exports.LoaderUtils = LoaderUtils;
  31850. exports.Cache = Cache;
  31851. exports.AudioLoader = AudioLoader;
  31852. exports.SpotLightShadow = SpotLightShadow;
  31853. exports.SpotLight = SpotLight;
  31854. exports.PointLight = PointLight;
  31855. exports.RectAreaLight = RectAreaLight;
  31856. exports.HemisphereLight = HemisphereLight;
  31857. exports.DirectionalLightShadow = DirectionalLightShadow;
  31858. exports.DirectionalLight = DirectionalLight;
  31859. exports.AmbientLight = AmbientLight;
  31860. exports.LightShadow = LightShadow;
  31861. exports.Light = Light;
  31862. exports.StereoCamera = StereoCamera;
  31863. exports.PerspectiveCamera = PerspectiveCamera;
  31864. exports.OrthographicCamera = OrthographicCamera;
  31865. exports.CubeCamera = CubeCamera;
  31866. exports.ArrayCamera = ArrayCamera;
  31867. exports.Camera = Camera;
  31868. exports.AudioListener = AudioListener;
  31869. exports.PositionalAudio = PositionalAudio;
  31870. exports.AudioContext = AudioContext;
  31871. exports.AudioAnalyser = AudioAnalyser;
  31872. exports.Audio = Audio;
  31873. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  31874. exports.StringKeyframeTrack = StringKeyframeTrack;
  31875. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  31876. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  31877. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  31878. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  31879. exports.PropertyMixer = PropertyMixer;
  31880. exports.PropertyBinding = PropertyBinding;
  31881. exports.KeyframeTrack = KeyframeTrack;
  31882. exports.AnimationUtils = AnimationUtils;
  31883. exports.AnimationObjectGroup = AnimationObjectGroup;
  31884. exports.AnimationMixer = AnimationMixer;
  31885. exports.AnimationClip = AnimationClip;
  31886. exports.Uniform = Uniform;
  31887. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  31888. exports.BufferGeometry = BufferGeometry;
  31889. exports.Geometry = Geometry;
  31890. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  31891. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  31892. exports.InterleavedBuffer = InterleavedBuffer;
  31893. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  31894. exports.Face3 = Face3;
  31895. exports.Object3D = Object3D;
  31896. exports.Raycaster = Raycaster;
  31897. exports.Layers = Layers;
  31898. exports.EventDispatcher = EventDispatcher;
  31899. exports.Clock = Clock;
  31900. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  31901. exports.LinearInterpolant = LinearInterpolant;
  31902. exports.DiscreteInterpolant = DiscreteInterpolant;
  31903. exports.CubicInterpolant = CubicInterpolant;
  31904. exports.Interpolant = Interpolant;
  31905. exports.Triangle = Triangle;
  31906. exports.Math = _Math;
  31907. exports.Spherical = Spherical;
  31908. exports.Cylindrical = Cylindrical;
  31909. exports.Plane = Plane;
  31910. exports.Frustum = Frustum;
  31911. exports.Sphere = Sphere;
  31912. exports.Ray = Ray;
  31913. exports.Matrix4 = Matrix4;
  31914. exports.Matrix3 = Matrix3;
  31915. exports.Box3 = Box3;
  31916. exports.Box2 = Box2;
  31917. exports.Line3 = Line3;
  31918. exports.Euler = Euler;
  31919. exports.Vector4 = Vector4;
  31920. exports.Vector3 = Vector3;
  31921. exports.Vector2 = Vector2;
  31922. exports.Quaternion = Quaternion;
  31923. exports.Color = Color;
  31924. exports.ImmediateRenderObject = ImmediateRenderObject;
  31925. exports.VertexNormalsHelper = VertexNormalsHelper;
  31926. exports.SpotLightHelper = SpotLightHelper;
  31927. exports.SkeletonHelper = SkeletonHelper;
  31928. exports.PointLightHelper = PointLightHelper;
  31929. exports.RectAreaLightHelper = RectAreaLightHelper;
  31930. exports.HemisphereLightHelper = HemisphereLightHelper;
  31931. exports.GridHelper = GridHelper;
  31932. exports.PolarGridHelper = PolarGridHelper;
  31933. exports.FaceNormalsHelper = FaceNormalsHelper;
  31934. exports.DirectionalLightHelper = DirectionalLightHelper;
  31935. exports.CameraHelper = CameraHelper;
  31936. exports.BoxHelper = BoxHelper;
  31937. exports.Box3Helper = Box3Helper;
  31938. exports.PlaneHelper = PlaneHelper;
  31939. exports.ArrowHelper = ArrowHelper;
  31940. exports.AxesHelper = AxesHelper;
  31941. exports.Shape = Shape;
  31942. exports.Path = Path;
  31943. exports.ShapePath = ShapePath;
  31944. exports.Font = Font;
  31945. exports.CurvePath = CurvePath;
  31946. exports.Curve = Curve;
  31947. exports.ShapeUtils = ShapeUtils;
  31948. exports.WebGLUtils = WebGLUtils;
  31949. exports.WireframeGeometry = WireframeGeometry;
  31950. exports.ParametricGeometry = ParametricGeometry;
  31951. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  31952. exports.TetrahedronGeometry = TetrahedronGeometry;
  31953. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  31954. exports.OctahedronGeometry = OctahedronGeometry;
  31955. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  31956. exports.IcosahedronGeometry = IcosahedronGeometry;
  31957. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  31958. exports.DodecahedronGeometry = DodecahedronGeometry;
  31959. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  31960. exports.PolyhedronGeometry = PolyhedronGeometry;
  31961. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  31962. exports.TubeGeometry = TubeGeometry;
  31963. exports.TubeBufferGeometry = TubeBufferGeometry;
  31964. exports.TorusKnotGeometry = TorusKnotGeometry;
  31965. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  31966. exports.TorusGeometry = TorusGeometry;
  31967. exports.TorusBufferGeometry = TorusBufferGeometry;
  31968. exports.TextGeometry = TextGeometry;
  31969. exports.TextBufferGeometry = TextBufferGeometry;
  31970. exports.SphereGeometry = SphereGeometry;
  31971. exports.SphereBufferGeometry = SphereBufferGeometry;
  31972. exports.RingGeometry = RingGeometry;
  31973. exports.RingBufferGeometry = RingBufferGeometry;
  31974. exports.PlaneGeometry = PlaneGeometry;
  31975. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  31976. exports.LatheGeometry = LatheGeometry;
  31977. exports.LatheBufferGeometry = LatheBufferGeometry;
  31978. exports.ShapeGeometry = ShapeGeometry;
  31979. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  31980. exports.ExtrudeGeometry = ExtrudeGeometry;
  31981. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  31982. exports.EdgesGeometry = EdgesGeometry;
  31983. exports.ConeGeometry = ConeGeometry;
  31984. exports.ConeBufferGeometry = ConeBufferGeometry;
  31985. exports.CylinderGeometry = CylinderGeometry;
  31986. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  31987. exports.CircleGeometry = CircleGeometry;
  31988. exports.CircleBufferGeometry = CircleBufferGeometry;
  31989. exports.BoxGeometry = BoxGeometry;
  31990. exports.BoxBufferGeometry = BoxBufferGeometry;
  31991. exports.ShadowMaterial = ShadowMaterial;
  31992. exports.SpriteMaterial = SpriteMaterial;
  31993. exports.RawShaderMaterial = RawShaderMaterial;
  31994. exports.ShaderMaterial = ShaderMaterial;
  31995. exports.PointsMaterial = PointsMaterial;
  31996. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  31997. exports.MeshStandardMaterial = MeshStandardMaterial;
  31998. exports.MeshPhongMaterial = MeshPhongMaterial;
  31999. exports.MeshToonMaterial = MeshToonMaterial;
  32000. exports.MeshNormalMaterial = MeshNormalMaterial;
  32001. exports.MeshLambertMaterial = MeshLambertMaterial;
  32002. exports.MeshDepthMaterial = MeshDepthMaterial;
  32003. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  32004. exports.MeshBasicMaterial = MeshBasicMaterial;
  32005. exports.LineDashedMaterial = LineDashedMaterial;
  32006. exports.LineBasicMaterial = LineBasicMaterial;
  32007. exports.Material = Material;
  32008. exports.Float64BufferAttribute = Float64BufferAttribute;
  32009. exports.Float32BufferAttribute = Float32BufferAttribute;
  32010. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  32011. exports.Int32BufferAttribute = Int32BufferAttribute;
  32012. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  32013. exports.Int16BufferAttribute = Int16BufferAttribute;
  32014. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  32015. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  32016. exports.Int8BufferAttribute = Int8BufferAttribute;
  32017. exports.BufferAttribute = BufferAttribute;
  32018. exports.ArcCurve = ArcCurve;
  32019. exports.CatmullRomCurve3 = CatmullRomCurve3;
  32020. exports.CubicBezierCurve = CubicBezierCurve;
  32021. exports.CubicBezierCurve3 = CubicBezierCurve3;
  32022. exports.EllipseCurve = EllipseCurve;
  32023. exports.LineCurve = LineCurve;
  32024. exports.LineCurve3 = LineCurve3;
  32025. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  32026. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  32027. exports.SplineCurve = SplineCurve;
  32028. exports.REVISION = REVISION;
  32029. exports.MOUSE = MOUSE;
  32030. exports.CullFaceNone = CullFaceNone;
  32031. exports.CullFaceBack = CullFaceBack;
  32032. exports.CullFaceFront = CullFaceFront;
  32033. exports.CullFaceFrontBack = CullFaceFrontBack;
  32034. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  32035. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  32036. exports.BasicShadowMap = BasicShadowMap;
  32037. exports.PCFShadowMap = PCFShadowMap;
  32038. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  32039. exports.FrontSide = FrontSide;
  32040. exports.BackSide = BackSide;
  32041. exports.DoubleSide = DoubleSide;
  32042. exports.FlatShading = FlatShading;
  32043. exports.SmoothShading = SmoothShading;
  32044. exports.NoColors = NoColors;
  32045. exports.FaceColors = FaceColors;
  32046. exports.VertexColors = VertexColors;
  32047. exports.NoBlending = NoBlending;
  32048. exports.NormalBlending = NormalBlending;
  32049. exports.AdditiveBlending = AdditiveBlending;
  32050. exports.SubtractiveBlending = SubtractiveBlending;
  32051. exports.MultiplyBlending = MultiplyBlending;
  32052. exports.CustomBlending = CustomBlending;
  32053. exports.AddEquation = AddEquation;
  32054. exports.SubtractEquation = SubtractEquation;
  32055. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  32056. exports.MinEquation = MinEquation;
  32057. exports.MaxEquation = MaxEquation;
  32058. exports.ZeroFactor = ZeroFactor;
  32059. exports.OneFactor = OneFactor;
  32060. exports.SrcColorFactor = SrcColorFactor;
  32061. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  32062. exports.SrcAlphaFactor = SrcAlphaFactor;
  32063. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  32064. exports.DstAlphaFactor = DstAlphaFactor;
  32065. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  32066. exports.DstColorFactor = DstColorFactor;
  32067. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  32068. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  32069. exports.NeverDepth = NeverDepth;
  32070. exports.AlwaysDepth = AlwaysDepth;
  32071. exports.LessDepth = LessDepth;
  32072. exports.LessEqualDepth = LessEqualDepth;
  32073. exports.EqualDepth = EqualDepth;
  32074. exports.GreaterEqualDepth = GreaterEqualDepth;
  32075. exports.GreaterDepth = GreaterDepth;
  32076. exports.NotEqualDepth = NotEqualDepth;
  32077. exports.MultiplyOperation = MultiplyOperation;
  32078. exports.MixOperation = MixOperation;
  32079. exports.AddOperation = AddOperation;
  32080. exports.NoToneMapping = NoToneMapping;
  32081. exports.LinearToneMapping = LinearToneMapping;
  32082. exports.ReinhardToneMapping = ReinhardToneMapping;
  32083. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  32084. exports.CineonToneMapping = CineonToneMapping;
  32085. exports.UVMapping = UVMapping;
  32086. exports.CubeReflectionMapping = CubeReflectionMapping;
  32087. exports.CubeRefractionMapping = CubeRefractionMapping;
  32088. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  32089. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  32090. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  32091. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  32092. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  32093. exports.RepeatWrapping = RepeatWrapping;
  32094. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  32095. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  32096. exports.NearestFilter = NearestFilter;
  32097. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  32098. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  32099. exports.LinearFilter = LinearFilter;
  32100. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  32101. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  32102. exports.UnsignedByteType = UnsignedByteType;
  32103. exports.ByteType = ByteType;
  32104. exports.ShortType = ShortType;
  32105. exports.UnsignedShortType = UnsignedShortType;
  32106. exports.IntType = IntType;
  32107. exports.UnsignedIntType = UnsignedIntType;
  32108. exports.FloatType = FloatType;
  32109. exports.HalfFloatType = HalfFloatType;
  32110. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  32111. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  32112. exports.UnsignedShort565Type = UnsignedShort565Type;
  32113. exports.UnsignedInt248Type = UnsignedInt248Type;
  32114. exports.AlphaFormat = AlphaFormat;
  32115. exports.RGBFormat = RGBFormat;
  32116. exports.RGBAFormat = RGBAFormat;
  32117. exports.LuminanceFormat = LuminanceFormat;
  32118. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  32119. exports.RGBEFormat = RGBEFormat;
  32120. exports.DepthFormat = DepthFormat;
  32121. exports.DepthStencilFormat = DepthStencilFormat;
  32122. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  32123. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  32124. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  32125. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  32126. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  32127. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  32128. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  32129. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  32130. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  32131. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  32132. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  32133. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  32134. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  32135. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  32136. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  32137. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  32138. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  32139. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  32140. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  32141. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  32142. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  32143. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  32144. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  32145. exports.LoopOnce = LoopOnce;
  32146. exports.LoopRepeat = LoopRepeat;
  32147. exports.LoopPingPong = LoopPingPong;
  32148. exports.InterpolateDiscrete = InterpolateDiscrete;
  32149. exports.InterpolateLinear = InterpolateLinear;
  32150. exports.InterpolateSmooth = InterpolateSmooth;
  32151. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  32152. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  32153. exports.WrapAroundEnding = WrapAroundEnding;
  32154. exports.TrianglesDrawMode = TrianglesDrawMode;
  32155. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  32156. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  32157. exports.LinearEncoding = LinearEncoding;
  32158. exports.sRGBEncoding = sRGBEncoding;
  32159. exports.GammaEncoding = GammaEncoding;
  32160. exports.RGBEEncoding = RGBEEncoding;
  32161. exports.LogLuvEncoding = LogLuvEncoding;
  32162. exports.RGBM7Encoding = RGBM7Encoding;
  32163. exports.RGBM16Encoding = RGBM16Encoding;
  32164. exports.RGBDEncoding = RGBDEncoding;
  32165. exports.BasicDepthPacking = BasicDepthPacking;
  32166. exports.RGBADepthPacking = RGBADepthPacking;
  32167. exports.CubeGeometry = BoxGeometry;
  32168. exports.Face4 = Face4;
  32169. exports.LineStrip = LineStrip;
  32170. exports.LinePieces = LinePieces;
  32171. exports.MeshFaceMaterial = MeshFaceMaterial;
  32172. exports.MultiMaterial = MultiMaterial;
  32173. exports.PointCloud = PointCloud;
  32174. exports.Particle = Particle;
  32175. exports.ParticleSystem = ParticleSystem;
  32176. exports.PointCloudMaterial = PointCloudMaterial;
  32177. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  32178. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  32179. exports.Vertex = Vertex;
  32180. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  32181. exports.Int8Attribute = Int8Attribute;
  32182. exports.Uint8Attribute = Uint8Attribute;
  32183. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  32184. exports.Int16Attribute = Int16Attribute;
  32185. exports.Uint16Attribute = Uint16Attribute;
  32186. exports.Int32Attribute = Int32Attribute;
  32187. exports.Uint32Attribute = Uint32Attribute;
  32188. exports.Float32Attribute = Float32Attribute;
  32189. exports.Float64Attribute = Float64Attribute;
  32190. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  32191. exports.SplineCurve3 = SplineCurve3;
  32192. exports.Spline = Spline;
  32193. exports.AxisHelper = AxisHelper;
  32194. exports.BoundingBoxHelper = BoundingBoxHelper;
  32195. exports.EdgesHelper = EdgesHelper;
  32196. exports.WireframeHelper = WireframeHelper;
  32197. exports.XHRLoader = XHRLoader;
  32198. exports.BinaryTextureLoader = BinaryTextureLoader;
  32199. exports.GeometryUtils = GeometryUtils;
  32200. exports.ImageUtils = ImageUtils;
  32201. exports.Projector = Projector;
  32202. exports.CanvasRenderer = CanvasRenderer;
  32203. exports.SceneUtils = SceneUtils;
  32204. exports.LensFlare = LensFlare;
  32205. Object.defineProperty(exports, '__esModule', { value: true });
  32206. })));
  32207. },{}],41:[function(_dereq_,module,exports){
  32208. /**
  32209. * @author mrdoob / http://mrdoob.com/
  32210. * @author Mugen87 / https://github.com/Mugen87
  32211. */
  32212. THREE.ColladaLoader = function ( manager ) {
  32213. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  32214. };
  32215. THREE.ColladaLoader.prototype = {
  32216. constructor: THREE.ColladaLoader,
  32217. crossOrigin: 'Anonymous',
  32218. load: function ( url, onLoad, onProgress, onError ) {
  32219. var scope = this;
  32220. var path = scope.path === undefined ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path;
  32221. var loader = new THREE.FileLoader( scope.manager );
  32222. loader.load( url, function ( text ) {
  32223. onLoad( scope.parse( text, path ) );
  32224. }, onProgress, onError );
  32225. },
  32226. setPath: function ( value ) {
  32227. this.path = value;
  32228. },
  32229. options: {
  32230. set convertUpAxis( value ) {
  32231. console.warn( 'THREE.ColladaLoader: options.convertUpAxis() has been removed. Up axis is converted automatically.' );
  32232. }
  32233. },
  32234. setCrossOrigin: function ( value ) {
  32235. this.crossOrigin = value;
  32236. },
  32237. parse: function ( text, path ) {
  32238. function getElementsByTagName( xml, name ) {
  32239. // Non recursive xml.getElementsByTagName() ...
  32240. var array = [];
  32241. var childNodes = xml.childNodes;
  32242. for ( var i = 0, l = childNodes.length; i < l; i ++ ) {
  32243. var child = childNodes[ i ];
  32244. if ( child.nodeName === name ) {
  32245. array.push( child );
  32246. }
  32247. }
  32248. return array;
  32249. }
  32250. function parseStrings( text ) {
  32251. if ( text.length === 0 ) return [];
  32252. var parts = text.trim().split( /\s+/ );
  32253. var array = new Array( parts.length );
  32254. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32255. array[ i ] = parts[ i ];
  32256. }
  32257. return array;
  32258. }
  32259. function parseFloats( text ) {
  32260. if ( text.length === 0 ) return [];
  32261. var parts = text.trim().split( /\s+/ );
  32262. var array = new Array( parts.length );
  32263. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32264. array[ i ] = parseFloat( parts[ i ] );
  32265. }
  32266. return array;
  32267. }
  32268. function parseInts( text ) {
  32269. if ( text.length === 0 ) return [];
  32270. var parts = text.trim().split( /\s+/ );
  32271. var array = new Array( parts.length );
  32272. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32273. array[ i ] = parseInt( parts[ i ] );
  32274. }
  32275. return array;
  32276. }
  32277. function parseId( text ) {
  32278. return text.substring( 1 );
  32279. }
  32280. function generateId() {
  32281. return 'three_default_' + ( count ++ );
  32282. }
  32283. function isEmpty( object ) {
  32284. return Object.keys( object ).length === 0;
  32285. }
  32286. // asset
  32287. function parseAsset( xml ) {
  32288. return {
  32289. unit: parseAssetUnit( getElementsByTagName( xml, 'unit' )[ 0 ] ),
  32290. upAxis: parseAssetUpAxis( getElementsByTagName( xml, 'up_axis' )[ 0 ] )
  32291. };
  32292. }
  32293. function parseAssetUnit( xml ) {
  32294. if ( ( xml !== undefined ) && ( xml.hasAttribute( 'meter' ) === true ) ) {
  32295. return parseFloat( xml.getAttribute( 'meter' ) );
  32296. } else {
  32297. return 1; // default 1 meter
  32298. }
  32299. }
  32300. function parseAssetUpAxis( xml ) {
  32301. return xml !== undefined ? xml.textContent : 'Y_UP';
  32302. }
  32303. // library
  32304. function parseLibrary( xml, libraryName, nodeName, parser ) {
  32305. var library = getElementsByTagName( xml, libraryName )[ 0 ];
  32306. if ( library !== undefined ) {
  32307. var elements = getElementsByTagName( library, nodeName );
  32308. for ( var i = 0; i < elements.length; i ++ ) {
  32309. parser( elements[ i ] );
  32310. }
  32311. }
  32312. }
  32313. function buildLibrary( data, builder ) {
  32314. for ( var name in data ) {
  32315. var object = data[ name ];
  32316. object.build = builder( data[ name ] );
  32317. }
  32318. }
  32319. // get
  32320. function getBuild( data, builder ) {
  32321. if ( data.build !== undefined ) return data.build;
  32322. data.build = builder( data );
  32323. return data.build;
  32324. }
  32325. // animation
  32326. function parseAnimation( xml ) {
  32327. var data = {
  32328. sources: {},
  32329. samplers: {},
  32330. channels: {}
  32331. };
  32332. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32333. var child = xml.childNodes[ i ];
  32334. if ( child.nodeType !== 1 ) continue;
  32335. var id;
  32336. switch ( child.nodeName ) {
  32337. case 'source':
  32338. id = child.getAttribute( 'id' );
  32339. data.sources[ id ] = parseSource( child );
  32340. break;
  32341. case 'sampler':
  32342. id = child.getAttribute( 'id' );
  32343. data.samplers[ id ] = parseAnimationSampler( child );
  32344. break;
  32345. case 'channel':
  32346. id = child.getAttribute( 'target' );
  32347. data.channels[ id ] = parseAnimationChannel( child );
  32348. break;
  32349. default:
  32350. console.log( child );
  32351. }
  32352. }
  32353. library.animations[ xml.getAttribute( 'id' ) ] = data;
  32354. }
  32355. function parseAnimationSampler( xml ) {
  32356. var data = {
  32357. inputs: {},
  32358. };
  32359. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32360. var child = xml.childNodes[ i ];
  32361. if ( child.nodeType !== 1 ) continue;
  32362. switch ( child.nodeName ) {
  32363. case 'input':
  32364. var id = parseId( child.getAttribute( 'source' ) );
  32365. var semantic = child.getAttribute( 'semantic' );
  32366. data.inputs[ semantic ] = id;
  32367. break;
  32368. }
  32369. }
  32370. return data;
  32371. }
  32372. function parseAnimationChannel( xml ) {
  32373. var data = {};
  32374. var target = xml.getAttribute( 'target' );
  32375. // parsing SID Addressing Syntax
  32376. var parts = target.split( '/' );
  32377. var id = parts.shift();
  32378. var sid = parts.shift();
  32379. // check selection syntax
  32380. var arraySyntax = ( sid.indexOf( '(' ) !== - 1 );
  32381. var memberSyntax = ( sid.indexOf( '.' ) !== - 1 );
  32382. if ( memberSyntax ) {
  32383. // member selection access
  32384. parts = sid.split( '.' );
  32385. sid = parts.shift();
  32386. data.member = parts.shift();
  32387. } else if ( arraySyntax ) {
  32388. // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
  32389. var indices = sid.split( '(' );
  32390. sid = indices.shift();
  32391. for ( var i = 0; i < indices.length; i ++ ) {
  32392. indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) );
  32393. }
  32394. data.indices = indices;
  32395. }
  32396. data.id = id;
  32397. data.sid = sid;
  32398. data.arraySyntax = arraySyntax;
  32399. data.memberSyntax = memberSyntax;
  32400. data.sampler = parseId( xml.getAttribute( 'source' ) );
  32401. return data;
  32402. }
  32403. function buildAnimation( data ) {
  32404. var tracks = [];
  32405. var channels = data.channels;
  32406. var samplers = data.samplers;
  32407. var sources = data.sources;
  32408. for ( var target in channels ) {
  32409. if ( channels.hasOwnProperty( target ) ) {
  32410. var channel = channels[ target ];
  32411. var sampler = samplers[ channel.sampler ];
  32412. var inputId = sampler.inputs.INPUT;
  32413. var outputId = sampler.inputs.OUTPUT;
  32414. var inputSource = sources[ inputId ];
  32415. var outputSource = sources[ outputId ];
  32416. var animation = buildAnimationChannel( channel, inputSource, outputSource );
  32417. createKeyframeTracks( animation, tracks );
  32418. }
  32419. }
  32420. return tracks;
  32421. }
  32422. function getAnimation( id ) {
  32423. return getBuild( library.animations[ id ], buildAnimation );
  32424. }
  32425. function buildAnimationChannel( channel, inputSource, outputSource ) {
  32426. var node = library.nodes[ channel.id ];
  32427. var object3D = getNode( node.id );
  32428. var transform = node.transforms[ channel.sid ];
  32429. var defaultMatrix = node.matrix.clone().transpose();
  32430. var time, stride;
  32431. var i, il, j, jl;
  32432. var data = {};
  32433. // the collada spec allows the animation of data in various ways.
  32434. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic
  32435. switch ( transform ) {
  32436. case 'matrix':
  32437. for ( i = 0, il = inputSource.array.length; i < il; i ++ ) {
  32438. time = inputSource.array[ i ];
  32439. stride = i * outputSource.stride;
  32440. if ( data[ time ] === undefined ) data[ time ] = {};
  32441. if ( channel.arraySyntax === true ) {
  32442. var value = outputSource.array[ stride ];
  32443. var index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ];
  32444. data[ time ][ index ] = value;
  32445. } else {
  32446. for ( j = 0, jl = outputSource.stride; j < jl; j ++ ) {
  32447. data[ time ][ j ] = outputSource.array[ stride + j ];
  32448. }
  32449. }
  32450. }
  32451. break;
  32452. case 'translate':
  32453. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  32454. break;
  32455. case 'rotate':
  32456. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  32457. break;
  32458. case 'scale':
  32459. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  32460. break;
  32461. }
  32462. var keyframes = prepareAnimationData( data, defaultMatrix );
  32463. var animation = {
  32464. name: object3D.uuid,
  32465. keyframes: keyframes
  32466. };
  32467. return animation;
  32468. }
  32469. function prepareAnimationData( data, defaultMatrix ) {
  32470. var keyframes = [];
  32471. // transfer data into a sortable array
  32472. for ( var time in data ) {
  32473. keyframes.push( { time: parseFloat( time ), value: data[ time ] } );
  32474. }
  32475. // ensure keyframes are sorted by time
  32476. keyframes.sort( ascending );
  32477. // now we clean up all animation data, so we can use them for keyframe tracks
  32478. for ( var i = 0; i < 16; i ++ ) {
  32479. transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );
  32480. }
  32481. return keyframes;
  32482. // array sort function
  32483. function ascending( a, b ) {
  32484. return a.time - b.time;
  32485. }
  32486. }
  32487. var position = new THREE.Vector3();
  32488. var scale = new THREE.Vector3();
  32489. var quaternion = new THREE.Quaternion();
  32490. function createKeyframeTracks( animation, tracks ) {
  32491. var keyframes = animation.keyframes;
  32492. var name = animation.name;
  32493. var times = [];
  32494. var positionData = [];
  32495. var quaternionData = [];
  32496. var scaleData = [];
  32497. for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
  32498. var keyframe = keyframes[ i ];
  32499. var time = keyframe.time;
  32500. var value = keyframe.value;
  32501. matrix.fromArray( value ).transpose();
  32502. matrix.decompose( position, quaternion, scale );
  32503. times.push( time );
  32504. positionData.push( position.x, position.y, position.z );
  32505. quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  32506. scaleData.push( scale.x, scale.y, scale.z );
  32507. }
  32508. if ( positionData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.position', times, positionData ) );
  32509. if ( quaternionData.length > 0 ) tracks.push( new THREE.QuaternionKeyframeTrack( name + '.quaternion', times, quaternionData ) );
  32510. if ( scaleData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.scale', times, scaleData ) );
  32511. return tracks;
  32512. }
  32513. function transformAnimationData( keyframes, property, defaultValue ) {
  32514. var keyframe;
  32515. var empty = true;
  32516. var i, l;
  32517. // check, if values of a property are missing in our keyframes
  32518. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  32519. keyframe = keyframes[ i ];
  32520. if ( keyframe.value[ property ] === undefined ) {
  32521. keyframe.value[ property ] = null; // mark as missing
  32522. } else {
  32523. empty = false;
  32524. }
  32525. }
  32526. if ( empty === true ) {
  32527. // no values at all, so we set a default value
  32528. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  32529. keyframe = keyframes[ i ];
  32530. keyframe.value[ property ] = defaultValue;
  32531. }
  32532. } else {
  32533. // filling gaps
  32534. createMissingKeyframes( keyframes, property );
  32535. }
  32536. }
  32537. function createMissingKeyframes( keyframes, property ) {
  32538. var prev, next;
  32539. for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
  32540. var keyframe = keyframes[ i ];
  32541. if ( keyframe.value[ property ] === null ) {
  32542. prev = getPrev( keyframes, i, property );
  32543. next = getNext( keyframes, i, property );
  32544. if ( prev === null ) {
  32545. keyframe.value[ property ] = next.value[ property ];
  32546. continue;
  32547. }
  32548. if ( next === null ) {
  32549. keyframe.value[ property ] = prev.value[ property ];
  32550. continue;
  32551. }
  32552. interpolate( keyframe, prev, next, property );
  32553. }
  32554. }
  32555. }
  32556. function getPrev( keyframes, i, property ) {
  32557. while ( i >= 0 ) {
  32558. var keyframe = keyframes[ i ];
  32559. if ( keyframe.value[ property ] !== null ) return keyframe;
  32560. i --;
  32561. }
  32562. return null;
  32563. }
  32564. function getNext( keyframes, i, property ) {
  32565. while ( i < keyframes.length ) {
  32566. var keyframe = keyframes[ i ];
  32567. if ( keyframe.value[ property ] !== null ) return keyframe;
  32568. i ++;
  32569. }
  32570. return null;
  32571. }
  32572. function interpolate( key, prev, next, property ) {
  32573. if ( ( next.time - prev.time ) === 0 ) {
  32574. key.value[ property ] = prev.value[ property ];
  32575. return;
  32576. }
  32577. key.value[ property ] = ( ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) ) + prev.value[ property ];
  32578. }
  32579. // animation clips
  32580. function parseAnimationClip( xml ) {
  32581. var data = {
  32582. name: xml.getAttribute( 'id' ) || 'default',
  32583. start: parseFloat( xml.getAttribute( 'start' ) || 0 ),
  32584. end: parseFloat( xml.getAttribute( 'end' ) || 0 ),
  32585. animations: []
  32586. };
  32587. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32588. var child = xml.childNodes[ i ];
  32589. if ( child.nodeType !== 1 ) continue;
  32590. switch ( child.nodeName ) {
  32591. case 'instance_animation':
  32592. data.animations.push( parseId( child.getAttribute( 'url' ) ) );
  32593. break;
  32594. }
  32595. }
  32596. library.clips[ xml.getAttribute( 'id' ) ] = data;
  32597. }
  32598. function buildAnimationClip( data ) {
  32599. var tracks = [];
  32600. var name = data.name;
  32601. var duration = ( data.end - data.start ) || - 1;
  32602. var animations = data.animations;
  32603. for ( var i = 0, il = animations.length; i < il; i ++ ) {
  32604. var animationTracks = getAnimation( animations[ i ] );
  32605. for ( var j = 0, jl = animationTracks.length; j < jl; j ++ ) {
  32606. tracks.push( animationTracks[ j ] );
  32607. }
  32608. }
  32609. return new THREE.AnimationClip( name, duration, tracks );
  32610. }
  32611. function getAnimationClip( id ) {
  32612. return getBuild( library.clips[ id ], buildAnimationClip );
  32613. }
  32614. // controller
  32615. function parseController( xml ) {
  32616. var data = {};
  32617. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32618. var child = xml.childNodes[ i ];
  32619. if ( child.nodeType !== 1 ) continue;
  32620. switch ( child.nodeName ) {
  32621. case 'skin':
  32622. // there is exactly one skin per controller
  32623. data.id = parseId( child.getAttribute( 'source' ) );
  32624. data.skin = parseSkin( child );
  32625. break;
  32626. case 'morph':
  32627. data.id = parseId( child.getAttribute( 'source' ) );
  32628. console.warn( 'THREE.ColladaLoader: Morph target animation not supported yet.' );
  32629. break;
  32630. }
  32631. }
  32632. library.controllers[ xml.getAttribute( 'id' ) ] = data;
  32633. }
  32634. function parseSkin( xml ) {
  32635. var data = {
  32636. sources: {}
  32637. };
  32638. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32639. var child = xml.childNodes[ i ];
  32640. if ( child.nodeType !== 1 ) continue;
  32641. switch ( child.nodeName ) {
  32642. case 'bind_shape_matrix':
  32643. data.bindShapeMatrix = parseFloats( child.textContent );
  32644. break;
  32645. case 'source':
  32646. var id = child.getAttribute( 'id' );
  32647. data.sources[ id ] = parseSource( child );
  32648. break;
  32649. case 'joints':
  32650. data.joints = parseJoints( child );
  32651. break;
  32652. case 'vertex_weights':
  32653. data.vertexWeights = parseVertexWeights( child );
  32654. break;
  32655. }
  32656. }
  32657. return data;
  32658. }
  32659. function parseJoints( xml ) {
  32660. var data = {
  32661. inputs: {}
  32662. };
  32663. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32664. var child = xml.childNodes[ i ];
  32665. if ( child.nodeType !== 1 ) continue;
  32666. switch ( child.nodeName ) {
  32667. case 'input':
  32668. var semantic = child.getAttribute( 'semantic' );
  32669. var id = parseId( child.getAttribute( 'source' ) );
  32670. data.inputs[ semantic ] = id;
  32671. break;
  32672. }
  32673. }
  32674. return data;
  32675. }
  32676. function parseVertexWeights( xml ) {
  32677. var data = {
  32678. inputs: {}
  32679. };
  32680. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32681. var child = xml.childNodes[ i ];
  32682. if ( child.nodeType !== 1 ) continue;
  32683. switch ( child.nodeName ) {
  32684. case 'input':
  32685. var semantic = child.getAttribute( 'semantic' );
  32686. var id = parseId( child.getAttribute( 'source' ) );
  32687. var offset = parseInt( child.getAttribute( 'offset' ) );
  32688. data.inputs[ semantic ] = { id: id, offset: offset };
  32689. break;
  32690. case 'vcount':
  32691. data.vcount = parseInts( child.textContent );
  32692. break;
  32693. case 'v':
  32694. data.v = parseInts( child.textContent );
  32695. break;
  32696. }
  32697. }
  32698. return data;
  32699. }
  32700. function buildController( data ) {
  32701. var build = {
  32702. id: data.id
  32703. };
  32704. var geometry = library.geometries[ build.id ];
  32705. if ( data.skin !== undefined ) {
  32706. build.skin = buildSkin( data.skin );
  32707. // we enhance the 'sources' property of the corresponding geometry with our skin data
  32708. geometry.sources.skinIndices = build.skin.indices;
  32709. geometry.sources.skinWeights = build.skin.weights;
  32710. }
  32711. return build;
  32712. }
  32713. function buildSkin( data ) {
  32714. var BONE_LIMIT = 4;
  32715. var build = {
  32716. joints: [], // this must be an array to preserve the joint order
  32717. indices: {
  32718. array: [],
  32719. stride: BONE_LIMIT
  32720. },
  32721. weights: {
  32722. array: [],
  32723. stride: BONE_LIMIT
  32724. }
  32725. };
  32726. var sources = data.sources;
  32727. var vertexWeights = data.vertexWeights;
  32728. var vcount = vertexWeights.vcount;
  32729. var v = vertexWeights.v;
  32730. var jointOffset = vertexWeights.inputs.JOINT.offset;
  32731. var weightOffset = vertexWeights.inputs.WEIGHT.offset;
  32732. var jointSource = data.sources[ data.joints.inputs.JOINT ];
  32733. var inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
  32734. var weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
  32735. var stride = 0;
  32736. var i, j, l;
  32737. // procces skin data for each vertex
  32738. for ( i = 0, l = vcount.length; i < l; i ++ ) {
  32739. var jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
  32740. var vertexSkinData = [];
  32741. for ( j = 0; j < jointCount; j ++ ) {
  32742. var skinIndex = v[ stride + jointOffset ];
  32743. var weightId = v[ stride + weightOffset ];
  32744. var skinWeight = weights[ weightId ];
  32745. vertexSkinData.push( { index: skinIndex, weight: skinWeight } );
  32746. stride += 2;
  32747. }
  32748. // we sort the joints in descending order based on the weights.
  32749. // this ensures, we only procced the most important joints of the vertex
  32750. vertexSkinData.sort( descending );
  32751. // now we provide for each vertex a set of four index and weight values.
  32752. // the order of the skin data matches the order of vertices
  32753. for ( j = 0; j < BONE_LIMIT; j ++ ) {
  32754. var d = vertexSkinData[ j ];
  32755. if ( d !== undefined ) {
  32756. build.indices.array.push( d.index );
  32757. build.weights.array.push( d.weight );
  32758. } else {
  32759. build.indices.array.push( 0 );
  32760. build.weights.array.push( 0 );
  32761. }
  32762. }
  32763. }
  32764. // setup bind matrix
  32765. build.bindMatrix = new THREE.Matrix4().fromArray( data.bindShapeMatrix ).transpose();
  32766. // process bones and inverse bind matrix data
  32767. for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {
  32768. var name = jointSource.array[ i ];
  32769. var boneInverse = new THREE.Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
  32770. build.joints.push( { name: name, boneInverse: boneInverse } );
  32771. }
  32772. return build;
  32773. // array sort function
  32774. function descending( a, b ) {
  32775. return b.weight - a.weight;
  32776. }
  32777. }
  32778. function getController( id ) {
  32779. return getBuild( library.controllers[ id ], buildController );
  32780. }
  32781. // image
  32782. function parseImage( xml ) {
  32783. var data = {
  32784. init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent
  32785. };
  32786. library.images[ xml.getAttribute( 'id' ) ] = data;
  32787. }
  32788. function buildImage( data ) {
  32789. if ( data.build !== undefined ) return data.build;
  32790. return data.init_from;
  32791. }
  32792. function getImage( id ) {
  32793. var data = library.images[ id ];
  32794. if ( data !== undefined ) {
  32795. return getBuild( data, buildImage );
  32796. }
  32797. console.warn( 'THREE.ColladaLoader: Couldn\'t find image with ID:', id );
  32798. return null;
  32799. }
  32800. // effect
  32801. function parseEffect( xml ) {
  32802. var data = {};
  32803. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32804. var child = xml.childNodes[ i ];
  32805. if ( child.nodeType !== 1 ) continue;
  32806. switch ( child.nodeName ) {
  32807. case 'profile_COMMON':
  32808. data.profile = parseEffectProfileCOMMON( child );
  32809. break;
  32810. }
  32811. }
  32812. library.effects[ xml.getAttribute( 'id' ) ] = data;
  32813. }
  32814. function parseEffectProfileCOMMON( xml ) {
  32815. var data = {
  32816. surfaces: {},
  32817. samplers: {}
  32818. };
  32819. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32820. var child = xml.childNodes[ i ];
  32821. if ( child.nodeType !== 1 ) continue;
  32822. switch ( child.nodeName ) {
  32823. case 'newparam':
  32824. parseEffectNewparam( child, data );
  32825. break;
  32826. case 'technique':
  32827. data.technique = parseEffectTechnique( child );
  32828. break;
  32829. case 'extra':
  32830. data.extra = parseEffectExtra( child );
  32831. break;
  32832. }
  32833. }
  32834. return data;
  32835. }
  32836. function parseEffectNewparam( xml, data ) {
  32837. var sid = xml.getAttribute( 'sid' );
  32838. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32839. var child = xml.childNodes[ i ];
  32840. if ( child.nodeType !== 1 ) continue;
  32841. switch ( child.nodeName ) {
  32842. case 'surface':
  32843. data.surfaces[ sid ] = parseEffectSurface( child );
  32844. break;
  32845. case 'sampler2D':
  32846. data.samplers[ sid ] = parseEffectSampler( child );
  32847. break;
  32848. }
  32849. }
  32850. }
  32851. function parseEffectSurface( xml ) {
  32852. var data = {};
  32853. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32854. var child = xml.childNodes[ i ];
  32855. if ( child.nodeType !== 1 ) continue;
  32856. switch ( child.nodeName ) {
  32857. case 'init_from':
  32858. data.init_from = child.textContent;
  32859. break;
  32860. }
  32861. }
  32862. return data;
  32863. }
  32864. function parseEffectSampler( xml ) {
  32865. var data = {};
  32866. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32867. var child = xml.childNodes[ i ];
  32868. if ( child.nodeType !== 1 ) continue;
  32869. switch ( child.nodeName ) {
  32870. case 'source':
  32871. data.source = child.textContent;
  32872. break;
  32873. }
  32874. }
  32875. return data;
  32876. }
  32877. function parseEffectTechnique( xml ) {
  32878. var data = {};
  32879. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32880. var child = xml.childNodes[ i ];
  32881. if ( child.nodeType !== 1 ) continue;
  32882. switch ( child.nodeName ) {
  32883. case 'constant':
  32884. case 'lambert':
  32885. case 'blinn':
  32886. case 'phong':
  32887. data.type = child.nodeName;
  32888. data.parameters = parseEffectParameters( child );
  32889. break;
  32890. }
  32891. }
  32892. return data;
  32893. }
  32894. function parseEffectParameters( xml ) {
  32895. var data = {};
  32896. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32897. var child = xml.childNodes[ i ];
  32898. if ( child.nodeType !== 1 ) continue;
  32899. switch ( child.nodeName ) {
  32900. case 'emission':
  32901. case 'diffuse':
  32902. case 'specular':
  32903. case 'shininess':
  32904. case 'transparency':
  32905. data[ child.nodeName ] = parseEffectParameter( child );
  32906. break;
  32907. case 'transparent':
  32908. data[ child.nodeName ] = {
  32909. opaque: child.getAttribute( 'opaque' ),
  32910. data: parseEffectParameter( child )
  32911. };
  32912. break;
  32913. }
  32914. }
  32915. return data;
  32916. }
  32917. function parseEffectParameter( xml ) {
  32918. var data = {};
  32919. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32920. var child = xml.childNodes[ i ];
  32921. if ( child.nodeType !== 1 ) continue;
  32922. switch ( child.nodeName ) {
  32923. case 'color':
  32924. data[ child.nodeName ] = parseFloats( child.textContent );
  32925. break;
  32926. case 'float':
  32927. data[ child.nodeName ] = parseFloat( child.textContent );
  32928. break;
  32929. case 'texture':
  32930. data[ child.nodeName ] = { id: child.getAttribute( 'texture' ), extra: parseEffectParameterTexture( child ) };
  32931. break;
  32932. }
  32933. }
  32934. return data;
  32935. }
  32936. function parseEffectParameterTexture( xml ) {
  32937. var data = {
  32938. technique: {}
  32939. };
  32940. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32941. var child = xml.childNodes[ i ];
  32942. if ( child.nodeType !== 1 ) continue;
  32943. switch ( child.nodeName ) {
  32944. case 'extra':
  32945. parseEffectParameterTextureExtra( child, data );
  32946. break;
  32947. }
  32948. }
  32949. return data;
  32950. }
  32951. function parseEffectParameterTextureExtra( xml, data ) {
  32952. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32953. var child = xml.childNodes[ i ];
  32954. if ( child.nodeType !== 1 ) continue;
  32955. switch ( child.nodeName ) {
  32956. case 'technique':
  32957. parseEffectParameterTextureExtraTechnique( child, data );
  32958. break;
  32959. }
  32960. }
  32961. }
  32962. function parseEffectParameterTextureExtraTechnique( xml, data ) {
  32963. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32964. var child = xml.childNodes[ i ];
  32965. if ( child.nodeType !== 1 ) continue;
  32966. switch ( child.nodeName ) {
  32967. case 'repeatU':
  32968. case 'repeatV':
  32969. case 'offsetU':
  32970. case 'offsetV':
  32971. data.technique[ child.nodeName ] = parseFloat( child.textContent );
  32972. break;
  32973. case 'wrapU':
  32974. case 'wrapV':
  32975. // some files have values for wrapU/wrapV which become NaN via parseInt
  32976. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  32977. data.technique[ child.nodeName ] = 1;
  32978. } else if ( child.textContent.toUpperCase() === 'FALSE' ) {
  32979. data.technique[ child.nodeName ] = 0;
  32980. } else {
  32981. data.technique[ child.nodeName ] = parseInt( child.textContent );
  32982. }
  32983. break;
  32984. }
  32985. }
  32986. }
  32987. function parseEffectExtra( xml ) {
  32988. var data = {};
  32989. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32990. var child = xml.childNodes[ i ];
  32991. if ( child.nodeType !== 1 ) continue;
  32992. switch ( child.nodeName ) {
  32993. case 'technique':
  32994. data.technique = parseEffectExtraTechnique( child );
  32995. break;
  32996. }
  32997. }
  32998. return data;
  32999. }
  33000. function parseEffectExtraTechnique( xml ) {
  33001. var data = {};
  33002. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33003. var child = xml.childNodes[ i ];
  33004. if ( child.nodeType !== 1 ) continue;
  33005. switch ( child.nodeName ) {
  33006. case 'double_sided':
  33007. data[ child.nodeName ] = parseInt( child.textContent );
  33008. break;
  33009. }
  33010. }
  33011. return data;
  33012. }
  33013. function buildEffect( data ) {
  33014. return data;
  33015. }
  33016. function getEffect( id ) {
  33017. return getBuild( library.effects[ id ], buildEffect );
  33018. }
  33019. // material
  33020. function parseMaterial( xml ) {
  33021. var data = {
  33022. name: xml.getAttribute( 'name' )
  33023. };
  33024. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33025. var child = xml.childNodes[ i ];
  33026. if ( child.nodeType !== 1 ) continue;
  33027. switch ( child.nodeName ) {
  33028. case 'instance_effect':
  33029. data.url = parseId( child.getAttribute( 'url' ) );
  33030. break;
  33031. }
  33032. }
  33033. library.materials[ xml.getAttribute( 'id' ) ] = data;
  33034. }
  33035. function buildMaterial( data ) {
  33036. var effect = getEffect( data.url );
  33037. var technique = effect.profile.technique;
  33038. var extra = effect.profile.extra;
  33039. var material;
  33040. switch ( technique.type ) {
  33041. case 'phong':
  33042. case 'blinn':
  33043. material = new THREE.MeshPhongMaterial();
  33044. break;
  33045. case 'lambert':
  33046. material = new THREE.MeshLambertMaterial();
  33047. break;
  33048. default:
  33049. material = new THREE.MeshBasicMaterial();
  33050. break;
  33051. }
  33052. material.name = data.name;
  33053. function getTexture( textureObject ) {
  33054. var sampler = effect.profile.samplers[ textureObject.id ];
  33055. var image = null;
  33056. // get image
  33057. if ( sampler !== undefined ) {
  33058. var surface = effect.profile.surfaces[ sampler.source ];
  33059. image = getImage( surface.init_from );
  33060. } else {
  33061. console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
  33062. image = getImage( textureObject.id );
  33063. }
  33064. // create texture if image is avaiable
  33065. if ( image !== null ) {
  33066. var texture = textureLoader.load( image );
  33067. var extra = textureObject.extra;
  33068. if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
  33069. var technique = extra.technique;
  33070. texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  33071. texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  33072. texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
  33073. texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
  33074. } else {
  33075. texture.wrapS = THREE.RepeatWrapping;
  33076. texture.wrapT = THREE.RepeatWrapping;
  33077. }
  33078. return texture;
  33079. } else {
  33080. console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );
  33081. return null;
  33082. }
  33083. }
  33084. var parameters = technique.parameters;
  33085. for ( var key in parameters ) {
  33086. var parameter = parameters[ key ];
  33087. switch ( key ) {
  33088. case 'diffuse':
  33089. if ( parameter.color ) material.color.fromArray( parameter.color );
  33090. if ( parameter.texture ) material.map = getTexture( parameter.texture );
  33091. break;
  33092. case 'specular':
  33093. if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
  33094. if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
  33095. break;
  33096. case 'shininess':
  33097. if ( parameter.float && material.shininess ) material.shininess = parameter.float;
  33098. break;
  33099. case 'emission':
  33100. if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
  33101. if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture );
  33102. break;
  33103. }
  33104. }
  33105. //
  33106. var transparent = parameters[ 'transparent' ];
  33107. var transparency = parameters[ 'transparency' ];
  33108. // <transparency> does not exist but <transparent>
  33109. if ( transparency === undefined && transparent ) {
  33110. transparency = {
  33111. float: 1
  33112. };
  33113. }
  33114. // <transparent> does not exist but <transparency>
  33115. if ( transparent === undefined && transparency ) {
  33116. transparent = {
  33117. opaque: 'A_ONE',
  33118. data: {
  33119. color: [ 1, 1, 1, 1 ]
  33120. } };
  33121. }
  33122. if ( transparent && transparency ) {
  33123. // handle case if a texture exists but no color
  33124. if ( transparent.data.texture ) {
  33125. // we do not set an alpha map (see #13792)
  33126. material.transparent = true;
  33127. } else {
  33128. var color = transparent.data.color;
  33129. switch ( transparent.opaque ) {
  33130. case 'A_ONE':
  33131. material.opacity = color[ 3 ] * transparency.float;
  33132. break;
  33133. case 'RGB_ZERO':
  33134. material.opacity = 1 - ( color[ 0 ] * transparency.float );
  33135. break;
  33136. case 'A_ZERO':
  33137. material.opacity = 1 - ( color[ 3 ] * transparency.float );
  33138. break;
  33139. case 'RGB_ONE':
  33140. material.opacity = color[ 0 ] * transparency.float;
  33141. break;
  33142. default:
  33143. console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
  33144. }
  33145. if ( material.opacity < 1 ) material.transparent = true;
  33146. }
  33147. }
  33148. //
  33149. if ( extra !== undefined && extra.technique !== undefined && extra.technique.double_sided === 1 ) {
  33150. material.side = THREE.DoubleSide;
  33151. }
  33152. return material;
  33153. }
  33154. function getMaterial( id ) {
  33155. return getBuild( library.materials[ id ], buildMaterial );
  33156. }
  33157. // camera
  33158. function parseCamera( xml ) {
  33159. var data = {
  33160. name: xml.getAttribute( 'name' )
  33161. };
  33162. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33163. var child = xml.childNodes[ i ];
  33164. if ( child.nodeType !== 1 ) continue;
  33165. switch ( child.nodeName ) {
  33166. case 'optics':
  33167. data.optics = parseCameraOptics( child );
  33168. break;
  33169. }
  33170. }
  33171. library.cameras[ xml.getAttribute( 'id' ) ] = data;
  33172. }
  33173. function parseCameraOptics( xml ) {
  33174. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33175. var child = xml.childNodes[ i ];
  33176. switch ( child.nodeName ) {
  33177. case 'technique_common':
  33178. return parseCameraTechnique( child );
  33179. }
  33180. }
  33181. return {};
  33182. }
  33183. function parseCameraTechnique( xml ) {
  33184. var data = {};
  33185. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33186. var child = xml.childNodes[ i ];
  33187. switch ( child.nodeName ) {
  33188. case 'perspective':
  33189. case 'orthographic':
  33190. data.technique = child.nodeName;
  33191. data.parameters = parseCameraParameters( child );
  33192. break;
  33193. }
  33194. }
  33195. return data;
  33196. }
  33197. function parseCameraParameters( xml ) {
  33198. var data = {};
  33199. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33200. var child = xml.childNodes[ i ];
  33201. switch ( child.nodeName ) {
  33202. case 'xfov':
  33203. case 'yfov':
  33204. case 'xmag':
  33205. case 'ymag':
  33206. case 'znear':
  33207. case 'zfar':
  33208. case 'aspect_ratio':
  33209. data[ child.nodeName ] = parseFloat( child.textContent );
  33210. break;
  33211. }
  33212. }
  33213. return data;
  33214. }
  33215. function buildCamera( data ) {
  33216. var camera;
  33217. switch ( data.optics.technique ) {
  33218. case 'perspective':
  33219. camera = new THREE.PerspectiveCamera(
  33220. data.optics.parameters.yfov,
  33221. data.optics.parameters.aspect_ratio,
  33222. data.optics.parameters.znear,
  33223. data.optics.parameters.zfar
  33224. );
  33225. break;
  33226. case 'orthographic':
  33227. var ymag = data.optics.parameters.ymag;
  33228. var xmag = data.optics.parameters.xmag;
  33229. var aspectRatio = data.optics.parameters.aspect_ratio;
  33230. xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag;
  33231. ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag;
  33232. xmag *= 0.5;
  33233. ymag *= 0.5;
  33234. camera = new THREE.OrthographicCamera(
  33235. - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  33236. data.optics.parameters.znear,
  33237. data.optics.parameters.zfar
  33238. );
  33239. break;
  33240. default:
  33241. camera = new THREE.PerspectiveCamera();
  33242. break;
  33243. }
  33244. camera.name = data.name;
  33245. return camera;
  33246. }
  33247. function getCamera( id ) {
  33248. var data = library.cameras[ id ];
  33249. if ( data !== undefined ) {
  33250. return getBuild( data, buildCamera );
  33251. }
  33252. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  33253. return null;
  33254. }
  33255. // light
  33256. function parseLight( xml ) {
  33257. var data = {};
  33258. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33259. var child = xml.childNodes[ i ];
  33260. if ( child.nodeType !== 1 ) continue;
  33261. switch ( child.nodeName ) {
  33262. case 'technique_common':
  33263. data = parseLightTechnique( child );
  33264. break;
  33265. }
  33266. }
  33267. library.lights[ xml.getAttribute( 'id' ) ] = data;
  33268. }
  33269. function parseLightTechnique( xml ) {
  33270. var data = {};
  33271. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33272. var child = xml.childNodes[ i ];
  33273. if ( child.nodeType !== 1 ) continue;
  33274. switch ( child.nodeName ) {
  33275. case 'directional':
  33276. case 'point':
  33277. case 'spot':
  33278. case 'ambient':
  33279. data.technique = child.nodeName;
  33280. data.parameters = parseLightParameters( child );
  33281. }
  33282. }
  33283. return data;
  33284. }
  33285. function parseLightParameters( xml ) {
  33286. var data = {};
  33287. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33288. var child = xml.childNodes[ i ];
  33289. if ( child.nodeType !== 1 ) continue;
  33290. switch ( child.nodeName ) {
  33291. case 'color':
  33292. var array = parseFloats( child.textContent );
  33293. data.color = new THREE.Color().fromArray( array );
  33294. break;
  33295. case 'falloff_angle':
  33296. data.falloffAngle = parseFloat( child.textContent );
  33297. break;
  33298. case 'quadratic_attenuation':
  33299. var f = parseFloat( child.textContent );
  33300. data.distance = f ? Math.sqrt( 1 / f ) : 0;
  33301. break;
  33302. }
  33303. }
  33304. return data;
  33305. }
  33306. function buildLight( data ) {
  33307. var light;
  33308. switch ( data.technique ) {
  33309. case 'directional':
  33310. light = new THREE.DirectionalLight();
  33311. break;
  33312. case 'point':
  33313. light = new THREE.PointLight();
  33314. break;
  33315. case 'spot':
  33316. light = new THREE.SpotLight();
  33317. break;
  33318. case 'ambient':
  33319. light = new THREE.AmbientLight();
  33320. break;
  33321. }
  33322. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  33323. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  33324. return light;
  33325. }
  33326. function getLight( id ) {
  33327. var data = library.lights[ id ];
  33328. if ( data !== undefined ) {
  33329. return getBuild( data, buildLight );
  33330. }
  33331. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  33332. return null;
  33333. }
  33334. // geometry
  33335. function parseGeometry( xml ) {
  33336. var data = {
  33337. name: xml.getAttribute( 'name' ),
  33338. sources: {},
  33339. vertices: {},
  33340. primitives: []
  33341. };
  33342. var mesh = getElementsByTagName( xml, 'mesh' )[ 0 ];
  33343. // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
  33344. if ( mesh === undefined ) return;
  33345. for ( var i = 0; i < mesh.childNodes.length; i ++ ) {
  33346. var child = mesh.childNodes[ i ];
  33347. if ( child.nodeType !== 1 ) continue;
  33348. var id = child.getAttribute( 'id' );
  33349. switch ( child.nodeName ) {
  33350. case 'source':
  33351. data.sources[ id ] = parseSource( child );
  33352. break;
  33353. case 'vertices':
  33354. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  33355. data.vertices = parseGeometryVertices( child );
  33356. break;
  33357. case 'polygons':
  33358. console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
  33359. break;
  33360. case 'lines':
  33361. case 'linestrips':
  33362. case 'polylist':
  33363. case 'triangles':
  33364. data.primitives.push( parseGeometryPrimitive( child ) );
  33365. break;
  33366. default:
  33367. console.log( child );
  33368. }
  33369. }
  33370. library.geometries[ xml.getAttribute( 'id' ) ] = data;
  33371. }
  33372. function parseSource( xml ) {
  33373. var data = {
  33374. array: [],
  33375. stride: 3
  33376. };
  33377. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33378. var child = xml.childNodes[ i ];
  33379. if ( child.nodeType !== 1 ) continue;
  33380. switch ( child.nodeName ) {
  33381. case 'float_array':
  33382. data.array = parseFloats( child.textContent );
  33383. break;
  33384. case 'Name_array':
  33385. data.array = parseStrings( child.textContent );
  33386. break;
  33387. case 'technique_common':
  33388. var accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
  33389. if ( accessor !== undefined ) {
  33390. data.stride = parseInt( accessor.getAttribute( 'stride' ) );
  33391. }
  33392. break;
  33393. }
  33394. }
  33395. return data;
  33396. }
  33397. function parseGeometryVertices( xml ) {
  33398. var data = {};
  33399. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33400. var child = xml.childNodes[ i ];
  33401. if ( child.nodeType !== 1 ) continue;
  33402. data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
  33403. }
  33404. return data;
  33405. }
  33406. function parseGeometryPrimitive( xml ) {
  33407. var primitive = {
  33408. type: xml.nodeName,
  33409. material: xml.getAttribute( 'material' ),
  33410. count: parseInt( xml.getAttribute( 'count' ) ),
  33411. inputs: {},
  33412. stride: 0,
  33413. hasUV: false
  33414. };
  33415. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33416. var child = xml.childNodes[ i ];
  33417. if ( child.nodeType !== 1 ) continue;
  33418. switch ( child.nodeName ) {
  33419. case 'input':
  33420. var id = parseId( child.getAttribute( 'source' ) );
  33421. var semantic = child.getAttribute( 'semantic' );
  33422. var offset = parseInt( child.getAttribute( 'offset' ) );
  33423. primitive.inputs[ semantic ] = { id: id, offset: offset };
  33424. primitive.stride = Math.max( primitive.stride, offset + 1 );
  33425. if ( semantic === 'TEXCOORD' ) primitive.hasUV = true;
  33426. break;
  33427. case 'vcount':
  33428. primitive.vcount = parseInts( child.textContent );
  33429. break;
  33430. case 'p':
  33431. primitive.p = parseInts( child.textContent );
  33432. break;
  33433. }
  33434. }
  33435. return primitive;
  33436. }
  33437. function groupPrimitives( primitives ) {
  33438. var build = {};
  33439. for ( var i = 0; i < primitives.length; i ++ ) {
  33440. var primitive = primitives[ i ];
  33441. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  33442. build[ primitive.type ].push( primitive );
  33443. }
  33444. return build;
  33445. }
  33446. function checkUVCoordinates( primitives ) {
  33447. var count = 0;
  33448. for ( var i = 0, l = primitives.length; i < l; i ++ ) {
  33449. var primitive = primitives[ i ];
  33450. if ( primitive.hasUV === true ) {
  33451. count ++;
  33452. }
  33453. }
  33454. if ( count > 0 && count < primitives.length ) {
  33455. primitives.uvsNeedsFix = true;
  33456. }
  33457. }
  33458. function buildGeometry( data ) {
  33459. var build = {};
  33460. var sources = data.sources;
  33461. var vertices = data.vertices;
  33462. var primitives = data.primitives;
  33463. if ( primitives.length === 0 ) return {};
  33464. // our goal is to create one buffer geometry for a single type of primitives
  33465. // first, we group all primitives by their type
  33466. var groupedPrimitives = groupPrimitives( primitives );
  33467. for ( var type in groupedPrimitives ) {
  33468. var primitiveType = groupedPrimitives[ type ];
  33469. // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  33470. checkUVCoordinates( primitiveType );
  33471. // third, create a buffer geometry for each type of primitives
  33472. build[ type ] = buildGeometryType( primitiveType, sources, vertices );
  33473. }
  33474. return build;
  33475. }
  33476. function buildGeometryType( primitives, sources, vertices ) {
  33477. var build = {};
  33478. var position = { array: [], stride: 0 };
  33479. var normal = { array: [], stride: 0 };
  33480. var uv = { array: [], stride: 0 };
  33481. var color = { array: [], stride: 0 };
  33482. var skinIndex = { array: [], stride: 4 };
  33483. var skinWeight = { array: [], stride: 4 };
  33484. var geometry = new THREE.BufferGeometry();
  33485. var materialKeys = [];
  33486. var start = 0;
  33487. for ( var p = 0; p < primitives.length; p ++ ) {
  33488. var primitive = primitives[ p ];
  33489. var inputs = primitive.inputs;
  33490. // groups
  33491. var count = 0;
  33492. switch ( primitive.type ) {
  33493. case 'lines':
  33494. case 'linestrips':
  33495. count = primitive.count * 2;
  33496. break;
  33497. case 'triangles':
  33498. count = primitive.count * 3;
  33499. break;
  33500. case 'polylist':
  33501. for ( var g = 0; g < primitive.count; g ++ ) {
  33502. var vc = primitive.vcount[ g ];
  33503. switch ( vc ) {
  33504. case 3:
  33505. count += 3; // single triangle
  33506. break;
  33507. case 4:
  33508. count += 6; // quad, subdivided into two triangles
  33509. break;
  33510. default:
  33511. count += ( vc - 2 ) * 3; // polylist with more than four vertices
  33512. break;
  33513. }
  33514. }
  33515. break;
  33516. default:
  33517. console.warn( 'THREE.ColladaLoader: Unknow primitive type:', primitive.type );
  33518. }
  33519. geometry.addGroup( start, count, p );
  33520. start += count;
  33521. // material
  33522. if ( primitive.material ) {
  33523. materialKeys.push( primitive.material );
  33524. }
  33525. // geometry data
  33526. for ( var name in inputs ) {
  33527. var input = inputs[ name ];
  33528. switch ( name ) {
  33529. case 'VERTEX':
  33530. for ( var key in vertices ) {
  33531. var id = vertices[ key ];
  33532. switch ( key ) {
  33533. case 'POSITION':
  33534. var prevLength = position.array.length;
  33535. buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  33536. position.stride = sources[ id ].stride;
  33537. if ( sources.skinWeights && sources.skinIndices ) {
  33538. buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  33539. buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  33540. }
  33541. // see #3803
  33542. if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
  33543. var count = ( position.array.length - prevLength ) / position.stride;
  33544. for ( var i = 0; i < count; i ++ ) {
  33545. // fill missing uv coordinates
  33546. uv.array.push( 0, 0 );
  33547. }
  33548. }
  33549. break;
  33550. case 'NORMAL':
  33551. buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  33552. normal.stride = sources[ id ].stride;
  33553. break;
  33554. case 'COLOR':
  33555. buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  33556. color.stride = sources[ id ].stride;
  33557. break;
  33558. case 'TEXCOORD':
  33559. buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  33560. uv.stride = sources[ id ].stride;
  33561. break;
  33562. default:
  33563. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  33564. }
  33565. }
  33566. break;
  33567. case 'NORMAL':
  33568. buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  33569. normal.stride = sources[ input.id ].stride;
  33570. break;
  33571. case 'COLOR':
  33572. buildGeometryData( primitive, sources[ input.id ], input.offset, color.array );
  33573. color.stride = sources[ input.id ].stride;
  33574. break;
  33575. case 'TEXCOORD':
  33576. buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  33577. uv.stride = sources[ input.id ].stride;
  33578. break;
  33579. }
  33580. }
  33581. }
  33582. // build geometry
  33583. if ( position.array.length > 0 ) geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( position.array, position.stride ) );
  33584. if ( normal.array.length > 0 ) geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normal.array, normal.stride ) );
  33585. if ( color.array.length > 0 ) geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( color.array, color.stride ) );
  33586. if ( uv.array.length > 0 ) geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( uv.array, uv.stride ) );
  33587. if ( skinIndex.array.length > 0 ) geometry.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  33588. if ( skinWeight.array.length > 0 ) geometry.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  33589. build.data = geometry;
  33590. build.type = primitives[ 0 ].type;
  33591. build.materialKeys = materialKeys;
  33592. return build;
  33593. }
  33594. function buildGeometryData( primitive, source, offset, array ) {
  33595. var indices = primitive.p;
  33596. var stride = primitive.stride;
  33597. var vcount = primitive.vcount;
  33598. function pushVector( i ) {
  33599. var index = indices[ i + offset ] * sourceStride;
  33600. var length = index + sourceStride;
  33601. for ( ; index < length; index ++ ) {
  33602. array.push( sourceArray[ index ] );
  33603. }
  33604. }
  33605. var sourceArray = source.array;
  33606. var sourceStride = source.stride;
  33607. if ( primitive.vcount !== undefined ) {
  33608. var index = 0;
  33609. for ( var i = 0, l = vcount.length; i < l; i ++ ) {
  33610. var count = vcount[ i ];
  33611. if ( count === 4 ) {
  33612. var a = index + stride * 0;
  33613. var b = index + stride * 1;
  33614. var c = index + stride * 2;
  33615. var d = index + stride * 3;
  33616. pushVector( a ); pushVector( b ); pushVector( d );
  33617. pushVector( b ); pushVector( c ); pushVector( d );
  33618. } else if ( count === 3 ) {
  33619. var a = index + stride * 0;
  33620. var b = index + stride * 1;
  33621. var c = index + stride * 2;
  33622. pushVector( a ); pushVector( b ); pushVector( c );
  33623. } else if ( count > 4 ) {
  33624. for ( var k = 1, kl = ( count - 2 ); k <= kl; k ++ ) {
  33625. var a = index + stride * 0;
  33626. var b = index + stride * k;
  33627. var c = index + stride * ( k + 1 );
  33628. pushVector( a ); pushVector( b ); pushVector( c );
  33629. }
  33630. }
  33631. index += stride * count;
  33632. }
  33633. } else {
  33634. for ( var i = 0, l = indices.length; i < l; i += stride ) {
  33635. pushVector( i );
  33636. }
  33637. }
  33638. }
  33639. function getGeometry( id ) {
  33640. return getBuild( library.geometries[ id ], buildGeometry );
  33641. }
  33642. // kinematics
  33643. function parseKinematicsModel( xml ) {
  33644. var data = {
  33645. name: xml.getAttribute( 'name' ) || '',
  33646. joints: {},
  33647. links: []
  33648. };
  33649. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33650. var child = xml.childNodes[ i ];
  33651. if ( child.nodeType !== 1 ) continue;
  33652. switch ( child.nodeName ) {
  33653. case 'technique_common':
  33654. parseKinematicsTechniqueCommon( child, data );
  33655. break;
  33656. }
  33657. }
  33658. library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
  33659. }
  33660. function buildKinematicsModel( data ) {
  33661. if ( data.build !== undefined ) return data.build;
  33662. return data;
  33663. }
  33664. function getKinematicsModel( id ) {
  33665. return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
  33666. }
  33667. function parseKinematicsTechniqueCommon( xml, data ) {
  33668. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33669. var child = xml.childNodes[ i ];
  33670. if ( child.nodeType !== 1 ) continue;
  33671. switch ( child.nodeName ) {
  33672. case 'joint':
  33673. data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
  33674. break;
  33675. case 'link':
  33676. data.links.push( parseKinematicsLink( child ) );
  33677. break;
  33678. }
  33679. }
  33680. }
  33681. function parseKinematicsJoint( xml ) {
  33682. var data;
  33683. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33684. var child = xml.childNodes[ i ];
  33685. if ( child.nodeType !== 1 ) continue;
  33686. switch ( child.nodeName ) {
  33687. case 'prismatic':
  33688. case 'revolute':
  33689. data = parseKinematicsJointParameter( child );
  33690. break;
  33691. }
  33692. }
  33693. return data;
  33694. }
  33695. function parseKinematicsJointParameter( xml, data ) {
  33696. var data = {
  33697. sid: xml.getAttribute( 'sid' ),
  33698. name: xml.getAttribute( 'name' ) || '',
  33699. axis: new THREE.Vector3(),
  33700. limits: {
  33701. min: 0,
  33702. max: 0
  33703. },
  33704. type: xml.nodeName,
  33705. static: false,
  33706. zeroPosition: 0,
  33707. middlePosition: 0
  33708. };
  33709. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33710. var child = xml.childNodes[ i ];
  33711. if ( child.nodeType !== 1 ) continue;
  33712. switch ( child.nodeName ) {
  33713. case 'axis':
  33714. var array = parseFloats( child.textContent );
  33715. data.axis.fromArray( array );
  33716. break;
  33717. case 'limits':
  33718. var max = child.getElementsByTagName( 'max' )[ 0 ];
  33719. var min = child.getElementsByTagName( 'min' )[ 0 ];
  33720. data.limits.max = parseFloat( max.textContent );
  33721. data.limits.min = parseFloat( min.textContent );
  33722. break;
  33723. }
  33724. }
  33725. // if min is equal to or greater than max, consider the joint static
  33726. if ( data.limits.min >= data.limits.max ) {
  33727. data.static = true;
  33728. }
  33729. // calculate middle position
  33730. data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
  33731. return data;
  33732. }
  33733. function parseKinematicsLink( xml ) {
  33734. var data = {
  33735. sid: xml.getAttribute( 'sid' ),
  33736. name: xml.getAttribute( 'name' ) || '',
  33737. attachments: [],
  33738. transforms: []
  33739. };
  33740. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33741. var child = xml.childNodes[ i ];
  33742. if ( child.nodeType !== 1 ) continue;
  33743. switch ( child.nodeName ) {
  33744. case 'attachment_full':
  33745. data.attachments.push( parseKinematicsAttachment( child ) );
  33746. break;
  33747. case 'matrix':
  33748. case 'translate':
  33749. case 'rotate':
  33750. data.transforms.push( parseKinematicsTransform( child ) );
  33751. break;
  33752. }
  33753. }
  33754. return data;
  33755. }
  33756. function parseKinematicsAttachment( xml ) {
  33757. var data = {
  33758. joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
  33759. transforms: [],
  33760. links: []
  33761. };
  33762. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33763. var child = xml.childNodes[ i ];
  33764. if ( child.nodeType !== 1 ) continue;
  33765. switch ( child.nodeName ) {
  33766. case 'link':
  33767. data.links.push( parseKinematicsLink( child ) );
  33768. break;
  33769. case 'matrix':
  33770. case 'translate':
  33771. case 'rotate':
  33772. data.transforms.push( parseKinematicsTransform( child ) );
  33773. break;
  33774. }
  33775. }
  33776. return data;
  33777. }
  33778. function parseKinematicsTransform( xml ) {
  33779. var data = {
  33780. type: xml.nodeName
  33781. };
  33782. var array = parseFloats( xml.textContent );
  33783. switch ( data.type ) {
  33784. case 'matrix':
  33785. data.obj = new THREE.Matrix4();
  33786. data.obj.fromArray( array ).transpose();
  33787. break;
  33788. case 'translate':
  33789. data.obj = new THREE.Vector3();
  33790. data.obj.fromArray( array );
  33791. break;
  33792. case 'rotate':
  33793. data.obj = new THREE.Vector3();
  33794. data.obj.fromArray( array );
  33795. data.angle = THREE.Math.degToRad( array[ 3 ] );
  33796. break;
  33797. }
  33798. return data;
  33799. }
  33800. function parseKinematicsScene( xml ) {
  33801. var data = {
  33802. bindJointAxis: []
  33803. };
  33804. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33805. var child = xml.childNodes[ i ];
  33806. if ( child.nodeType !== 1 ) continue;
  33807. switch ( child.nodeName ) {
  33808. case 'bind_joint_axis':
  33809. data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
  33810. break;
  33811. }
  33812. }
  33813. library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
  33814. }
  33815. function parseKinematicsBindJointAxis( xml ) {
  33816. var data = {
  33817. target: xml.getAttribute( 'target' ).split( '/' ).pop()
  33818. };
  33819. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33820. var child = xml.childNodes[ i ];
  33821. if ( child.nodeType !== 1 ) continue;
  33822. switch ( child.nodeName ) {
  33823. case 'axis':
  33824. var param = child.getElementsByTagName( 'param' )[ 0 ];
  33825. data.axis = param.textContent;
  33826. var tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
  33827. data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 );
  33828. break;
  33829. }
  33830. }
  33831. return data;
  33832. }
  33833. function buildKinematicsScene( data ) {
  33834. if ( data.build !== undefined ) return data.build;
  33835. return data;
  33836. }
  33837. function getKinematicsScene( id ) {
  33838. return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
  33839. }
  33840. function setupKinematics() {
  33841. var kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
  33842. var kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
  33843. var visualSceneId = Object.keys( library.visualScenes )[ 0 ];
  33844. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  33845. var kinematicsModel = getKinematicsModel( kinematicsModelId );
  33846. var kinematicsScene = getKinematicsScene( kinematicsSceneId );
  33847. var visualScene = getVisualScene( visualSceneId );
  33848. var bindJointAxis = kinematicsScene.bindJointAxis;
  33849. var jointMap = {};
  33850. for ( var i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  33851. var axis = bindJointAxis[ i ];
  33852. // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  33853. var targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  33854. if ( targetElement ) {
  33855. // get the parent of the transfrom element
  33856. var parentVisualElement = targetElement.parentElement;
  33857. // connect the joint of the kinematics model with the element in the visual scene
  33858. connect( axis.jointIndex, parentVisualElement );
  33859. }
  33860. }
  33861. function connect( jointIndex, visualElement ) {
  33862. var visualElementName = visualElement.getAttribute( 'name' );
  33863. var joint = kinematicsModel.joints[ jointIndex ];
  33864. visualScene.traverse( function ( object ) {
  33865. if ( object.name === visualElementName ) {
  33866. jointMap[ jointIndex ] = {
  33867. object: object,
  33868. transforms: buildTransformList( visualElement ),
  33869. joint: joint,
  33870. position: joint.zeroPosition
  33871. };
  33872. }
  33873. } );
  33874. }
  33875. var m0 = new THREE.Matrix4();
  33876. kinematics = {
  33877. joints: kinematicsModel && kinematicsModel.joints,
  33878. getJointValue: function ( jointIndex ) {
  33879. var jointData = jointMap[ jointIndex ];
  33880. if ( jointData ) {
  33881. return jointData.position;
  33882. } else {
  33883. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  33884. }
  33885. },
  33886. setJointValue: function ( jointIndex, value ) {
  33887. var jointData = jointMap[ jointIndex ];
  33888. if ( jointData ) {
  33889. var joint = jointData.joint;
  33890. if ( value > joint.limits.max || value < joint.limits.min ) {
  33891. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  33892. } else if ( joint.static ) {
  33893. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  33894. } else {
  33895. var object = jointData.object;
  33896. var axis = joint.axis;
  33897. var transforms = jointData.transforms;
  33898. matrix.identity();
  33899. // each update, we have to apply all transforms in the correct order
  33900. for ( var i = 0; i < transforms.length; i ++ ) {
  33901. var transform = transforms[ i ];
  33902. // if there is a connection of the transform node with a joint, apply the joint value
  33903. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  33904. switch ( joint.type ) {
  33905. case 'revolute':
  33906. matrix.multiply( m0.makeRotationAxis( axis, THREE.Math.degToRad( value ) ) );
  33907. break;
  33908. case 'prismatic':
  33909. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  33910. break;
  33911. default:
  33912. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  33913. break;
  33914. }
  33915. } else {
  33916. switch ( transform.type ) {
  33917. case 'matrix':
  33918. matrix.multiply( transform.obj );
  33919. break;
  33920. case 'translate':
  33921. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  33922. break;
  33923. case 'scale':
  33924. matrix.scale( transform.obj );
  33925. break;
  33926. case 'rotate':
  33927. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  33928. break;
  33929. }
  33930. }
  33931. }
  33932. object.matrix.copy( matrix );
  33933. object.matrix.decompose( object.position, object.quaternion, object.scale );
  33934. jointMap[ jointIndex ].position = value;
  33935. }
  33936. } else {
  33937. console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
  33938. }
  33939. }
  33940. };
  33941. }
  33942. function buildTransformList( node ) {
  33943. var transforms = [];
  33944. var xml = collada.querySelector( '[id="' + node.id + '"]' );
  33945. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33946. var child = xml.childNodes[ i ];
  33947. if ( child.nodeType !== 1 ) continue;
  33948. switch ( child.nodeName ) {
  33949. case 'matrix':
  33950. var array = parseFloats( child.textContent );
  33951. var matrix = new THREE.Matrix4().fromArray( array ).transpose();
  33952. transforms.push( {
  33953. sid: child.getAttribute( 'sid' ),
  33954. type: child.nodeName,
  33955. obj: matrix
  33956. } );
  33957. break;
  33958. case 'translate':
  33959. case 'scale':
  33960. var array = parseFloats( child.textContent );
  33961. var vector = new THREE.Vector3().fromArray( array );
  33962. transforms.push( {
  33963. sid: child.getAttribute( 'sid' ),
  33964. type: child.nodeName,
  33965. obj: vector
  33966. } );
  33967. break;
  33968. case 'rotate':
  33969. var array = parseFloats( child.textContent );
  33970. var vector = new THREE.Vector3().fromArray( array );
  33971. var angle = THREE.Math.degToRad( array[ 3 ] );
  33972. transforms.push( {
  33973. sid: child.getAttribute( 'sid' ),
  33974. type: child.nodeName,
  33975. obj: vector,
  33976. angle: angle
  33977. } );
  33978. break;
  33979. }
  33980. }
  33981. return transforms;
  33982. }
  33983. // nodes
  33984. function prepareNodes( xml ) {
  33985. var elements = xml.getElementsByTagName( 'node' );
  33986. // ensure all node elements have id attributes
  33987. for ( var i = 0; i < elements.length; i ++ ) {
  33988. var element = elements[ i ];
  33989. if ( element.hasAttribute( 'id' ) === false ) {
  33990. element.setAttribute( 'id', generateId() );
  33991. }
  33992. }
  33993. }
  33994. var matrix = new THREE.Matrix4();
  33995. var vector = new THREE.Vector3();
  33996. function parseNode( xml ) {
  33997. var data = {
  33998. name: xml.getAttribute( 'name' ) || '',
  33999. type: xml.getAttribute( 'type' ),
  34000. id: xml.getAttribute( 'id' ),
  34001. sid: xml.getAttribute( 'sid' ),
  34002. matrix: new THREE.Matrix4(),
  34003. nodes: [],
  34004. instanceCameras: [],
  34005. instanceControllers: [],
  34006. instanceLights: [],
  34007. instanceGeometries: [],
  34008. instanceNodes: [],
  34009. transforms: {}
  34010. };
  34011. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34012. var child = xml.childNodes[ i ];
  34013. if ( child.nodeType !== 1 ) continue;
  34014. switch ( child.nodeName ) {
  34015. case 'node':
  34016. data.nodes.push( child.getAttribute( 'id' ) );
  34017. parseNode( child );
  34018. break;
  34019. case 'instance_camera':
  34020. data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
  34021. break;
  34022. case 'instance_controller':
  34023. data.instanceControllers.push( parseNodeInstance( child ) );
  34024. break;
  34025. case 'instance_light':
  34026. data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
  34027. break;
  34028. case 'instance_geometry':
  34029. data.instanceGeometries.push( parseNodeInstance( child ) );
  34030. break;
  34031. case 'instance_node':
  34032. data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
  34033. break;
  34034. case 'matrix':
  34035. var array = parseFloats( child.textContent );
  34036. data.matrix.multiply( matrix.fromArray( array ).transpose() );
  34037. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34038. break;
  34039. case 'translate':
  34040. var array = parseFloats( child.textContent );
  34041. vector.fromArray( array );
  34042. data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
  34043. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34044. break;
  34045. case 'rotate':
  34046. var array = parseFloats( child.textContent );
  34047. var angle = THREE.Math.degToRad( array[ 3 ] );
  34048. data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
  34049. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34050. break;
  34051. case 'scale':
  34052. var array = parseFloats( child.textContent );
  34053. data.matrix.scale( vector.fromArray( array ) );
  34054. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34055. break;
  34056. case 'extra':
  34057. break;
  34058. default:
  34059. console.log( child );
  34060. }
  34061. }
  34062. library.nodes[ data.id ] = data;
  34063. return data;
  34064. }
  34065. function parseNodeInstance( xml ) {
  34066. var data = {
  34067. id: parseId( xml.getAttribute( 'url' ) ),
  34068. materials: {},
  34069. skeletons: []
  34070. };
  34071. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34072. var child = xml.childNodes[ i ];
  34073. switch ( child.nodeName ) {
  34074. case 'bind_material':
  34075. var instances = child.getElementsByTagName( 'instance_material' );
  34076. for ( var j = 0; j < instances.length; j ++ ) {
  34077. var instance = instances[ j ];
  34078. var symbol = instance.getAttribute( 'symbol' );
  34079. var target = instance.getAttribute( 'target' );
  34080. data.materials[ symbol ] = parseId( target );
  34081. }
  34082. break;
  34083. case 'skeleton':
  34084. data.skeletons.push( parseId( child.textContent ) );
  34085. break;
  34086. default:
  34087. break;
  34088. }
  34089. }
  34090. return data;
  34091. }
  34092. function buildSkeleton( skeletons, joints ) {
  34093. var boneData = [];
  34094. var sortedBoneData = [];
  34095. var i, j, data;
  34096. // a skeleton can have multiple root bones. collada expresses this
  34097. // situtation with multiple "skeleton" tags per controller instance
  34098. for ( i = 0; i < skeletons.length; i ++ ) {
  34099. var skeleton = skeletons[ i ];
  34100. var root;
  34101. if ( hasNode( skeleton ) ) {
  34102. root = getNode( skeleton );
  34103. buildBoneHierarchy( root, joints, boneData );
  34104. } else if ( hasVisualScene( skeleton ) ) {
  34105. // handle case where the skeleton refers to the visual scene (#13335)
  34106. var visualScene = library.visualScenes[ skeleton ];
  34107. var children = visualScene.children;
  34108. for ( var j = 0; j < children.length; j ++ ) {
  34109. var child = children[ j ];
  34110. if ( child.type === 'JOINT' ) {
  34111. var root = getNode( child.id );
  34112. buildBoneHierarchy( root, joints, boneData );
  34113. }
  34114. }
  34115. } else {
  34116. console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
  34117. }
  34118. }
  34119. // sort bone data (the order is defined in the corresponding controller)
  34120. for ( i = 0; i < joints.length; i ++ ) {
  34121. for ( j = 0; j < boneData.length; j ++ ) {
  34122. data = boneData[ j ];
  34123. if ( data.bone.name === joints[ i ].name ) {
  34124. sortedBoneData[ i ] = data;
  34125. data.processed = true;
  34126. break;
  34127. }
  34128. }
  34129. }
  34130. // add unprocessed bone data at the end of the list
  34131. for ( i = 0; i < boneData.length; i ++ ) {
  34132. data = boneData[ i ];
  34133. if ( data.processed === false ) {
  34134. sortedBoneData.push( data );
  34135. data.processed = true;
  34136. }
  34137. }
  34138. // setup arrays for skeleton creation
  34139. var bones = [];
  34140. var boneInverses = [];
  34141. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  34142. data = sortedBoneData[ i ];
  34143. bones.push( data.bone );
  34144. boneInverses.push( data.boneInverse );
  34145. }
  34146. return new THREE.Skeleton( bones, boneInverses );
  34147. }
  34148. function buildBoneHierarchy( root, joints, boneData ) {
  34149. // setup bone data from visual scene
  34150. root.traverse( function ( object ) {
  34151. if ( object.isBone === true ) {
  34152. var boneInverse;
  34153. // retrieve the boneInverse from the controller data
  34154. for ( var i = 0; i < joints.length; i ++ ) {
  34155. var joint = joints[ i ];
  34156. if ( joint.name === object.name ) {
  34157. boneInverse = joint.boneInverse;
  34158. break;
  34159. }
  34160. }
  34161. if ( boneInverse === undefined ) {
  34162. // Unfortunately, there can be joints in the visual scene that are not part of the
  34163. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  34164. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  34165. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  34166. // ensure a correct animation of the model.
  34167. boneInverse = new THREE.Matrix4();
  34168. }
  34169. boneData.push( { bone: object, boneInverse: boneInverse, processed: false } );
  34170. }
  34171. } );
  34172. }
  34173. function buildNode( data ) {
  34174. var objects = [];
  34175. var matrix = data.matrix;
  34176. var nodes = data.nodes;
  34177. var type = data.type;
  34178. var instanceCameras = data.instanceCameras;
  34179. var instanceControllers = data.instanceControllers;
  34180. var instanceLights = data.instanceLights;
  34181. var instanceGeometries = data.instanceGeometries;
  34182. var instanceNodes = data.instanceNodes;
  34183. // nodes
  34184. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  34185. objects.push( getNode( nodes[ i ] ) );
  34186. }
  34187. // instance cameras
  34188. for ( var i = 0, l = instanceCameras.length; i < l; i ++ ) {
  34189. var instanceCamera = getCamera( instanceCameras[ i ] );
  34190. if ( instanceCamera !== null ) {
  34191. objects.push( instanceCamera.clone() );
  34192. }
  34193. }
  34194. // instance controllers
  34195. for ( var i = 0, l = instanceControllers.length; i < l; i ++ ) {
  34196. var instance = instanceControllers[ i ];
  34197. var controller = getController( instance.id );
  34198. var geometries = getGeometry( controller.id );
  34199. var newObjects = buildObjects( geometries, instance.materials );
  34200. var skeletons = instance.skeletons;
  34201. var joints = controller.skin.joints;
  34202. var skeleton = buildSkeleton( skeletons, joints );
  34203. for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
  34204. var object = newObjects[ j ];
  34205. if ( object.isSkinnedMesh ) {
  34206. object.bind( skeleton, controller.skin.bindMatrix );
  34207. object.normalizeSkinWeights();
  34208. }
  34209. objects.push( object );
  34210. }
  34211. }
  34212. // instance lights
  34213. for ( var i = 0, l = instanceLights.length; i < l; i ++ ) {
  34214. var instanceLight = getLight( instanceLights[ i ] );
  34215. if ( instanceLight !== null ) {
  34216. objects.push( instanceLight.clone() );
  34217. }
  34218. }
  34219. // instance geometries
  34220. for ( var i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  34221. var instance = instanceGeometries[ i ];
  34222. // a single geometry instance in collada can lead to multiple object3Ds.
  34223. // this is the case when primitives are combined like triangles and lines
  34224. var geometries = getGeometry( instance.id );
  34225. var newObjects = buildObjects( geometries, instance.materials );
  34226. for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
  34227. objects.push( newObjects[ j ] );
  34228. }
  34229. }
  34230. // instance nodes
  34231. for ( var i = 0, l = instanceNodes.length; i < l; i ++ ) {
  34232. objects.push( getNode( instanceNodes[ i ] ).clone() );
  34233. }
  34234. var object;
  34235. if ( nodes.length === 0 && objects.length === 1 ) {
  34236. object = objects[ 0 ];
  34237. } else {
  34238. object = ( type === 'JOINT' ) ? new THREE.Bone() : new THREE.Group();
  34239. for ( var i = 0; i < objects.length; i ++ ) {
  34240. object.add( objects[ i ] );
  34241. }
  34242. }
  34243. if ( object.name === '' ) {
  34244. object.name = ( type === 'JOINT' ) ? data.sid : data.name;
  34245. }
  34246. object.matrix.copy( matrix );
  34247. object.matrix.decompose( object.position, object.quaternion, object.scale );
  34248. return object;
  34249. }
  34250. function resolveMaterialBinding( keys, instanceMaterials ) {
  34251. var materials = [];
  34252. for ( var i = 0, l = keys.length; i < l; i ++ ) {
  34253. var id = instanceMaterials[ keys[ i ] ];
  34254. materials.push( getMaterial( id ) );
  34255. }
  34256. return materials;
  34257. }
  34258. function buildObjects( geometries, instanceMaterials ) {
  34259. var objects = [];
  34260. for ( var type in geometries ) {
  34261. var geometry = geometries[ type ];
  34262. var materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials );
  34263. // handle case if no materials are defined
  34264. if ( materials.length === 0 ) {
  34265. if ( type === 'lines' || type === 'linestrips' ) {
  34266. materials.push( new THREE.LineBasicMaterial() );
  34267. } else {
  34268. materials.push( new THREE.MeshPhongMaterial() );
  34269. }
  34270. }
  34271. // regard skinning
  34272. var skinning = ( geometry.data.attributes.skinIndex !== undefined );
  34273. if ( skinning ) {
  34274. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  34275. materials[ i ].skinning = true;
  34276. }
  34277. }
  34278. // choose between a single or multi materials (material array)
  34279. var material = ( materials.length === 1 ) ? materials[ 0 ] : materials;
  34280. // now create a specific 3D object
  34281. var object;
  34282. switch ( type ) {
  34283. case 'lines':
  34284. object = new THREE.LineSegments( geometry.data, material );
  34285. break;
  34286. case 'linestrips':
  34287. object = new THREE.Line( geometry.data, material );
  34288. break;
  34289. case 'triangles':
  34290. case 'polylist':
  34291. if ( skinning ) {
  34292. object = new THREE.SkinnedMesh( geometry.data, material );
  34293. } else {
  34294. object = new THREE.Mesh( geometry.data, material );
  34295. }
  34296. break;
  34297. }
  34298. objects.push( object );
  34299. }
  34300. return objects;
  34301. }
  34302. function hasNode( id ) {
  34303. return library.nodes[ id ] !== undefined;
  34304. }
  34305. function getNode( id ) {
  34306. return getBuild( library.nodes[ id ], buildNode );
  34307. }
  34308. // visual scenes
  34309. function parseVisualScene( xml ) {
  34310. var data = {
  34311. name: xml.getAttribute( 'name' ),
  34312. children: []
  34313. };
  34314. prepareNodes( xml );
  34315. var elements = getElementsByTagName( xml, 'node' );
  34316. for ( var i = 0; i < elements.length; i ++ ) {
  34317. data.children.push( parseNode( elements[ i ] ) );
  34318. }
  34319. library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
  34320. }
  34321. function buildVisualScene( data ) {
  34322. var group = new THREE.Group();
  34323. group.name = data.name;
  34324. var children = data.children;
  34325. for ( var i = 0; i < children.length; i ++ ) {
  34326. var child = children[ i ];
  34327. group.add( getNode( child.id ) );
  34328. }
  34329. return group;
  34330. }
  34331. function hasVisualScene( id ) {
  34332. return library.visualScenes[ id ] !== undefined;
  34333. }
  34334. function getVisualScene( id ) {
  34335. return getBuild( library.visualScenes[ id ], buildVisualScene );
  34336. }
  34337. // scenes
  34338. function parseScene( xml ) {
  34339. var instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  34340. return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
  34341. }
  34342. function setupAnimations() {
  34343. var clips = library.clips;
  34344. if ( isEmpty( clips ) === true ) {
  34345. if ( isEmpty( library.animations ) === false ) {
  34346. // if there are animations but no clips, we create a default clip for playback
  34347. var tracks = [];
  34348. for ( var id in library.animations ) {
  34349. var animationTracks = getAnimation( id );
  34350. for ( var i = 0, l = animationTracks.length; i < l; i ++ ) {
  34351. tracks.push( animationTracks[ i ] );
  34352. }
  34353. }
  34354. animations.push( new THREE.AnimationClip( 'default', - 1, tracks ) );
  34355. }
  34356. } else {
  34357. for ( var id in clips ) {
  34358. animations.push( getAnimationClip( id ) );
  34359. }
  34360. }
  34361. }
  34362. if ( text.length === 0 ) {
  34363. return { scene: new THREE.Scene() };
  34364. }
  34365. var xml = new DOMParser().parseFromString( text, 'application/xml' );
  34366. var collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
  34367. // metadata
  34368. var version = collada.getAttribute( 'version' );
  34369. console.log( 'THREE.ColladaLoader: File version', version );
  34370. var asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
  34371. var textureLoader = new THREE.TextureLoader( this.manager );
  34372. textureLoader.setPath( path ).setCrossOrigin( this.crossOrigin );
  34373. //
  34374. var animations = [];
  34375. var kinematics = {};
  34376. var count = 0;
  34377. //
  34378. var library = {
  34379. animations: {},
  34380. clips: {},
  34381. controllers: {},
  34382. images: {},
  34383. effects: {},
  34384. materials: {},
  34385. cameras: {},
  34386. lights: {},
  34387. geometries: {},
  34388. nodes: {},
  34389. visualScenes: {},
  34390. kinematicsModels: {},
  34391. kinematicsScenes: {}
  34392. };
  34393. parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
  34394. parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
  34395. parseLibrary( collada, 'library_controllers', 'controller', parseController );
  34396. parseLibrary( collada, 'library_images', 'image', parseImage );
  34397. parseLibrary( collada, 'library_effects', 'effect', parseEffect );
  34398. parseLibrary( collada, 'library_materials', 'material', parseMaterial );
  34399. parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
  34400. parseLibrary( collada, 'library_lights', 'light', parseLight );
  34401. parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
  34402. parseLibrary( collada, 'library_nodes', 'node', parseNode );
  34403. parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
  34404. parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
  34405. parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
  34406. buildLibrary( library.animations, buildAnimation );
  34407. buildLibrary( library.clips, buildAnimationClip );
  34408. buildLibrary( library.controllers, buildController );
  34409. buildLibrary( library.images, buildImage );
  34410. buildLibrary( library.effects, buildEffect );
  34411. buildLibrary( library.materials, buildMaterial );
  34412. buildLibrary( library.cameras, buildCamera );
  34413. buildLibrary( library.lights, buildLight );
  34414. buildLibrary( library.geometries, buildGeometry );
  34415. buildLibrary( library.visualScenes, buildVisualScene );
  34416. setupAnimations();
  34417. setupKinematics();
  34418. var scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
  34419. if ( asset.upAxis === 'Z_UP' ) {
  34420. scene.quaternion.setFromEuler( new THREE.Euler( - Math.PI / 2, 0, 0 ) );
  34421. }
  34422. scene.scale.multiplyScalar( asset.unit );
  34423. return {
  34424. animations: animations,
  34425. kinematics: kinematics,
  34426. library: library,
  34427. scene: scene
  34428. };
  34429. }
  34430. };
  34431. },{}],42:[function(_dereq_,module,exports){
  34432. /**
  34433. * @author Rich Tibbett / https://github.com/richtr
  34434. * @author mrdoob / http://mrdoob.com/
  34435. * @author Tony Parisi / http://www.tonyparisi.com/
  34436. * @author Takahiro / https://github.com/takahirox
  34437. * @author Don McCurdy / https://www.donmccurdy.com
  34438. */
  34439. THREE.GLTFLoader = ( function () {
  34440. function GLTFLoader( manager ) {
  34441. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  34442. this.dracoLoader = null;
  34443. }
  34444. GLTFLoader.prototype = {
  34445. constructor: GLTFLoader,
  34446. crossOrigin: 'Anonymous',
  34447. load: function ( url, onLoad, onProgress, onError ) {
  34448. var scope = this;
  34449. var path = this.path !== undefined ? this.path : THREE.LoaderUtils.extractUrlBase( url );
  34450. var loader = new THREE.FileLoader( scope.manager );
  34451. loader.setResponseType( 'arraybuffer' );
  34452. loader.load( url, function ( data ) {
  34453. try {
  34454. scope.parse( data, path, onLoad, onError );
  34455. } catch ( e ) {
  34456. if ( onError !== undefined ) {
  34457. onError( e );
  34458. } else {
  34459. throw e;
  34460. }
  34461. }
  34462. }, onProgress, onError );
  34463. },
  34464. setCrossOrigin: function ( value ) {
  34465. this.crossOrigin = value;
  34466. return this;
  34467. },
  34468. setPath: function ( value ) {
  34469. this.path = value;
  34470. return this;
  34471. },
  34472. setDRACOLoader: function ( dracoLoader ) {
  34473. this.dracoLoader = dracoLoader;
  34474. return this;
  34475. },
  34476. parse: function ( data, path, onLoad, onError ) {
  34477. var content;
  34478. var extensions = {};
  34479. if ( typeof data === 'string' ) {
  34480. content = data;
  34481. } else {
  34482. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  34483. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  34484. try {
  34485. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  34486. } catch ( error ) {
  34487. if ( onError ) onError( error );
  34488. return;
  34489. }
  34490. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  34491. } else {
  34492. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  34493. }
  34494. }
  34495. var json = JSON.parse( content );
  34496. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  34497. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  34498. return;
  34499. }
  34500. if ( json.extensionsUsed ) {
  34501. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_LIGHTS ) >= 0 ) {
  34502. extensions[ EXTENSIONS.KHR_LIGHTS ] = new GLTFLightsExtension( json );
  34503. }
  34504. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_UNLIT ) >= 0 ) {
  34505. extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] = new GLTFMaterialsUnlitExtension( json );
  34506. }
  34507. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ) >= 0 ) {
  34508. extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  34509. }
  34510. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ) >= 0 ) {
  34511. extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] = new GLTFDracoMeshCompressionExtension( this.dracoLoader );
  34512. }
  34513. if ( json.extensionsUsed.indexOf( EXTENSIONS.MSFT_TEXTURE_DDS ) >= 0 ) {
  34514. extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension();
  34515. }
  34516. }
  34517. var parser = new GLTFParser( json, extensions, {
  34518. path: path || this.path || '',
  34519. crossOrigin: this.crossOrigin,
  34520. manager: this.manager
  34521. } );
  34522. parser.parse( function ( scene, scenes, cameras, animations, asset ) {
  34523. var glTF = {
  34524. scene: scene,
  34525. scenes: scenes,
  34526. cameras: cameras,
  34527. animations: animations,
  34528. asset: asset
  34529. };
  34530. onLoad( glTF );
  34531. }, onError );
  34532. }
  34533. };
  34534. /* GLTFREGISTRY */
  34535. function GLTFRegistry() {
  34536. var objects = {};
  34537. return {
  34538. get: function ( key ) {
  34539. return objects[ key ];
  34540. },
  34541. add: function ( key, object ) {
  34542. objects[ key ] = object;
  34543. },
  34544. remove: function ( key ) {
  34545. delete objects[ key ];
  34546. },
  34547. removeAll: function () {
  34548. objects = {};
  34549. }
  34550. };
  34551. }
  34552. /*********************************/
  34553. /********** EXTENSIONS ***********/
  34554. /*********************************/
  34555. var EXTENSIONS = {
  34556. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  34557. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  34558. KHR_LIGHTS: 'KHR_lights',
  34559. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  34560. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  34561. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  34562. };
  34563. /**
  34564. * DDS Texture Extension
  34565. *
  34566. * Specification:
  34567. * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  34568. *
  34569. */
  34570. function GLTFTextureDDSExtension() {
  34571. if ( ! THREE.DDSLoader ) {
  34572. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  34573. }
  34574. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  34575. this.ddsLoader = new THREE.DDSLoader();
  34576. }
  34577. /**
  34578. * Lights Extension
  34579. *
  34580. * Specification: PENDING
  34581. */
  34582. function GLTFLightsExtension( json ) {
  34583. this.name = EXTENSIONS.KHR_LIGHTS;
  34584. this.lights = {};
  34585. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS ] ) || {};
  34586. var lights = extension.lights || {};
  34587. for ( var lightId in lights ) {
  34588. var light = lights[ lightId ];
  34589. var lightNode;
  34590. var color = new THREE.Color().fromArray( light.color );
  34591. switch ( light.type ) {
  34592. case 'directional':
  34593. lightNode = new THREE.DirectionalLight( color );
  34594. lightNode.target.position.set( 0, 0, 1 );
  34595. lightNode.add( lightNode.target );
  34596. break;
  34597. case 'point':
  34598. lightNode = new THREE.PointLight( color );
  34599. break;
  34600. case 'spot':
  34601. lightNode = new THREE.SpotLight( color );
  34602. // Handle spotlight properties.
  34603. light.spot = light.spot || {};
  34604. light.spot.innerConeAngle = light.spot.innerConeAngle !== undefined ? light.spot.innerConeAngle : 0;
  34605. light.spot.outerConeAngle = light.spot.outerConeAngle !== undefined ? light.spot.outerConeAngle : Math.PI / 4.0;
  34606. lightNode.angle = light.spot.outerConeAngle;
  34607. lightNode.penumbra = 1.0 - light.spot.innerConeAngle / light.spot.outerConeAngle;
  34608. lightNode.target.position.set( 0, 0, 1 );
  34609. lightNode.add( lightNode.target );
  34610. break;
  34611. case 'ambient':
  34612. lightNode = new THREE.AmbientLight( color );
  34613. break;
  34614. }
  34615. if ( lightNode ) {
  34616. lightNode.decay = 2;
  34617. if ( light.intensity !== undefined ) {
  34618. lightNode.intensity = light.intensity;
  34619. }
  34620. lightNode.name = light.name || ( 'light_' + lightId );
  34621. this.lights[ lightId ] = lightNode;
  34622. }
  34623. }
  34624. }
  34625. /**
  34626. * Unlit Materials Extension (pending)
  34627. *
  34628. * PR: https://github.com/KhronosGroup/glTF/pull/1163
  34629. */
  34630. function GLTFMaterialsUnlitExtension( json ) {
  34631. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  34632. }
  34633. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function ( material ) {
  34634. return THREE.MeshBasicMaterial;
  34635. };
  34636. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, material, parser ) {
  34637. var pending = [];
  34638. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  34639. materialParams.opacity = 1.0;
  34640. var metallicRoughness = material.pbrMetallicRoughness;
  34641. if ( metallicRoughness ) {
  34642. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  34643. var array = metallicRoughness.baseColorFactor;
  34644. materialParams.color.fromArray( array );
  34645. materialParams.opacity = array[ 3 ];
  34646. }
  34647. if ( metallicRoughness.baseColorTexture !== undefined ) {
  34648. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  34649. }
  34650. }
  34651. return Promise.all( pending );
  34652. };
  34653. /* BINARY EXTENSION */
  34654. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  34655. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  34656. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  34657. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  34658. function GLTFBinaryExtension( data ) {
  34659. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  34660. this.content = null;
  34661. this.body = null;
  34662. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  34663. this.header = {
  34664. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  34665. version: headerView.getUint32( 4, true ),
  34666. length: headerView.getUint32( 8, true )
  34667. };
  34668. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  34669. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  34670. } else if ( this.header.version < 2.0 ) {
  34671. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  34672. }
  34673. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  34674. var chunkIndex = 0;
  34675. while ( chunkIndex < chunkView.byteLength ) {
  34676. var chunkLength = chunkView.getUint32( chunkIndex, true );
  34677. chunkIndex += 4;
  34678. var chunkType = chunkView.getUint32( chunkIndex, true );
  34679. chunkIndex += 4;
  34680. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  34681. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  34682. this.content = THREE.LoaderUtils.decodeText( contentArray );
  34683. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  34684. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  34685. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  34686. }
  34687. // Clients must ignore chunks with unknown types.
  34688. chunkIndex += chunkLength;
  34689. }
  34690. if ( this.content === null ) {
  34691. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  34692. }
  34693. }
  34694. /**
  34695. * DRACO Mesh Compression Extension
  34696. *
  34697. * Specification: https://github.com/KhronosGroup/glTF/pull/874
  34698. */
  34699. function GLTFDracoMeshCompressionExtension ( dracoLoader ) {
  34700. if ( ! dracoLoader ) {
  34701. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  34702. }
  34703. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  34704. this.dracoLoader = dracoLoader;
  34705. }
  34706. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  34707. var dracoLoader = this.dracoLoader;
  34708. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  34709. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  34710. var threeAttributeMap = {};
  34711. for ( var attributeName in gltfAttributeMap ) {
  34712. if ( !( attributeName in ATTRIBUTES ) ) continue;
  34713. threeAttributeMap[ ATTRIBUTES[ attributeName ] ] = gltfAttributeMap[ attributeName ];
  34714. }
  34715. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  34716. return new Promise( function ( resolve ) {
  34717. dracoLoader.decodeDracoFile( bufferView, resolve, threeAttributeMap );
  34718. } );
  34719. } );
  34720. };
  34721. /**
  34722. * Specular-Glossiness Extension
  34723. *
  34724. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  34725. */
  34726. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  34727. return {
  34728. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  34729. specularGlossinessParams: [
  34730. 'color',
  34731. 'map',
  34732. 'lightMap',
  34733. 'lightMapIntensity',
  34734. 'aoMap',
  34735. 'aoMapIntensity',
  34736. 'emissive',
  34737. 'emissiveIntensity',
  34738. 'emissiveMap',
  34739. 'bumpMap',
  34740. 'bumpScale',
  34741. 'normalMap',
  34742. 'displacementMap',
  34743. 'displacementScale',
  34744. 'displacementBias',
  34745. 'specularMap',
  34746. 'specular',
  34747. 'glossinessMap',
  34748. 'glossiness',
  34749. 'alphaMap',
  34750. 'envMap',
  34751. 'envMapIntensity',
  34752. 'refractionRatio',
  34753. ],
  34754. getMaterialType: function () {
  34755. return THREE.ShaderMaterial;
  34756. },
  34757. extendParams: function ( params, material, parser ) {
  34758. var pbrSpecularGlossiness = material.extensions[ this.name ];
  34759. var shader = THREE.ShaderLib[ 'standard' ];
  34760. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  34761. var specularMapParsFragmentChunk = [
  34762. '#ifdef USE_SPECULARMAP',
  34763. ' uniform sampler2D specularMap;',
  34764. '#endif'
  34765. ].join( '\n' );
  34766. var glossinessMapParsFragmentChunk = [
  34767. '#ifdef USE_GLOSSINESSMAP',
  34768. ' uniform sampler2D glossinessMap;',
  34769. '#endif'
  34770. ].join( '\n' );
  34771. var specularMapFragmentChunk = [
  34772. 'vec3 specularFactor = specular;',
  34773. '#ifdef USE_SPECULARMAP',
  34774. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  34775. ' texelSpecular = sRGBToLinear( texelSpecular );',
  34776. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34777. ' specularFactor *= texelSpecular.rgb;',
  34778. '#endif'
  34779. ].join( '\n' );
  34780. var glossinessMapFragmentChunk = [
  34781. 'float glossinessFactor = glossiness;',
  34782. '#ifdef USE_GLOSSINESSMAP',
  34783. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  34784. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34785. ' glossinessFactor *= texelGlossiness.a;',
  34786. '#endif'
  34787. ].join( '\n' );
  34788. var lightPhysicalFragmentChunk = [
  34789. 'PhysicalMaterial material;',
  34790. 'material.diffuseColor = diffuseColor.rgb;',
  34791. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  34792. 'material.specularColor = specularFactor.rgb;',
  34793. ].join( '\n' );
  34794. var fragmentShader = shader.fragmentShader
  34795. .replace( '#include <specularmap_fragment>', '' )
  34796. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  34797. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  34798. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  34799. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  34800. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  34801. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  34802. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  34803. delete uniforms.roughness;
  34804. delete uniforms.metalness;
  34805. delete uniforms.roughnessMap;
  34806. delete uniforms.metalnessMap;
  34807. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  34808. uniforms.glossiness = { value: 0.5 };
  34809. uniforms.specularMap = { value: null };
  34810. uniforms.glossinessMap = { value: null };
  34811. params.vertexShader = shader.vertexShader;
  34812. params.fragmentShader = fragmentShader;
  34813. params.uniforms = uniforms;
  34814. params.defines = { 'STANDARD': '' };
  34815. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  34816. params.opacity = 1.0;
  34817. var pending = [];
  34818. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  34819. var array = pbrSpecularGlossiness.diffuseFactor;
  34820. params.color.fromArray( array );
  34821. params.opacity = array[ 3 ];
  34822. }
  34823. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  34824. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture.index ) );
  34825. }
  34826. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  34827. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  34828. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  34829. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  34830. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  34831. }
  34832. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  34833. var specGlossIndex = pbrSpecularGlossiness.specularGlossinessTexture.index;
  34834. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossIndex ) );
  34835. pending.push( parser.assignTexture( params, 'specularMap', specGlossIndex ) );
  34836. }
  34837. return Promise.all( pending );
  34838. },
  34839. createMaterial: function ( params ) {
  34840. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  34841. var material = new THREE.ShaderMaterial( {
  34842. defines: params.defines,
  34843. vertexShader: params.vertexShader,
  34844. fragmentShader: params.fragmentShader,
  34845. uniforms: params.uniforms,
  34846. fog: true,
  34847. lights: true,
  34848. opacity: params.opacity,
  34849. transparent: params.transparent
  34850. } );
  34851. material.isGLTFSpecularGlossinessMaterial = true;
  34852. material.color = params.color;
  34853. material.map = params.map === undefined ? null : params.map;
  34854. material.lightMap = null;
  34855. material.lightMapIntensity = 1.0;
  34856. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  34857. material.aoMapIntensity = 1.0;
  34858. material.emissive = params.emissive;
  34859. material.emissiveIntensity = 1.0;
  34860. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  34861. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  34862. material.bumpScale = 1;
  34863. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  34864. if ( params.normalScale ) material.normalScale = params.normalScale;
  34865. material.displacementMap = null;
  34866. material.displacementScale = 1;
  34867. material.displacementBias = 0;
  34868. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  34869. material.specular = params.specular;
  34870. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  34871. material.glossiness = params.glossiness;
  34872. material.alphaMap = null;
  34873. material.envMap = params.envMap === undefined ? null : params.envMap;
  34874. material.envMapIntensity = 1.0;
  34875. material.refractionRatio = 0.98;
  34876. material.extensions.derivatives = true;
  34877. return material;
  34878. },
  34879. /**
  34880. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  34881. * copy only properties it knows about or inherits, and misses many properties that would
  34882. * normally be defined by MeshStandardMaterial.
  34883. *
  34884. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  34885. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  34886. * AND also updating `.onBeforeRender` on the parent mesh.
  34887. *
  34888. * @param {THREE.ShaderMaterial} source
  34889. * @return {THREE.ShaderMaterial}
  34890. */
  34891. cloneMaterial: function ( source ) {
  34892. var target = source.clone();
  34893. target.isGLTFSpecularGlossinessMaterial = true;
  34894. var params = this.specularGlossinessParams;
  34895. for ( var i = 0, il = params.length; i < il; i ++ ) {
  34896. target[ params[ i ] ] = source[ params[ i ] ];
  34897. }
  34898. return target;
  34899. },
  34900. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  34901. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  34902. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  34903. return;
  34904. }
  34905. var uniforms = material.uniforms;
  34906. var defines = material.defines;
  34907. uniforms.opacity.value = material.opacity;
  34908. uniforms.diffuse.value.copy( material.color );
  34909. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  34910. uniforms.map.value = material.map;
  34911. uniforms.specularMap.value = material.specularMap;
  34912. uniforms.alphaMap.value = material.alphaMap;
  34913. uniforms.lightMap.value = material.lightMap;
  34914. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  34915. uniforms.aoMap.value = material.aoMap;
  34916. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  34917. // uv repeat and offset setting priorities
  34918. // 1. color map
  34919. // 2. specular map
  34920. // 3. normal map
  34921. // 4. bump map
  34922. // 5. alpha map
  34923. // 6. emissive map
  34924. var uvScaleMap;
  34925. if ( material.map ) {
  34926. uvScaleMap = material.map;
  34927. } else if ( material.specularMap ) {
  34928. uvScaleMap = material.specularMap;
  34929. } else if ( material.displacementMap ) {
  34930. uvScaleMap = material.displacementMap;
  34931. } else if ( material.normalMap ) {
  34932. uvScaleMap = material.normalMap;
  34933. } else if ( material.bumpMap ) {
  34934. uvScaleMap = material.bumpMap;
  34935. } else if ( material.glossinessMap ) {
  34936. uvScaleMap = material.glossinessMap;
  34937. } else if ( material.alphaMap ) {
  34938. uvScaleMap = material.alphaMap;
  34939. } else if ( material.emissiveMap ) {
  34940. uvScaleMap = material.emissiveMap;
  34941. }
  34942. if ( uvScaleMap !== undefined ) {
  34943. // backwards compatibility
  34944. if ( uvScaleMap.isWebGLRenderTarget ) {
  34945. uvScaleMap = uvScaleMap.texture;
  34946. }
  34947. var offset;
  34948. var repeat;
  34949. if ( uvScaleMap.matrix !== undefined ) {
  34950. // > r88.
  34951. if ( uvScaleMap.matrixAutoUpdate === true ) {
  34952. offset = uvScaleMap.offset;
  34953. repeat = uvScaleMap.repeat;
  34954. var rotation = uvScaleMap.rotation;
  34955. var center = uvScaleMap.center;
  34956. uvScaleMap.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y );
  34957. }
  34958. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  34959. } else {
  34960. // <= r87. Remove when reasonable.
  34961. offset = uvScaleMap.offset;
  34962. repeat = uvScaleMap.repeat;
  34963. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  34964. }
  34965. }
  34966. uniforms.envMap.value = material.envMap;
  34967. uniforms.envMapIntensity.value = material.envMapIntensity;
  34968. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? - 1 : 1;
  34969. uniforms.refractionRatio.value = material.refractionRatio;
  34970. uniforms.specular.value.copy( material.specular );
  34971. uniforms.glossiness.value = material.glossiness;
  34972. uniforms.glossinessMap.value = material.glossinessMap;
  34973. uniforms.emissiveMap.value = material.emissiveMap;
  34974. uniforms.bumpMap.value = material.bumpMap;
  34975. uniforms.normalMap.value = material.normalMap;
  34976. uniforms.displacementMap.value = material.displacementMap;
  34977. uniforms.displacementScale.value = material.displacementScale;
  34978. uniforms.displacementBias.value = material.displacementBias;
  34979. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  34980. defines.USE_GLOSSINESSMAP = '';
  34981. // set USE_ROUGHNESSMAP to enable vUv
  34982. defines.USE_ROUGHNESSMAP = '';
  34983. }
  34984. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  34985. delete defines.USE_GLOSSINESSMAP;
  34986. delete defines.USE_ROUGHNESSMAP;
  34987. }
  34988. }
  34989. };
  34990. }
  34991. /*********************************/
  34992. /********** INTERPOLATION ********/
  34993. /*********************************/
  34994. // Spline Interpolation
  34995. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  34996. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  34997. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  34998. };
  34999. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  35000. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  35001. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  35002. var result = this.resultBuffer;
  35003. var values = this.sampleValues;
  35004. var stride = this.valueSize;
  35005. var stride2 = stride * 2;
  35006. var stride3 = stride * 3;
  35007. var td = t1 - t0;
  35008. var p = ( t - t0 ) / td;
  35009. var pp = p * p;
  35010. var ppp = pp * p;
  35011. var offset1 = i1 * stride3;
  35012. var offset0 = offset1 - stride3;
  35013. var s0 = 2 * ppp - 3 * pp + 1;
  35014. var s1 = ppp - 2 * pp + p;
  35015. var s2 = - 2 * ppp + 3 * pp;
  35016. var s3 = ppp - pp;
  35017. // Layout of keyframe output values for CUBICSPLINE animations:
  35018. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  35019. for ( var i = 0; i !== stride; i ++ ) {
  35020. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  35021. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  35022. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  35023. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  35024. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  35025. }
  35026. return result;
  35027. };
  35028. /*********************************/
  35029. /********** INTERNALS ************/
  35030. /*********************************/
  35031. /* CONSTANTS */
  35032. var WEBGL_CONSTANTS = {
  35033. FLOAT: 5126,
  35034. //FLOAT_MAT2: 35674,
  35035. FLOAT_MAT3: 35675,
  35036. FLOAT_MAT4: 35676,
  35037. FLOAT_VEC2: 35664,
  35038. FLOAT_VEC3: 35665,
  35039. FLOAT_VEC4: 35666,
  35040. LINEAR: 9729,
  35041. REPEAT: 10497,
  35042. SAMPLER_2D: 35678,
  35043. POINTS: 0,
  35044. LINES: 1,
  35045. LINE_LOOP: 2,
  35046. LINE_STRIP: 3,
  35047. TRIANGLES: 4,
  35048. TRIANGLE_STRIP: 5,
  35049. TRIANGLE_FAN: 6,
  35050. UNSIGNED_BYTE: 5121,
  35051. UNSIGNED_SHORT: 5123
  35052. };
  35053. var WEBGL_TYPE = {
  35054. 5126: Number,
  35055. //35674: THREE.Matrix2,
  35056. 35675: THREE.Matrix3,
  35057. 35676: THREE.Matrix4,
  35058. 35664: THREE.Vector2,
  35059. 35665: THREE.Vector3,
  35060. 35666: THREE.Vector4,
  35061. 35678: THREE.Texture
  35062. };
  35063. var WEBGL_COMPONENT_TYPES = {
  35064. 5120: Int8Array,
  35065. 5121: Uint8Array,
  35066. 5122: Int16Array,
  35067. 5123: Uint16Array,
  35068. 5125: Uint32Array,
  35069. 5126: Float32Array
  35070. };
  35071. var WEBGL_FILTERS = {
  35072. 9728: THREE.NearestFilter,
  35073. 9729: THREE.LinearFilter,
  35074. 9984: THREE.NearestMipMapNearestFilter,
  35075. 9985: THREE.LinearMipMapNearestFilter,
  35076. 9986: THREE.NearestMipMapLinearFilter,
  35077. 9987: THREE.LinearMipMapLinearFilter
  35078. };
  35079. var WEBGL_WRAPPINGS = {
  35080. 33071: THREE.ClampToEdgeWrapping,
  35081. 33648: THREE.MirroredRepeatWrapping,
  35082. 10497: THREE.RepeatWrapping
  35083. };
  35084. var WEBGL_TEXTURE_FORMATS = {
  35085. 6406: THREE.AlphaFormat,
  35086. 6407: THREE.RGBFormat,
  35087. 6408: THREE.RGBAFormat,
  35088. 6409: THREE.LuminanceFormat,
  35089. 6410: THREE.LuminanceAlphaFormat
  35090. };
  35091. var WEBGL_TEXTURE_DATATYPES = {
  35092. 5121: THREE.UnsignedByteType,
  35093. 32819: THREE.UnsignedShort4444Type,
  35094. 32820: THREE.UnsignedShort5551Type,
  35095. 33635: THREE.UnsignedShort565Type
  35096. };
  35097. var WEBGL_SIDES = {
  35098. 1028: THREE.BackSide, // Culling front
  35099. 1029: THREE.FrontSide // Culling back
  35100. //1032: THREE.NoSide // Culling front and back, what to do?
  35101. };
  35102. var WEBGL_DEPTH_FUNCS = {
  35103. 512: THREE.NeverDepth,
  35104. 513: THREE.LessDepth,
  35105. 514: THREE.EqualDepth,
  35106. 515: THREE.LessEqualDepth,
  35107. 516: THREE.GreaterEqualDepth,
  35108. 517: THREE.NotEqualDepth,
  35109. 518: THREE.GreaterEqualDepth,
  35110. 519: THREE.AlwaysDepth
  35111. };
  35112. var WEBGL_BLEND_EQUATIONS = {
  35113. 32774: THREE.AddEquation,
  35114. 32778: THREE.SubtractEquation,
  35115. 32779: THREE.ReverseSubtractEquation
  35116. };
  35117. var WEBGL_BLEND_FUNCS = {
  35118. 0: THREE.ZeroFactor,
  35119. 1: THREE.OneFactor,
  35120. 768: THREE.SrcColorFactor,
  35121. 769: THREE.OneMinusSrcColorFactor,
  35122. 770: THREE.SrcAlphaFactor,
  35123. 771: THREE.OneMinusSrcAlphaFactor,
  35124. 772: THREE.DstAlphaFactor,
  35125. 773: THREE.OneMinusDstAlphaFactor,
  35126. 774: THREE.DstColorFactor,
  35127. 775: THREE.OneMinusDstColorFactor,
  35128. 776: THREE.SrcAlphaSaturateFactor
  35129. // The followings are not supported by Three.js yet
  35130. //32769: CONSTANT_COLOR,
  35131. //32770: ONE_MINUS_CONSTANT_COLOR,
  35132. //32771: CONSTANT_ALPHA,
  35133. //32772: ONE_MINUS_CONSTANT_COLOR
  35134. };
  35135. var WEBGL_TYPE_SIZES = {
  35136. 'SCALAR': 1,
  35137. 'VEC2': 2,
  35138. 'VEC3': 3,
  35139. 'VEC4': 4,
  35140. 'MAT2': 4,
  35141. 'MAT3': 9,
  35142. 'MAT4': 16
  35143. };
  35144. var ATTRIBUTES = {
  35145. POSITION: 'position',
  35146. NORMAL: 'normal',
  35147. TEXCOORD_0: 'uv',
  35148. TEXCOORD0: 'uv', // deprecated
  35149. TEXCOORD: 'uv', // deprecated
  35150. TEXCOORD_1: 'uv2',
  35151. COLOR_0: 'color',
  35152. COLOR0: 'color', // deprecated
  35153. COLOR: 'color', // deprecated
  35154. WEIGHTS_0: 'skinWeight',
  35155. WEIGHT: 'skinWeight', // deprecated
  35156. JOINTS_0: 'skinIndex',
  35157. JOINT: 'skinIndex' // deprecated
  35158. }
  35159. var PATH_PROPERTIES = {
  35160. scale: 'scale',
  35161. translation: 'position',
  35162. rotation: 'quaternion',
  35163. weights: 'morphTargetInfluences'
  35164. };
  35165. var INTERPOLATION = {
  35166. CUBICSPLINE: THREE.InterpolateSmooth, // We use custom interpolation GLTFCubicSplineInterpolation for CUBICSPLINE.
  35167. // KeyframeTrack.optimize() can't handle glTF Cubic Spline output values layout,
  35168. // using THREE.InterpolateSmooth for KeyframeTrack instantiation to prevent optimization.
  35169. // See KeyframeTrack.optimize() for the detail.
  35170. LINEAR: THREE.InterpolateLinear,
  35171. STEP: THREE.InterpolateDiscrete
  35172. };
  35173. var STATES_ENABLES = {
  35174. 2884: 'CULL_FACE',
  35175. 2929: 'DEPTH_TEST',
  35176. 3042: 'BLEND',
  35177. 3089: 'SCISSOR_TEST',
  35178. 32823: 'POLYGON_OFFSET_FILL',
  35179. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  35180. };
  35181. var ALPHA_MODES = {
  35182. OPAQUE: 'OPAQUE',
  35183. MASK: 'MASK',
  35184. BLEND: 'BLEND'
  35185. };
  35186. /* UTILITY FUNCTIONS */
  35187. function resolveURL( url, path ) {
  35188. // Invalid URL
  35189. if ( typeof url !== 'string' || url === '' ) return '';
  35190. // Absolute URL http://,https://,//
  35191. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35192. // Data URI
  35193. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35194. // Blob URL
  35195. if ( /^blob:.*$/i.test( url ) ) return url;
  35196. // Relative URL
  35197. return path + url;
  35198. }
  35199. /**
  35200. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  35201. */
  35202. function createDefaultMaterial() {
  35203. return new THREE.MeshStandardMaterial( {
  35204. color: 0xFFFFFF,
  35205. emissive: 0x000000,
  35206. metalness: 1,
  35207. roughness: 1,
  35208. transparent: false,
  35209. depthTest: true,
  35210. side: THREE.FrontSide
  35211. } );
  35212. }
  35213. /**
  35214. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  35215. *
  35216. * @param {THREE.Mesh} mesh
  35217. * @param {GLTF.Mesh} meshDef
  35218. * @param {GLTF.Primitive} primitiveDef
  35219. * @param {Array<THREE.BufferAttribute>} accessors
  35220. */
  35221. function addMorphTargets( mesh, meshDef, primitiveDef, accessors ) {
  35222. var geometry = mesh.geometry;
  35223. var targets = primitiveDef.targets;
  35224. var hasMorphPosition = false;
  35225. var hasMorphNormal = false;
  35226. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  35227. var target = targets[ i ];
  35228. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  35229. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  35230. if ( hasMorphPosition && hasMorphNormal ) break;
  35231. }
  35232. if ( ! hasMorphPosition && ! hasMorphNormal ) return;
  35233. var morphPositions = [];
  35234. var morphNormals = [];
  35235. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  35236. var target = targets[ i ];
  35237. var attributeName = 'morphTarget' + i;
  35238. if ( hasMorphPosition ) {
  35239. // Three.js morph position is absolute value. The formula is
  35240. // basePosition
  35241. // + weight0 * ( morphPosition0 - basePosition )
  35242. // + weight1 * ( morphPosition1 - basePosition )
  35243. // ...
  35244. // while the glTF one is relative
  35245. // basePosition
  35246. // + weight0 * glTFmorphPosition0
  35247. // + weight1 * glTFmorphPosition1
  35248. // ...
  35249. // then we need to convert from relative to absolute here.
  35250. if ( target.POSITION !== undefined ) {
  35251. // Cloning not to pollute original accessor
  35252. var positionAttribute = cloneBufferAttribute( accessors[ target.POSITION ] );
  35253. positionAttribute.name = attributeName;
  35254. var position = geometry.attributes.position;
  35255. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  35256. positionAttribute.setXYZ(
  35257. j,
  35258. positionAttribute.getX( j ) + position.getX( j ),
  35259. positionAttribute.getY( j ) + position.getY( j ),
  35260. positionAttribute.getZ( j ) + position.getZ( j )
  35261. );
  35262. }
  35263. } else {
  35264. positionAttribute = geometry.attributes.position;
  35265. }
  35266. morphPositions.push( positionAttribute );
  35267. }
  35268. if ( hasMorphNormal ) {
  35269. // see target.POSITION's comment
  35270. var normalAttribute;
  35271. if ( target.NORMAL !== undefined ) {
  35272. var normalAttribute = cloneBufferAttribute( accessors[ target.NORMAL ] );
  35273. normalAttribute.name = attributeName;
  35274. var normal = geometry.attributes.normal;
  35275. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  35276. normalAttribute.setXYZ(
  35277. j,
  35278. normalAttribute.getX( j ) + normal.getX( j ),
  35279. normalAttribute.getY( j ) + normal.getY( j ),
  35280. normalAttribute.getZ( j ) + normal.getZ( j )
  35281. );
  35282. }
  35283. } else {
  35284. normalAttribute = geometry.attributes.normal;
  35285. }
  35286. morphNormals.push( normalAttribute );
  35287. }
  35288. }
  35289. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  35290. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  35291. mesh.updateMorphTargets();
  35292. if ( meshDef.weights !== undefined ) {
  35293. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  35294. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  35295. }
  35296. }
  35297. // .extras has user-defined data, so check that .extras.targetNames is an array.
  35298. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  35299. var targetNames = meshDef.extras.targetNames;
  35300. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  35301. mesh.morphTargetDictionary = {};
  35302. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  35303. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  35304. }
  35305. } else {
  35306. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  35307. }
  35308. }
  35309. }
  35310. function isPrimitiveEqual( a, b ) {
  35311. if ( a.indices !== b.indices ) {
  35312. return false;
  35313. }
  35314. var attribA = a.attributes || {};
  35315. var attribB = b.attributes || {};
  35316. var keysA = Object.keys( attribA );
  35317. var keysB = Object.keys( attribB );
  35318. if ( keysA.length !== keysB.length ) {
  35319. return false;
  35320. }
  35321. for ( var i = 0, il = keysA.length; i < il; i ++ ) {
  35322. var key = keysA[ i ];
  35323. if ( attribA[ key ] !== attribB[ key ] ) {
  35324. return false;
  35325. }
  35326. }
  35327. return true;
  35328. }
  35329. function getCachedGeometry( cache, newPrimitive ) {
  35330. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  35331. var cached = cache[ i ];
  35332. if ( isPrimitiveEqual( cached.primitive, newPrimitive ) ) {
  35333. return cached.promise;
  35334. }
  35335. }
  35336. return null;
  35337. }
  35338. function cloneBufferAttribute( attribute ) {
  35339. if ( attribute.isInterleavedBufferAttribute ) {
  35340. var count = attribute.count;
  35341. var itemSize = attribute.itemSize;
  35342. var array = attribute.array.slice( 0, count * itemSize );
  35343. for ( var i = 0; i < count; ++ i ) {
  35344. array[ i ] = attribute.getX( i );
  35345. if ( itemSize >= 2 ) array[ i + 1 ] = attribute.getY( i );
  35346. if ( itemSize >= 3 ) array[ i + 2 ] = attribute.getZ( i );
  35347. if ( itemSize >= 4 ) array[ i + 3 ] = attribute.getW( i );
  35348. }
  35349. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  35350. }
  35351. return attribute.clone();
  35352. }
  35353. /* GLTF PARSER */
  35354. function GLTFParser( json, extensions, options ) {
  35355. this.json = json || {};
  35356. this.extensions = extensions || {};
  35357. this.options = options || {};
  35358. // loader object cache
  35359. this.cache = new GLTFRegistry();
  35360. // BufferGeometry caching
  35361. this.primitiveCache = [];
  35362. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  35363. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  35364. this.fileLoader = new THREE.FileLoader( this.options.manager );
  35365. this.fileLoader.setResponseType( 'arraybuffer' );
  35366. }
  35367. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  35368. var json = this.json;
  35369. // Clear the loader cache
  35370. this.cache.removeAll();
  35371. // Mark the special nodes/meshes in json for efficient parse
  35372. this.markDefs();
  35373. // Fire the callback on complete
  35374. this.getMultiDependencies( [
  35375. 'scene',
  35376. 'animation',
  35377. 'camera'
  35378. ] ).then( function ( dependencies ) {
  35379. var scenes = dependencies.scenes || [];
  35380. var scene = scenes[ json.scene || 0 ];
  35381. var animations = dependencies.animations || [];
  35382. var asset = json.asset;
  35383. var cameras = dependencies.cameras || [];
  35384. onLoad( scene, scenes, cameras, animations, asset );
  35385. } ).catch( onError );
  35386. };
  35387. /**
  35388. * Marks the special nodes/meshes in json for efficient parse.
  35389. */
  35390. GLTFParser.prototype.markDefs = function () {
  35391. var nodeDefs = this.json.nodes || [];
  35392. var skinDefs = this.json.skins || [];
  35393. var meshDefs = this.json.meshes || [];
  35394. var meshReferences = {};
  35395. var meshUses = {};
  35396. // Nothing in the node definition indicates whether it is a Bone or an
  35397. // Object3D. Use the skins' joint references to mark bones.
  35398. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  35399. var joints = skinDefs[ skinIndex ].joints;
  35400. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  35401. nodeDefs[ joints[ i ] ].isBone = true;
  35402. }
  35403. }
  35404. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  35405. // avoid having more than one THREE.Mesh with the same name, count
  35406. // references and rename instances below.
  35407. //
  35408. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  35409. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  35410. var nodeDef = nodeDefs[ nodeIndex ];
  35411. if ( nodeDef.mesh !== undefined ) {
  35412. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  35413. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  35414. }
  35415. meshReferences[ nodeDef.mesh ] ++;
  35416. // Nothing in the mesh definition indicates whether it is
  35417. // a SkinnedMesh or Mesh. Use the node's mesh reference
  35418. // to mark SkinnedMesh if node has skin.
  35419. if ( nodeDef.skin !== undefined ) {
  35420. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  35421. }
  35422. }
  35423. }
  35424. this.json.meshReferences = meshReferences;
  35425. this.json.meshUses = meshUses;
  35426. };
  35427. /**
  35428. * Requests the specified dependency asynchronously, with caching.
  35429. * @param {string} type
  35430. * @param {number} index
  35431. * @return {Promise<Object>}
  35432. */
  35433. GLTFParser.prototype.getDependency = function ( type, index ) {
  35434. var cacheKey = type + ':' + index;
  35435. var dependency = this.cache.get( cacheKey );
  35436. if ( ! dependency ) {
  35437. switch ( type ) {
  35438. case 'scene':
  35439. dependency = this.loadScene( index );
  35440. break;
  35441. case 'node':
  35442. dependency = this.loadNode( index );
  35443. break;
  35444. case 'mesh':
  35445. dependency = this.loadMesh( index );
  35446. break;
  35447. case 'accessor':
  35448. dependency = this.loadAccessor( index );
  35449. break;
  35450. case 'bufferView':
  35451. dependency = this.loadBufferView( index );
  35452. break;
  35453. case 'buffer':
  35454. dependency = this.loadBuffer( index );
  35455. break;
  35456. case 'material':
  35457. dependency = this.loadMaterial( index );
  35458. break;
  35459. case 'texture':
  35460. dependency = this.loadTexture( index );
  35461. break;
  35462. case 'skin':
  35463. dependency = this.loadSkin( index );
  35464. break;
  35465. case 'animation':
  35466. dependency = this.loadAnimation( index );
  35467. break;
  35468. case 'camera':
  35469. dependency = this.loadCamera( index );
  35470. break;
  35471. default:
  35472. throw new Error( 'Unknown type: ' + type );
  35473. }
  35474. this.cache.add( cacheKey, dependency );
  35475. }
  35476. return dependency;
  35477. };
  35478. /**
  35479. * Requests all dependencies of the specified type asynchronously, with caching.
  35480. * @param {string} type
  35481. * @return {Promise<Array<Object>>}
  35482. */
  35483. GLTFParser.prototype.getDependencies = function ( type ) {
  35484. var dependencies = this.cache.get( type );
  35485. if ( ! dependencies ) {
  35486. var parser = this;
  35487. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  35488. dependencies = Promise.all( defs.map( function ( def, index ) {
  35489. return parser.getDependency( type, index );
  35490. } ) );
  35491. this.cache.add( type, dependencies );
  35492. }
  35493. return dependencies;
  35494. };
  35495. /**
  35496. * Requests all multiple dependencies of the specified types asynchronously, with caching.
  35497. * @param {Array<string>} types
  35498. * @return {Promise<Object<Array<Object>>>}
  35499. */
  35500. GLTFParser.prototype.getMultiDependencies = function ( types ) {
  35501. var results = {};
  35502. var pendings = [];
  35503. for ( var i = 0, il = types.length; i < il; i ++ ) {
  35504. var type = types[ i ];
  35505. var value = this.getDependencies( type );
  35506. value = value.then( function ( key, value ) {
  35507. results[ key ] = value;
  35508. }.bind( this, type + ( type === 'mesh' ? 'es' : 's' ) ) );
  35509. pendings.push( value );
  35510. }
  35511. return Promise.all( pendings ).then( function () {
  35512. return results;
  35513. } );
  35514. };
  35515. /**
  35516. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35517. * @param {number} bufferIndex
  35518. * @return {Promise<ArrayBuffer>}
  35519. */
  35520. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  35521. var bufferDef = this.json.buffers[ bufferIndex ];
  35522. var loader = this.fileLoader;
  35523. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  35524. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  35525. }
  35526. // If present, GLB container is required to be the first buffer.
  35527. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  35528. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  35529. }
  35530. var options = this.options;
  35531. return new Promise( function ( resolve, reject ) {
  35532. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  35533. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  35534. } );
  35535. } );
  35536. };
  35537. /**
  35538. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35539. * @param {number} bufferViewIndex
  35540. * @return {Promise<ArrayBuffer>}
  35541. */
  35542. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  35543. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  35544. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  35545. var byteLength = bufferViewDef.byteLength || 0;
  35546. var byteOffset = bufferViewDef.byteOffset || 0;
  35547. return buffer.slice( byteOffset, byteOffset + byteLength );
  35548. } );
  35549. };
  35550. /**
  35551. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  35552. * @param {number} accessorIndex
  35553. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  35554. */
  35555. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  35556. var parser = this;
  35557. var json = this.json;
  35558. var accessorDef = this.json.accessors[ accessorIndex ];
  35559. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  35560. // Ignore empty accessors, which may be used to declare runtime
  35561. // information about attributes coming from another source (e.g. Draco
  35562. // compression extension).
  35563. return null;
  35564. }
  35565. var pendingBufferViews = [];
  35566. if ( accessorDef.bufferView !== undefined ) {
  35567. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  35568. } else {
  35569. pendingBufferViews.push( null );
  35570. }
  35571. if ( accessorDef.sparse !== undefined ) {
  35572. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  35573. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  35574. }
  35575. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  35576. var bufferView = bufferViews[ 0 ];
  35577. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  35578. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  35579. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  35580. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  35581. var itemBytes = elementBytes * itemSize;
  35582. var byteOffset = accessorDef.byteOffset || 0;
  35583. var byteStride = json.bufferViews[ accessorDef.bufferView ].byteStride;
  35584. var normalized = accessorDef.normalized === true;
  35585. var array, bufferAttribute;
  35586. // The buffer is not interleaved if the stride is the item size in bytes.
  35587. if ( byteStride && byteStride !== itemBytes ) {
  35588. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType;
  35589. var ib = parser.cache.get( ibCacheKey );
  35590. if ( ! ib ) {
  35591. // Use the full buffer if it's interleaved.
  35592. array = new TypedArray( bufferView );
  35593. // Integer parameters to IB/IBA are in array elements, not bytes.
  35594. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  35595. parser.cache.add( ibCacheKey, ib );
  35596. }
  35597. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, byteOffset / elementBytes, normalized );
  35598. } else {
  35599. if ( bufferView === null ) {
  35600. array = new TypedArray( accessorDef.count * itemSize );
  35601. } else {
  35602. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  35603. }
  35604. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  35605. }
  35606. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  35607. if ( accessorDef.sparse !== undefined ) {
  35608. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  35609. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  35610. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  35611. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  35612. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  35613. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  35614. if ( bufferView !== null ) {
  35615. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  35616. bufferAttribute.setArray( bufferAttribute.array.slice() );
  35617. }
  35618. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  35619. var index = sparseIndices[ i ];
  35620. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  35621. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  35622. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  35623. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  35624. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  35625. }
  35626. }
  35627. return bufferAttribute;
  35628. } );
  35629. };
  35630. /**
  35631. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  35632. * @param {number} textureIndex
  35633. * @return {Promise<THREE.Texture>}
  35634. */
  35635. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  35636. var parser = this;
  35637. var json = this.json;
  35638. var options = this.options;
  35639. var textureLoader = this.textureLoader;
  35640. var URL = window.URL || window.webkitURL;
  35641. var textureDef = json.textures[ textureIndex ];
  35642. var textureExtensions = textureDef.extensions || {};
  35643. var source;
  35644. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  35645. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  35646. } else {
  35647. source = json.images[ textureDef.source ];
  35648. }
  35649. var sourceURI = source.uri;
  35650. var isObjectURL = false;
  35651. if ( source.bufferView !== undefined ) {
  35652. // Load binary image data from bufferView, if provided.
  35653. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  35654. isObjectURL = true;
  35655. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  35656. sourceURI = URL.createObjectURL( blob );
  35657. return sourceURI;
  35658. } );
  35659. }
  35660. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  35661. // Load Texture resource.
  35662. var loader = THREE.Loader.Handlers.get( sourceURI );
  35663. if ( ! loader ) {
  35664. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  35665. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  35666. : textureLoader;
  35667. }
  35668. return new Promise( function ( resolve, reject ) {
  35669. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  35670. } );
  35671. } ).then( function ( texture ) {
  35672. // Clean up resources and configure Texture.
  35673. if ( isObjectURL === true ) {
  35674. URL.revokeObjectURL( sourceURI );
  35675. }
  35676. texture.flipY = false;
  35677. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  35678. // .format of dds texture is set in DDSLoader
  35679. if ( ! textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  35680. texture.format = textureDef.format !== undefined ? WEBGL_TEXTURE_FORMATS[ textureDef.format ] : THREE.RGBAFormat;
  35681. }
  35682. if ( textureDef.internalFormat !== undefined && texture.format !== WEBGL_TEXTURE_FORMATS[ textureDef.internalFormat ] ) {
  35683. console.warn( 'THREE.GLTFLoader: Three.js does not support texture internalFormat which is different from texture format. ' +
  35684. 'internalFormat will be forced to be the same value as format.' );
  35685. }
  35686. texture.type = textureDef.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ textureDef.type ] : THREE.UnsignedByteType;
  35687. var samplers = json.samplers || {};
  35688. var sampler = samplers[ textureDef.sampler ] || {};
  35689. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  35690. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  35691. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  35692. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  35693. return texture;
  35694. } );
  35695. };
  35696. /**
  35697. * Asynchronously assigns a texture to the given material parameters.
  35698. * @param {Object} materialParams
  35699. * @param {string} textureName
  35700. * @param {number} textureIndex
  35701. * @return {Promise}
  35702. */
  35703. GLTFParser.prototype.assignTexture = function ( materialParams, textureName, textureIndex ) {
  35704. return this.getDependency( 'texture', textureIndex ).then( function ( texture ) {
  35705. materialParams[ textureName ] = texture;
  35706. } );
  35707. };
  35708. /**
  35709. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  35710. * @param {number} materialIndex
  35711. * @return {Promise<THREE.Material>}
  35712. */
  35713. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  35714. var parser = this;
  35715. var json = this.json;
  35716. var extensions = this.extensions;
  35717. var materialDef = this.json.materials[ materialIndex ];
  35718. var materialType;
  35719. var materialParams = {};
  35720. var materialExtensions = materialDef.extensions || {};
  35721. var pending = [];
  35722. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  35723. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  35724. materialType = sgExtension.getMaterialType( materialDef );
  35725. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  35726. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  35727. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  35728. materialType = kmuExtension.getMaterialType( materialDef );
  35729. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  35730. } else {
  35731. // Specification:
  35732. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  35733. materialType = THREE.MeshStandardMaterial;
  35734. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  35735. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  35736. materialParams.opacity = 1.0;
  35737. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  35738. var array = metallicRoughness.baseColorFactor;
  35739. materialParams.color.fromArray( array );
  35740. materialParams.opacity = array[ 3 ];
  35741. }
  35742. if ( metallicRoughness.baseColorTexture !== undefined ) {
  35743. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  35744. }
  35745. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  35746. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  35747. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  35748. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  35749. pending.push( parser.assignTexture( materialParams, 'metalnessMap', textureIndex ) );
  35750. pending.push( parser.assignTexture( materialParams, 'roughnessMap', textureIndex ) );
  35751. }
  35752. }
  35753. if ( materialDef.doubleSided === true ) {
  35754. materialParams.side = THREE.DoubleSide;
  35755. }
  35756. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  35757. if ( alphaMode === ALPHA_MODES.BLEND ) {
  35758. materialParams.transparent = true;
  35759. } else {
  35760. materialParams.transparent = false;
  35761. if ( alphaMode === ALPHA_MODES.MASK ) {
  35762. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  35763. }
  35764. }
  35765. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
  35766. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture.index ) );
  35767. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  35768. if ( materialDef.normalTexture.scale !== undefined ) {
  35769. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  35770. }
  35771. }
  35772. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
  35773. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture.index ) );
  35774. if ( materialDef.occlusionTexture.strength !== undefined ) {
  35775. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  35776. }
  35777. }
  35778. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial) {
  35779. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  35780. }
  35781. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
  35782. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture.index ) );
  35783. }
  35784. return Promise.all( pending ).then( function () {
  35785. var material;
  35786. if ( materialType === THREE.ShaderMaterial ) {
  35787. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  35788. } else {
  35789. material = new materialType( materialParams );
  35790. }
  35791. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  35792. // Normal map textures use OpenGL conventions:
  35793. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  35794. if ( material.normalScale ) {
  35795. material.normalScale.y = - material.normalScale.y;
  35796. }
  35797. // emissiveTexture and baseColorTexture use sRGB encoding.
  35798. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  35799. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  35800. if ( materialDef.extras ) material.userData = materialDef.extras;
  35801. return material;
  35802. } );
  35803. };
  35804. /**
  35805. * @param {THREE.BufferGeometry} geometry
  35806. * @param {GLTF.Primitive} primitiveDef
  35807. * @param {Array<THREE.BufferAttribute>} accessors
  35808. */
  35809. function addPrimitiveAttributes ( geometry, primitiveDef, accessors ) {
  35810. var attributes = primitiveDef.attributes;
  35811. for ( var gltfAttributeName in attributes ) {
  35812. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ];
  35813. var bufferAttribute = accessors[ attributes[ gltfAttributeName ] ];
  35814. // Skip attributes already provided by e.g. Draco extension.
  35815. if ( !threeAttributeName ) continue;
  35816. if ( threeAttributeName in geometry.attributes ) continue;
  35817. geometry.addAttribute( threeAttributeName, bufferAttribute );
  35818. }
  35819. if ( primitiveDef.indices !== undefined && !geometry.index ) {
  35820. geometry.setIndex( accessors[ primitiveDef.indices ] );
  35821. }
  35822. }
  35823. /**
  35824. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  35825. * @param {Array<Object>} primitives
  35826. * @return {Promise<Array<THREE.BufferGeometry>>}
  35827. */
  35828. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  35829. var parser = this;
  35830. var extensions = this.extensions;
  35831. var cache = this.primitiveCache;
  35832. return this.getDependencies( 'accessor' ).then( function ( accessors ) {
  35833. var pending = [];
  35834. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  35835. var primitive = primitives[ i ];
  35836. // See if we've already created this geometry
  35837. var cached = getCachedGeometry( cache, primitive );
  35838. if ( cached ) {
  35839. // Use the cached geometry if it exists
  35840. pending.push( cached );
  35841. } else if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  35842. // Use DRACO geometry if available
  35843. var geometryPromise = extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  35844. .decodePrimitive( primitive, parser )
  35845. .then( function ( geometry ) {
  35846. addPrimitiveAttributes( geometry, primitive, accessors );
  35847. return geometry;
  35848. } );
  35849. cache.push( { primitive: primitive, promise: geometryPromise } );
  35850. pending.push( geometryPromise );
  35851. } else {
  35852. // Otherwise create a new geometry
  35853. var geometry = new THREE.BufferGeometry();
  35854. addPrimitiveAttributes( geometry, primitive, accessors );
  35855. var geometryPromise = Promise.resolve( geometry );
  35856. // Cache this geometry
  35857. cache.push( {
  35858. primitive: primitive,
  35859. promise: geometryPromise
  35860. } );
  35861. pending.push( geometryPromise );
  35862. }
  35863. }
  35864. return Promise.all( pending );
  35865. } );
  35866. };
  35867. /**
  35868. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  35869. * @param {number} meshIndex
  35870. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  35871. */
  35872. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  35873. var scope = this;
  35874. var json = this.json;
  35875. var extensions = this.extensions;
  35876. var meshDef = this.json.meshes[ meshIndex ];
  35877. return this.getMultiDependencies( [
  35878. 'accessor',
  35879. 'material'
  35880. ] ).then( function ( dependencies ) {
  35881. var group = new THREE.Group();
  35882. var primitives = meshDef.primitives;
  35883. return scope.loadGeometries( primitives ).then( function ( geometries ) {
  35884. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  35885. var primitive = primitives[ i ];
  35886. var geometry = geometries[ i ];
  35887. var material = primitive.material === undefined
  35888. ? createDefaultMaterial()
  35889. : dependencies.materials[ primitive.material ];
  35890. if ( material.aoMap
  35891. && geometry.attributes.uv2 === undefined
  35892. && geometry.attributes.uv !== undefined ) {
  35893. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  35894. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  35895. }
  35896. // If the material will be modified later on, clone it now.
  35897. var useVertexColors = geometry.attributes.color !== undefined;
  35898. var useFlatShading = geometry.attributes.normal === undefined;
  35899. var useSkinning = meshDef.isSkinnedMesh === true;
  35900. var useMorphTargets = primitive.targets !== undefined;
  35901. if ( useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  35902. if ( material.isGLTFSpecularGlossinessMaterial ) {
  35903. var specGlossExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  35904. material = specGlossExtension.cloneMaterial( material );
  35905. } else {
  35906. material = material.clone();
  35907. }
  35908. }
  35909. if ( useVertexColors ) {
  35910. material.vertexColors = THREE.VertexColors;
  35911. material.needsUpdate = true;
  35912. }
  35913. if ( useFlatShading ) {
  35914. material.flatShading = true;
  35915. }
  35916. var mesh;
  35917. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  35918. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  35919. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  35920. primitive.mode === undefined ) {
  35921. if ( useSkinning ) {
  35922. mesh = new THREE.SkinnedMesh( geometry, material );
  35923. material.skinning = true;
  35924. } else {
  35925. mesh = new THREE.Mesh( geometry, material );
  35926. }
  35927. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  35928. mesh.drawMode = THREE.TriangleStripDrawMode;
  35929. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  35930. mesh.drawMode = THREE.TriangleFanDrawMode;
  35931. }
  35932. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ||
  35933. primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ||
  35934. primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  35935. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  35936. var lineMaterial = scope.cache.get( cacheKey );
  35937. if ( ! lineMaterial ) {
  35938. lineMaterial = new THREE.LineBasicMaterial();
  35939. THREE.Material.prototype.copy.call( lineMaterial, material );
  35940. lineMaterial.color.copy( material.color );
  35941. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  35942. scope.cache.add( cacheKey, lineMaterial );
  35943. }
  35944. material = lineMaterial;
  35945. if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  35946. mesh = new THREE.LineSegments( geometry, material );
  35947. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  35948. mesh = new THREE.Line( geometry, material );
  35949. } else {
  35950. mesh = new THREE.LineLoop( geometry, material );
  35951. }
  35952. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  35953. var cacheKey = 'PointsMaterial:' + material.uuid;
  35954. var pointsMaterial = scope.cache.get( cacheKey );
  35955. if ( ! pointsMaterial ) {
  35956. pointsMaterial = new THREE.PointsMaterial();
  35957. THREE.Material.prototype.copy.call( pointsMaterial, material );
  35958. pointsMaterial.color.copy( material.color );
  35959. pointsMaterial.map = material.map;
  35960. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  35961. scope.cache.add( cacheKey, pointsMaterial );
  35962. }
  35963. material = pointsMaterial;
  35964. mesh = new THREE.Points( geometry, material );
  35965. } else {
  35966. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  35967. }
  35968. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  35969. if ( useMorphTargets ) {
  35970. addMorphTargets( mesh, meshDef, primitive, dependencies.accessors );
  35971. material.morphTargets = true;
  35972. if ( mesh.geometry.morphAttributes.normal !== undefined ) material.morphNormals = true;
  35973. }
  35974. if ( meshDef.extras !== undefined ) mesh.userData = meshDef.extras;
  35975. if ( primitive.extras !== undefined ) mesh.geometry.userData = primitive.extras;
  35976. // for Specular-Glossiness.
  35977. if ( material.isGLTFSpecularGlossinessMaterial === true ) {
  35978. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  35979. }
  35980. if ( primitives.length > 1 ) {
  35981. mesh.name += '_' + i;
  35982. group.add( mesh );
  35983. } else {
  35984. return mesh;
  35985. }
  35986. }
  35987. return group;
  35988. } );
  35989. } );
  35990. };
  35991. /**
  35992. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  35993. * @param {number} cameraIndex
  35994. * @return {Promise<THREE.Camera>}
  35995. */
  35996. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  35997. var camera;
  35998. var cameraDef = this.json.cameras[ cameraIndex ];
  35999. var params = cameraDef[ cameraDef.type ];
  36000. if ( ! params ) {
  36001. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  36002. return;
  36003. }
  36004. if ( cameraDef.type === 'perspective' ) {
  36005. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  36006. } else if ( cameraDef.type === 'orthographic' ) {
  36007. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  36008. }
  36009. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  36010. if ( cameraDef.extras ) camera.userData = cameraDef.extras;
  36011. return Promise.resolve( camera );
  36012. };
  36013. /**
  36014. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  36015. * @param {number} skinIndex
  36016. * @return {Promise<Object>}
  36017. */
  36018. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  36019. var skinDef = this.json.skins[ skinIndex ];
  36020. var skinEntry = { joints: skinDef.joints };
  36021. if ( skinDef.inverseBindMatrices === undefined ) {
  36022. return Promise.resolve( skinEntry );
  36023. }
  36024. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  36025. skinEntry.inverseBindMatrices = accessor;
  36026. return skinEntry;
  36027. } );
  36028. };
  36029. /**
  36030. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  36031. * @param {number} animationIndex
  36032. * @return {Promise<THREE.AnimationClip>}
  36033. */
  36034. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  36035. var json = this.json;
  36036. var animationDef = this.json.animations[ animationIndex ];
  36037. return this.getMultiDependencies( [
  36038. 'accessor',
  36039. 'node'
  36040. ] ).then( function ( dependencies ) {
  36041. var tracks = [];
  36042. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  36043. var channel = animationDef.channels[ i ];
  36044. var sampler = animationDef.samplers[ channel.sampler ];
  36045. if ( sampler ) {
  36046. var target = channel.target;
  36047. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  36048. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  36049. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  36050. var inputAccessor = dependencies.accessors[ input ];
  36051. var outputAccessor = dependencies.accessors[ output ];
  36052. var node = dependencies.nodes[ name ];
  36053. if ( node ) {
  36054. node.updateMatrix();
  36055. node.matrixAutoUpdate = true;
  36056. var TypedKeyframeTrack;
  36057. switch ( PATH_PROPERTIES[ target.path ] ) {
  36058. case PATH_PROPERTIES.weights:
  36059. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  36060. break;
  36061. case PATH_PROPERTIES.rotation:
  36062. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  36063. break;
  36064. case PATH_PROPERTIES.position:
  36065. case PATH_PROPERTIES.scale:
  36066. default:
  36067. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  36068. break;
  36069. }
  36070. var targetName = node.name ? node.name : node.uuid;
  36071. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  36072. var targetNames = [];
  36073. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  36074. // node should be THREE.Group here but
  36075. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  36076. // the property of a mesh object under node.
  36077. // So finding targets here.
  36078. node.traverse( function ( object ) {
  36079. if ( object.isMesh === true && object.material.morphTargets === true ) {
  36080. targetNames.push( object.name ? object.name : object.uuid );
  36081. }
  36082. } );
  36083. } else {
  36084. targetNames.push( targetName );
  36085. }
  36086. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  36087. // buffers before creating a truncated copy to keep. Because buffers may
  36088. // be reused by other tracks, make copies here.
  36089. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  36090. var track = new TypedKeyframeTrack(
  36091. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  36092. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  36093. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  36094. interpolation
  36095. );
  36096. // Here is the trick to enable custom interpolation.
  36097. // Overrides .createInterpolant in a factory method which creates custom interpolation.
  36098. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  36099. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  36100. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  36101. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  36102. // must be divided by three to get the interpolant's sampleSize argument.
  36103. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  36104. };
  36105. // Workaround, provide an alternate way to know if the interpolant type is cubis spline to track.
  36106. // track.getInterpolation() doesn't return valid value for custom interpolant.
  36107. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  36108. }
  36109. tracks.push( track );
  36110. }
  36111. }
  36112. }
  36113. }
  36114. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  36115. return new THREE.AnimationClip( name, undefined, tracks );
  36116. } );
  36117. };
  36118. /**
  36119. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  36120. * @param {number} nodeIndex
  36121. * @return {Promise<THREE.Object3D>}
  36122. */
  36123. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  36124. var json = this.json;
  36125. var extensions = this.extensions;
  36126. var meshReferences = this.json.meshReferences;
  36127. var meshUses = this.json.meshUses;
  36128. var nodeDef = this.json.nodes[ nodeIndex ];
  36129. return this.getMultiDependencies( [
  36130. 'mesh',
  36131. 'skin',
  36132. 'camera',
  36133. 'light'
  36134. ] ).then( function ( dependencies ) {
  36135. var node;
  36136. if ( nodeDef.isBone === true ) {
  36137. node = new THREE.Bone();
  36138. } else if ( nodeDef.mesh !== undefined ) {
  36139. var mesh = dependencies.meshes[ nodeDef.mesh ];
  36140. node = mesh.clone();
  36141. // for Specular-Glossiness
  36142. if ( mesh.isGroup === true ) {
  36143. for ( var i = 0, il = mesh.children.length; i < il; i ++ ) {
  36144. var child = mesh.children[ i ];
  36145. if ( child.material && child.material.isGLTFSpecularGlossinessMaterial === true ) {
  36146. node.children[ i ].onBeforeRender = child.onBeforeRender;
  36147. }
  36148. }
  36149. } else {
  36150. if ( mesh.material && mesh.material.isGLTFSpecularGlossinessMaterial === true ) {
  36151. node.onBeforeRender = mesh.onBeforeRender;
  36152. }
  36153. }
  36154. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  36155. node.name += '_instance_' + meshUses[ nodeDef.mesh ] ++;
  36156. }
  36157. } else if ( nodeDef.camera !== undefined ) {
  36158. node = dependencies.cameras[ nodeDef.camera ];
  36159. } else if ( nodeDef.extensions
  36160. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  36161. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  36162. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  36163. node = lights[ nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ];
  36164. } else {
  36165. node = new THREE.Object3D();
  36166. }
  36167. if ( nodeDef.name !== undefined ) {
  36168. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  36169. }
  36170. if ( nodeDef.extras ) node.userData = nodeDef.extras;
  36171. if ( nodeDef.matrix !== undefined ) {
  36172. var matrix = new THREE.Matrix4();
  36173. matrix.fromArray( nodeDef.matrix );
  36174. node.applyMatrix( matrix );
  36175. } else {
  36176. if ( nodeDef.translation !== undefined ) {
  36177. node.position.fromArray( nodeDef.translation );
  36178. }
  36179. if ( nodeDef.rotation !== undefined ) {
  36180. node.quaternion.fromArray( nodeDef.rotation );
  36181. }
  36182. if ( nodeDef.scale !== undefined ) {
  36183. node.scale.fromArray( nodeDef.scale );
  36184. }
  36185. }
  36186. return node;
  36187. } );
  36188. };
  36189. /**
  36190. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  36191. * @param {number} sceneIndex
  36192. * @return {Promise<THREE.Scene>}
  36193. */
  36194. GLTFParser.prototype.loadScene = function () {
  36195. // scene node hierachy builder
  36196. function buildNodeHierachy( nodeId, parentObject, json, allNodes, skins ) {
  36197. var node = allNodes[ nodeId ];
  36198. var nodeDef = json.nodes[ nodeId ];
  36199. // build skeleton here as well
  36200. if ( nodeDef.skin !== undefined ) {
  36201. var meshes = node.isGroup === true ? node.children : [ node ];
  36202. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  36203. var mesh = meshes[ i ];
  36204. var skinEntry = skins[ nodeDef.skin ];
  36205. var bones = [];
  36206. var boneInverses = [];
  36207. for ( var j = 0, jl = skinEntry.joints.length; j < jl; j ++ ) {
  36208. var jointId = skinEntry.joints[ j ];
  36209. var jointNode = allNodes[ jointId ];
  36210. if ( jointNode ) {
  36211. bones.push( jointNode );
  36212. var mat = new THREE.Matrix4();
  36213. if ( skinEntry.inverseBindMatrices !== undefined ) {
  36214. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  36215. }
  36216. boneInverses.push( mat );
  36217. } else {
  36218. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', jointId );
  36219. }
  36220. }
  36221. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  36222. }
  36223. }
  36224. // build node hierachy
  36225. parentObject.add( node );
  36226. if ( nodeDef.children ) {
  36227. var children = nodeDef.children;
  36228. for ( var i = 0, il = children.length; i < il; i ++ ) {
  36229. var child = children[ i ];
  36230. buildNodeHierachy( child, node, json, allNodes, skins );
  36231. }
  36232. }
  36233. }
  36234. return function loadScene( sceneIndex ) {
  36235. var json = this.json;
  36236. var extensions = this.extensions;
  36237. var sceneDef = this.json.scenes[ sceneIndex ];
  36238. return this.getMultiDependencies( [
  36239. 'node',
  36240. 'skin'
  36241. ] ).then( function ( dependencies ) {
  36242. var scene = new THREE.Scene();
  36243. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  36244. if ( sceneDef.extras ) scene.userData = sceneDef.extras;
  36245. var nodeIds = sceneDef.nodes || [];
  36246. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  36247. buildNodeHierachy( nodeIds[ i ], scene, json, dependencies.nodes, dependencies.skins );
  36248. }
  36249. // Ambient lighting, if present, is always attached to the scene root.
  36250. if ( sceneDef.extensions
  36251. && sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  36252. && sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  36253. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  36254. scene.add( lights[ sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  36255. }
  36256. return scene;
  36257. } );
  36258. };
  36259. }();
  36260. return GLTFLoader;
  36261. } )();
  36262. },{}],43:[function(_dereq_,module,exports){
  36263. /**
  36264. * Loads a Wavefront .mtl file specifying materials
  36265. *
  36266. * @author angelxuanchang
  36267. */
  36268. THREE.MTLLoader = function ( manager ) {
  36269. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  36270. };
  36271. THREE.MTLLoader.prototype = {
  36272. constructor: THREE.MTLLoader,
  36273. /**
  36274. * Loads and parses a MTL asset from a URL.
  36275. *
  36276. * @param {String} url - URL to the MTL file.
  36277. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  36278. * @param {Function} [onProgress] - Callback for download progress.
  36279. * @param {Function} [onError] - Callback for download errors.
  36280. *
  36281. * @see setPath setTexturePath
  36282. *
  36283. * @note In order for relative texture references to resolve correctly
  36284. * you must call setPath and/or setTexturePath explicitly prior to load.
  36285. */
  36286. load: function ( url, onLoad, onProgress, onError ) {
  36287. var scope = this;
  36288. var loader = new THREE.FileLoader( this.manager );
  36289. loader.setPath( this.path );
  36290. loader.load( url, function ( text ) {
  36291. onLoad( scope.parse( text ) );
  36292. }, onProgress, onError );
  36293. },
  36294. /**
  36295. * Set base path for resolving references.
  36296. * If set this path will be prepended to each loaded and found reference.
  36297. *
  36298. * @see setTexturePath
  36299. * @param {String} path
  36300. * @return {THREE.MTLLoader}
  36301. *
  36302. * @example
  36303. * mtlLoader.setPath( 'assets/obj/' );
  36304. * mtlLoader.load( 'my.mtl', ... );
  36305. */
  36306. setPath: function ( path ) {
  36307. this.path = path;
  36308. return this;
  36309. },
  36310. /**
  36311. * Set base path for resolving texture references.
  36312. * If set this path will be prepended found texture reference.
  36313. * If not set and setPath is, it will be used as texture base path.
  36314. *
  36315. * @see setPath
  36316. * @param {String} path
  36317. * @return {THREE.MTLLoader}
  36318. *
  36319. * @example
  36320. * mtlLoader.setPath( 'assets/obj/' );
  36321. * mtlLoader.setTexturePath( 'assets/textures/' );
  36322. * mtlLoader.load( 'my.mtl', ... );
  36323. */
  36324. setTexturePath: function ( path ) {
  36325. this.texturePath = path;
  36326. return this;
  36327. },
  36328. setBaseUrl: function ( path ) {
  36329. console.warn( 'THREE.MTLLoader: .setBaseUrl() is deprecated. Use .setTexturePath( path ) for texture path or .setPath( path ) for general base path instead.' );
  36330. return this.setTexturePath( path );
  36331. },
  36332. setCrossOrigin: function ( value ) {
  36333. this.crossOrigin = value;
  36334. return this;
  36335. },
  36336. setMaterialOptions: function ( value ) {
  36337. this.materialOptions = value;
  36338. return this;
  36339. },
  36340. /**
  36341. * Parses a MTL file.
  36342. *
  36343. * @param {String} text - Content of MTL file
  36344. * @return {THREE.MTLLoader.MaterialCreator}
  36345. *
  36346. * @see setPath setTexturePath
  36347. *
  36348. * @note In order for relative texture references to resolve correctly
  36349. * you must call setPath and/or setTexturePath explicitly prior to parse.
  36350. */
  36351. parse: function ( text ) {
  36352. var lines = text.split( '\n' );
  36353. var info = {};
  36354. var delimiter_pattern = /\s+/;
  36355. var materialsInfo = {};
  36356. for ( var i = 0; i < lines.length; i ++ ) {
  36357. var line = lines[ i ];
  36358. line = line.trim();
  36359. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  36360. // Blank line or comment ignore
  36361. continue;
  36362. }
  36363. var pos = line.indexOf( ' ' );
  36364. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  36365. key = key.toLowerCase();
  36366. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  36367. value = value.trim();
  36368. if ( key === 'newmtl' ) {
  36369. // New material
  36370. info = { name: value };
  36371. materialsInfo[ value ] = info;
  36372. } else if ( info ) {
  36373. if ( key === 'ka' || key === 'kd' || key === 'ks' ) {
  36374. var ss = value.split( delimiter_pattern, 3 );
  36375. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  36376. } else {
  36377. info[ key ] = value;
  36378. }
  36379. }
  36380. }
  36381. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.texturePath || this.path, this.materialOptions );
  36382. materialCreator.setCrossOrigin( this.crossOrigin );
  36383. materialCreator.setManager( this.manager );
  36384. materialCreator.setMaterials( materialsInfo );
  36385. return materialCreator;
  36386. }
  36387. };
  36388. /**
  36389. * Create a new THREE-MTLLoader.MaterialCreator
  36390. * @param baseUrl - Url relative to which textures are loaded
  36391. * @param options - Set of options on how to construct the materials
  36392. * side: Which side to apply the material
  36393. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  36394. * wrap: What type of wrapping to apply for textures
  36395. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  36396. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  36397. * Default: false, assumed to be already normalized
  36398. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  36399. * Default: false
  36400. * @constructor
  36401. */
  36402. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  36403. this.baseUrl = baseUrl || '';
  36404. this.options = options;
  36405. this.materialsInfo = {};
  36406. this.materials = {};
  36407. this.materialsArray = [];
  36408. this.nameLookup = {};
  36409. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  36410. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  36411. };
  36412. THREE.MTLLoader.MaterialCreator.prototype = {
  36413. constructor: THREE.MTLLoader.MaterialCreator,
  36414. crossOrigin: 'Anonymous',
  36415. setCrossOrigin: function ( value ) {
  36416. this.crossOrigin = value;
  36417. },
  36418. setManager: function ( value ) {
  36419. this.manager = value;
  36420. },
  36421. setMaterials: function ( materialsInfo ) {
  36422. this.materialsInfo = this.convert( materialsInfo );
  36423. this.materials = {};
  36424. this.materialsArray = [];
  36425. this.nameLookup = {};
  36426. },
  36427. convert: function ( materialsInfo ) {
  36428. if ( ! this.options ) return materialsInfo;
  36429. var converted = {};
  36430. for ( var mn in materialsInfo ) {
  36431. // Convert materials info into normalized form based on options
  36432. var mat = materialsInfo[ mn ];
  36433. var covmat = {};
  36434. converted[ mn ] = covmat;
  36435. for ( var prop in mat ) {
  36436. var save = true;
  36437. var value = mat[ prop ];
  36438. var lprop = prop.toLowerCase();
  36439. switch ( lprop ) {
  36440. case 'kd':
  36441. case 'ka':
  36442. case 'ks':
  36443. // Diffuse color (color under white light) using RGB values
  36444. if ( this.options && this.options.normalizeRGB ) {
  36445. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  36446. }
  36447. if ( this.options && this.options.ignoreZeroRGBs ) {
  36448. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  36449. // ignore
  36450. save = false;
  36451. }
  36452. }
  36453. break;
  36454. default:
  36455. break;
  36456. }
  36457. if ( save ) {
  36458. covmat[ lprop ] = value;
  36459. }
  36460. }
  36461. }
  36462. return converted;
  36463. },
  36464. preload: function () {
  36465. for ( var mn in this.materialsInfo ) {
  36466. this.create( mn );
  36467. }
  36468. },
  36469. getIndex: function ( materialName ) {
  36470. return this.nameLookup[ materialName ];
  36471. },
  36472. getAsArray: function () {
  36473. var index = 0;
  36474. for ( var mn in this.materialsInfo ) {
  36475. this.materialsArray[ index ] = this.create( mn );
  36476. this.nameLookup[ mn ] = index;
  36477. index ++;
  36478. }
  36479. return this.materialsArray;
  36480. },
  36481. create: function ( materialName ) {
  36482. if ( this.materials[ materialName ] === undefined ) {
  36483. this.createMaterial_( materialName );
  36484. }
  36485. return this.materials[ materialName ];
  36486. },
  36487. createMaterial_: function ( materialName ) {
  36488. // Create material
  36489. var scope = this;
  36490. var mat = this.materialsInfo[ materialName ];
  36491. var params = {
  36492. name: materialName,
  36493. side: this.side
  36494. };
  36495. function resolveURL( baseUrl, url ) {
  36496. if ( typeof url !== 'string' || url === '' )
  36497. return '';
  36498. // Absolute URL
  36499. if ( /^https?:\/\//i.test( url ) ) return url;
  36500. return baseUrl + url;
  36501. }
  36502. function setMapForType( mapType, value ) {
  36503. if ( params[ mapType ] ) return; // Keep the first encountered texture
  36504. var texParams = scope.getTextureParams( value, params );
  36505. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  36506. map.repeat.copy( texParams.scale );
  36507. map.offset.copy( texParams.offset );
  36508. map.wrapS = scope.wrap;
  36509. map.wrapT = scope.wrap;
  36510. params[ mapType ] = map;
  36511. }
  36512. for ( var prop in mat ) {
  36513. var value = mat[ prop ];
  36514. var n;
  36515. if ( value === '' ) continue;
  36516. switch ( prop.toLowerCase() ) {
  36517. // Ns is material specular exponent
  36518. case 'kd':
  36519. // Diffuse color (color under white light) using RGB values
  36520. params.color = new THREE.Color().fromArray( value );
  36521. break;
  36522. case 'ks':
  36523. // Specular color (color when light is reflected from shiny surface) using RGB values
  36524. params.specular = new THREE.Color().fromArray( value );
  36525. break;
  36526. case 'map_kd':
  36527. // Diffuse texture map
  36528. setMapForType( "map", value );
  36529. break;
  36530. case 'map_ks':
  36531. // Specular map
  36532. setMapForType( "specularMap", value );
  36533. break;
  36534. case 'norm':
  36535. setMapForType( "normalMap", value );
  36536. break;
  36537. case 'map_bump':
  36538. case 'bump':
  36539. // Bump texture map
  36540. setMapForType( "bumpMap", value );
  36541. break;
  36542. case 'ns':
  36543. // The specular exponent (defines the focus of the specular highlight)
  36544. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  36545. params.shininess = parseFloat( value );
  36546. break;
  36547. case 'd':
  36548. n = parseFloat( value );
  36549. if ( n < 1 ) {
  36550. params.opacity = n;
  36551. params.transparent = true;
  36552. }
  36553. break;
  36554. case 'tr':
  36555. n = parseFloat( value );
  36556. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  36557. if ( n > 0 ) {
  36558. params.opacity = 1 - n;
  36559. params.transparent = true;
  36560. }
  36561. break;
  36562. default:
  36563. break;
  36564. }
  36565. }
  36566. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  36567. return this.materials[ materialName ];
  36568. },
  36569. getTextureParams: function ( value, matParams ) {
  36570. var texParams = {
  36571. scale: new THREE.Vector2( 1, 1 ),
  36572. offset: new THREE.Vector2( 0, 0 )
  36573. };
  36574. var items = value.split( /\s+/ );
  36575. var pos;
  36576. pos = items.indexOf( '-bm' );
  36577. if ( pos >= 0 ) {
  36578. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  36579. items.splice( pos, 2 );
  36580. }
  36581. pos = items.indexOf( '-s' );
  36582. if ( pos >= 0 ) {
  36583. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36584. items.splice( pos, 4 ); // we expect 3 parameters here!
  36585. }
  36586. pos = items.indexOf( '-o' );
  36587. if ( pos >= 0 ) {
  36588. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36589. items.splice( pos, 4 ); // we expect 3 parameters here!
  36590. }
  36591. texParams.url = items.join( ' ' ).trim();
  36592. return texParams;
  36593. },
  36594. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  36595. var texture;
  36596. var loader = THREE.Loader.Handlers.get( url );
  36597. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  36598. if ( loader === null ) {
  36599. loader = new THREE.TextureLoader( manager );
  36600. }
  36601. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  36602. texture = loader.load( url, onLoad, onProgress, onError );
  36603. if ( mapping !== undefined ) texture.mapping = mapping;
  36604. return texture;
  36605. }
  36606. };
  36607. },{}],44:[function(_dereq_,module,exports){
  36608. /**
  36609. * @author mrdoob / http://mrdoob.com/
  36610. */
  36611. THREE.OBJLoader = ( function () {
  36612. // o object_name | g group_name
  36613. var object_pattern = /^[og]\s*(.+)?/;
  36614. // mtllib file_reference
  36615. var material_library_pattern = /^mtllib /;
  36616. // usemtl material_name
  36617. var material_use_pattern = /^usemtl /;
  36618. function ParserState() {
  36619. var state = {
  36620. objects: [],
  36621. object: {},
  36622. vertices: [],
  36623. normals: [],
  36624. colors: [],
  36625. uvs: [],
  36626. materialLibraries: [],
  36627. startObject: function ( name, fromDeclaration ) {
  36628. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  36629. // file. We need to use it for the first parsed g/o to keep things in sync.
  36630. if ( this.object && this.object.fromDeclaration === false ) {
  36631. this.object.name = name;
  36632. this.object.fromDeclaration = ( fromDeclaration !== false );
  36633. return;
  36634. }
  36635. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  36636. if ( this.object && typeof this.object._finalize === 'function' ) {
  36637. this.object._finalize( true );
  36638. }
  36639. this.object = {
  36640. name: name || '',
  36641. fromDeclaration: ( fromDeclaration !== false ),
  36642. geometry: {
  36643. vertices: [],
  36644. normals: [],
  36645. colors: [],
  36646. uvs: []
  36647. },
  36648. materials: [],
  36649. smooth: true,
  36650. startMaterial: function ( name, libraries ) {
  36651. var previous = this._finalize( false );
  36652. // New usemtl declaration overwrites an inherited material, except if faces were declared
  36653. // after the material, then it must be preserved for proper MultiMaterial continuation.
  36654. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  36655. this.materials.splice( previous.index, 1 );
  36656. }
  36657. var material = {
  36658. index: this.materials.length,
  36659. name: name || '',
  36660. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  36661. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  36662. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  36663. groupEnd: - 1,
  36664. groupCount: - 1,
  36665. inherited: false,
  36666. clone: function ( index ) {
  36667. var cloned = {
  36668. index: ( typeof index === 'number' ? index : this.index ),
  36669. name: this.name,
  36670. mtllib: this.mtllib,
  36671. smooth: this.smooth,
  36672. groupStart: 0,
  36673. groupEnd: - 1,
  36674. groupCount: - 1,
  36675. inherited: false
  36676. };
  36677. cloned.clone = this.clone.bind( cloned );
  36678. return cloned;
  36679. }
  36680. };
  36681. this.materials.push( material );
  36682. return material;
  36683. },
  36684. currentMaterial: function () {
  36685. if ( this.materials.length > 0 ) {
  36686. return this.materials[ this.materials.length - 1 ];
  36687. }
  36688. return undefined;
  36689. },
  36690. _finalize: function ( end ) {
  36691. var lastMultiMaterial = this.currentMaterial();
  36692. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  36693. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  36694. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  36695. lastMultiMaterial.inherited = false;
  36696. }
  36697. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  36698. if ( end && this.materials.length > 1 ) {
  36699. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  36700. if ( this.materials[ mi ].groupCount <= 0 ) {
  36701. this.materials.splice( mi, 1 );
  36702. }
  36703. }
  36704. }
  36705. // Guarantee at least one empty material, this makes the creation later more straight forward.
  36706. if ( end && this.materials.length === 0 ) {
  36707. this.materials.push( {
  36708. name: '',
  36709. smooth: this.smooth
  36710. } );
  36711. }
  36712. return lastMultiMaterial;
  36713. }
  36714. };
  36715. // Inherit previous objects material.
  36716. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  36717. // If a usemtl declaration is encountered while this new object is being parsed, it will
  36718. // overwrite the inherited material. Exception being that there was already face declarations
  36719. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  36720. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  36721. var declared = previousMaterial.clone( 0 );
  36722. declared.inherited = true;
  36723. this.object.materials.push( declared );
  36724. }
  36725. this.objects.push( this.object );
  36726. },
  36727. finalize: function () {
  36728. if ( this.object && typeof this.object._finalize === 'function' ) {
  36729. this.object._finalize( true );
  36730. }
  36731. },
  36732. parseVertexIndex: function ( value, len ) {
  36733. var index = parseInt( value, 10 );
  36734. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  36735. },
  36736. parseNormalIndex: function ( value, len ) {
  36737. var index = parseInt( value, 10 );
  36738. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  36739. },
  36740. parseUVIndex: function ( value, len ) {
  36741. var index = parseInt( value, 10 );
  36742. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  36743. },
  36744. addVertex: function ( a, b, c ) {
  36745. var src = this.vertices;
  36746. var dst = this.object.geometry.vertices;
  36747. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36748. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36749. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36750. },
  36751. addVertexPoint: function ( a ) {
  36752. var src = this.vertices;
  36753. var dst = this.object.geometry.vertices;
  36754. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36755. },
  36756. addVertexLine: function ( a ) {
  36757. var src = this.vertices;
  36758. var dst = this.object.geometry.vertices;
  36759. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36760. },
  36761. addNormal: function ( a, b, c ) {
  36762. var src = this.normals;
  36763. var dst = this.object.geometry.normals;
  36764. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36765. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36766. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36767. },
  36768. addColor: function ( a, b, c ) {
  36769. var src = this.colors;
  36770. var dst = this.object.geometry.colors;
  36771. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36772. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36773. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36774. },
  36775. addUV: function ( a, b, c ) {
  36776. var src = this.uvs;
  36777. var dst = this.object.geometry.uvs;
  36778. dst.push( src[ a + 0 ], src[ a + 1 ] );
  36779. dst.push( src[ b + 0 ], src[ b + 1 ] );
  36780. dst.push( src[ c + 0 ], src[ c + 1 ] );
  36781. },
  36782. addUVLine: function ( a ) {
  36783. var src = this.uvs;
  36784. var dst = this.object.geometry.uvs;
  36785. dst.push( src[ a + 0 ], src[ a + 1 ] );
  36786. },
  36787. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  36788. var vLen = this.vertices.length;
  36789. var ia = this.parseVertexIndex( a, vLen );
  36790. var ib = this.parseVertexIndex( b, vLen );
  36791. var ic = this.parseVertexIndex( c, vLen );
  36792. this.addVertex( ia, ib, ic );
  36793. if ( ua !== undefined && ua !== '' ) {
  36794. var uvLen = this.uvs.length;
  36795. ia = this.parseUVIndex( ua, uvLen );
  36796. ib = this.parseUVIndex( ub, uvLen );
  36797. ic = this.parseUVIndex( uc, uvLen );
  36798. this.addUV( ia, ib, ic );
  36799. }
  36800. if ( na !== undefined && na !== '' ) {
  36801. // Normals are many times the same. If so, skip function call and parseInt.
  36802. var nLen = this.normals.length;
  36803. ia = this.parseNormalIndex( na, nLen );
  36804. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  36805. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  36806. this.addNormal( ia, ib, ic );
  36807. }
  36808. if ( this.colors.length > 0 ) {
  36809. this.addColor( ia, ib, ic );
  36810. }
  36811. },
  36812. addPointGeometry: function ( vertices ) {
  36813. this.object.geometry.type = 'Points';
  36814. var vLen = this.vertices.length;
  36815. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  36816. this.addVertexPoint( this.parseVertexIndex( vertices[ vi ], vLen ) );
  36817. }
  36818. },
  36819. addLineGeometry: function ( vertices, uvs ) {
  36820. this.object.geometry.type = 'Line';
  36821. var vLen = this.vertices.length;
  36822. var uvLen = this.uvs.length;
  36823. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  36824. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  36825. }
  36826. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  36827. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  36828. }
  36829. }
  36830. };
  36831. state.startObject( '', false );
  36832. return state;
  36833. }
  36834. //
  36835. function OBJLoader( manager ) {
  36836. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  36837. this.materials = null;
  36838. }
  36839. OBJLoader.prototype = {
  36840. constructor: OBJLoader,
  36841. load: function ( url, onLoad, onProgress, onError ) {
  36842. var scope = this;
  36843. var loader = new THREE.FileLoader( scope.manager );
  36844. loader.setPath( this.path );
  36845. loader.load( url, function ( text ) {
  36846. onLoad( scope.parse( text ) );
  36847. }, onProgress, onError );
  36848. },
  36849. setPath: function ( value ) {
  36850. this.path = value;
  36851. return this;
  36852. },
  36853. setMaterials: function ( materials ) {
  36854. this.materials = materials;
  36855. return this;
  36856. },
  36857. parse: function ( text ) {
  36858. console.time( 'OBJLoader' );
  36859. var state = new ParserState();
  36860. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  36861. // This is faster than String.split with regex that splits on both
  36862. text = text.replace( /\r\n/g, '\n' );
  36863. }
  36864. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  36865. // join lines separated by a line continuation character (\)
  36866. text = text.replace( /\\\n/g, '' );
  36867. }
  36868. var lines = text.split( '\n' );
  36869. var line = '', lineFirstChar = '';
  36870. var lineLength = 0;
  36871. var result = [];
  36872. // Faster to just trim left side of the line. Use if available.
  36873. var trimLeft = ( typeof ''.trimLeft === 'function' );
  36874. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  36875. line = lines[ i ];
  36876. line = trimLeft ? line.trimLeft() : line.trim();
  36877. lineLength = line.length;
  36878. if ( lineLength === 0 ) continue;
  36879. lineFirstChar = line.charAt( 0 );
  36880. // @todo invoke passed in handler if any
  36881. if ( lineFirstChar === '#' ) continue;
  36882. if ( lineFirstChar === 'v' ) {
  36883. var data = line.split( /\s+/ );
  36884. switch ( data[ 0 ] ) {
  36885. case 'v':
  36886. state.vertices.push(
  36887. parseFloat( data[ 1 ] ),
  36888. parseFloat( data[ 2 ] ),
  36889. parseFloat( data[ 3 ] )
  36890. );
  36891. if ( data.length === 8 ) {
  36892. state.colors.push(
  36893. parseFloat( data[ 4 ] ),
  36894. parseFloat( data[ 5 ] ),
  36895. parseFloat( data[ 6 ] )
  36896. );
  36897. }
  36898. break;
  36899. case 'vn':
  36900. state.normals.push(
  36901. parseFloat( data[ 1 ] ),
  36902. parseFloat( data[ 2 ] ),
  36903. parseFloat( data[ 3 ] )
  36904. );
  36905. break;
  36906. case 'vt':
  36907. state.uvs.push(
  36908. parseFloat( data[ 1 ] ),
  36909. parseFloat( data[ 2 ] )
  36910. );
  36911. break;
  36912. }
  36913. } else if ( lineFirstChar === 'f' ) {
  36914. var lineData = line.substr( 1 ).trim();
  36915. var vertexData = lineData.split( /\s+/ );
  36916. var faceVertices = [];
  36917. // Parse the face vertex data into an easy to work with format
  36918. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  36919. var vertex = vertexData[ j ];
  36920. if ( vertex.length > 0 ) {
  36921. var vertexParts = vertex.split( '/' );
  36922. faceVertices.push( vertexParts );
  36923. }
  36924. }
  36925. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  36926. var v1 = faceVertices[ 0 ];
  36927. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  36928. var v2 = faceVertices[ j ];
  36929. var v3 = faceVertices[ j + 1 ];
  36930. state.addFace(
  36931. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  36932. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  36933. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  36934. );
  36935. }
  36936. } else if ( lineFirstChar === 'l' ) {
  36937. var lineParts = line.substring( 1 ).trim().split( " " );
  36938. var lineVertices = [], lineUVs = [];
  36939. if ( line.indexOf( "/" ) === - 1 ) {
  36940. lineVertices = lineParts;
  36941. } else {
  36942. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  36943. var parts = lineParts[ li ].split( "/" );
  36944. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  36945. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  36946. }
  36947. }
  36948. state.addLineGeometry( lineVertices, lineUVs );
  36949. } else if ( lineFirstChar === 'p' ) {
  36950. var lineData = line.substr( 1 ).trim();
  36951. var pointData = lineData.split( " " );
  36952. state.addPointGeometry( pointData );
  36953. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  36954. // o object_name
  36955. // or
  36956. // g group_name
  36957. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  36958. // var name = result[ 0 ].substr( 1 ).trim();
  36959. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  36960. state.startObject( name );
  36961. } else if ( material_use_pattern.test( line ) ) {
  36962. // material
  36963. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  36964. } else if ( material_library_pattern.test( line ) ) {
  36965. // mtl file
  36966. state.materialLibraries.push( line.substring( 7 ).trim() );
  36967. } else if ( lineFirstChar === 's' ) {
  36968. result = line.split( ' ' );
  36969. // smooth shading
  36970. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  36971. // but does not define a usemtl for each face set.
  36972. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  36973. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  36974. // where explicit usemtl defines geometry groups.
  36975. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  36976. /*
  36977. * http://paulbourke.net/dataformats/obj/
  36978. * or
  36979. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  36980. *
  36981. * From chapter "Grouping" Syntax explanation "s group_number":
  36982. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  36983. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  36984. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  36985. * than 0."
  36986. */
  36987. if ( result.length > 1 ) {
  36988. var value = result[ 1 ].trim().toLowerCase();
  36989. state.object.smooth = ( value !== '0' && value !== 'off' );
  36990. } else {
  36991. // ZBrush can produce "s" lines #11707
  36992. state.object.smooth = true;
  36993. }
  36994. var material = state.object.currentMaterial();
  36995. if ( material ) material.smooth = state.object.smooth;
  36996. } else {
  36997. // Handle null terminated files without exception
  36998. if ( line === '\0' ) continue;
  36999. throw new Error( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  37000. }
  37001. }
  37002. state.finalize();
  37003. var container = new THREE.Group();
  37004. container.materialLibraries = [].concat( state.materialLibraries );
  37005. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  37006. var object = state.objects[ i ];
  37007. var geometry = object.geometry;
  37008. var materials = object.materials;
  37009. var isLine = ( geometry.type === 'Line' );
  37010. var isPoints = ( geometry.type === 'Points' );
  37011. var hasVertexColors = false;
  37012. // Skip o/g line declarations that did not follow with any faces
  37013. if ( geometry.vertices.length === 0 ) continue;
  37014. var buffergeometry = new THREE.BufferGeometry();
  37015. buffergeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  37016. if ( geometry.normals.length > 0 ) {
  37017. buffergeometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  37018. } else {
  37019. buffergeometry.computeVertexNormals();
  37020. }
  37021. if ( geometry.colors.length > 0 ) {
  37022. hasVertexColors = true;
  37023. buffergeometry.addAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  37024. }
  37025. if ( geometry.uvs.length > 0 ) {
  37026. buffergeometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  37027. }
  37028. // Create materials
  37029. var createdMaterials = [];
  37030. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  37031. var sourceMaterial = materials[ mi ];
  37032. var material = undefined;
  37033. if ( this.materials !== null ) {
  37034. material = this.materials.create( sourceMaterial.name );
  37035. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  37036. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  37037. var materialLine = new THREE.LineBasicMaterial();
  37038. materialLine.copy( material );
  37039. materialLine.lights = false; // TOFIX
  37040. material = materialLine;
  37041. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  37042. var materialPoints = new THREE.PointsMaterial( { size: 10, sizeAttenuation: false } );
  37043. materialLine.copy( material );
  37044. material = materialPoints;
  37045. }
  37046. }
  37047. if ( ! material ) {
  37048. if ( isLine ) {
  37049. material = new THREE.LineBasicMaterial();
  37050. } else if ( isPoints ) {
  37051. material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  37052. } else {
  37053. material = new THREE.MeshPhongMaterial();
  37054. }
  37055. material.name = sourceMaterial.name;
  37056. }
  37057. material.flatShading = sourceMaterial.smooth ? false : true;
  37058. material.vertexColors = hasVertexColors ? THREE.VertexColors : THREE.NoColors;
  37059. createdMaterials.push( material );
  37060. }
  37061. // Create mesh
  37062. var mesh;
  37063. if ( createdMaterials.length > 1 ) {
  37064. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  37065. var sourceMaterial = materials[ mi ];
  37066. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  37067. }
  37068. if ( isLine ) {
  37069. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  37070. } else if ( isPoints ) {
  37071. mesh = new THREE.Points( buffergeometry, createdMaterials );
  37072. } else {
  37073. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  37074. }
  37075. } else {
  37076. if ( isLine ) {
  37077. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  37078. } else if ( isPoints ) {
  37079. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  37080. } else {
  37081. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  37082. }
  37083. }
  37084. mesh.name = object.name;
  37085. container.add( mesh );
  37086. }
  37087. console.timeEnd( 'OBJLoader' );
  37088. return container;
  37089. }
  37090. };
  37091. return OBJLoader;
  37092. } )();
  37093. },{}],45:[function(_dereq_,module,exports){
  37094. exports = module.exports = trim;
  37095. function trim(str){
  37096. return str.replace(/^\s*|\s*$/g, '');
  37097. }
  37098. exports.left = function(str){
  37099. return str.replace(/^\s*/, '');
  37100. };
  37101. exports.right = function(str){
  37102. return str.replace(/\s*$/, '');
  37103. };
  37104. },{}],46:[function(_dereq_,module,exports){
  37105. (function (global){
  37106. /**
  37107. * @license
  37108. * webvr-polyfill
  37109. * Copyright (c) 2015-2017 Google
  37110. * Licensed under the Apache License, Version 2.0 (the "License");
  37111. * you may not use this file except in compliance with the License.
  37112. * You may obtain a copy of the License at
  37113. *
  37114. * http://www.apache.org/licenses/LICENSE-2.0
  37115. *
  37116. * Unless required by applicable law or agreed to in writing, software
  37117. * distributed under the License is distributed on an "AS IS" BASIS,
  37118. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37119. * See the License for the specific language governing permissions and
  37120. * limitations under the License.
  37121. */
  37122. /**
  37123. * @license
  37124. * cardboard-vr-display
  37125. * Copyright (c) 2015-2017 Google
  37126. * Licensed under the Apache License, Version 2.0 (the "License");
  37127. * you may not use this file except in compliance with the License.
  37128. * You may obtain a copy of the License at
  37129. *
  37130. * http://www.apache.org/licenses/LICENSE-2.0
  37131. *
  37132. * Unless required by applicable law or agreed to in writing, software
  37133. * distributed under the License is distributed on an "AS IS" BASIS,
  37134. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37135. * See the License for the specific language governing permissions and
  37136. * limitations under the License.
  37137. */
  37138. /**
  37139. * @license
  37140. * webvr-polyfill-dpdb
  37141. * Copyright (c) 2017 Google
  37142. * Licensed under the Apache License, Version 2.0 (the "License");
  37143. * you may not use this file except in compliance with the License.
  37144. * You may obtain a copy of the License at
  37145. *
  37146. * http://www.apache.org/licenses/LICENSE-2.0
  37147. *
  37148. * Unless required by applicable law or agreed to in writing, software
  37149. * distributed under the License is distributed on an "AS IS" BASIS,
  37150. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37151. * See the License for the specific language governing permissions and
  37152. * limitations under the License.
  37153. */
  37154. /**
  37155. * @license
  37156. * wglu-preserve-state
  37157. * Copyright (c) 2016, Brandon Jones.
  37158. *
  37159. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37160. * of this software and associated documentation files (the "Software"), to deal
  37161. * in the Software without restriction, including without limitation the rights
  37162. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37163. * copies of the Software, and to permit persons to whom the Software is
  37164. * furnished to do so, subject to the following conditions:
  37165. *
  37166. * The above copyright notice and this permission notice shall be included in
  37167. * all copies or substantial portions of the Software.
  37168. *
  37169. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37170. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37171. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37172. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37173. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37174. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37175. * THE SOFTWARE.
  37176. */
  37177. /**
  37178. * @license
  37179. * nosleep.js
  37180. * Copyright (c) 2017, Rich Tibbett
  37181. *
  37182. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37183. * of this software and associated documentation files (the "Software"), to deal
  37184. * in the Software without restriction, including without limitation the rights
  37185. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37186. * copies of the Software, and to permit persons to whom the Software is
  37187. * furnished to do so, subject to the following conditions:
  37188. *
  37189. * The above copyright notice and this permission notice shall be included in
  37190. * all copies or substantial portions of the Software.
  37191. *
  37192. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37193. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37194. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37195. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37196. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37197. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37198. * THE SOFTWARE.
  37199. */
  37200. (function (global, factory) {
  37201. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  37202. typeof define === 'function' && define.amd ? define(factory) :
  37203. (global.WebVRPolyfill = factory());
  37204. }(this, (function () { 'use strict';
  37205. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  37206. function unwrapExports (x) {
  37207. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  37208. }
  37209. function createCommonjsModule(fn, module) {
  37210. return module = { exports: {} }, fn(module, module.exports), module.exports;
  37211. }
  37212. var race = function race(promises) {
  37213. if (Promise.race) {
  37214. return Promise.race(promises);
  37215. }
  37216. return new Promise(function (resolve, reject) {
  37217. for (var i = 0; i < promises.length; i++) {
  37218. promises[i].then(resolve, reject);
  37219. }
  37220. });
  37221. };
  37222. var isMobile = function isMobile() {
  37223. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  37224. );
  37225. };
  37226. var copyArray = function copyArray(source, dest) {
  37227. for (var i = 0, n = source.length; i < n; i++) {
  37228. dest[i] = source[i];
  37229. }
  37230. };
  37231. var extend = function extend(dest, src) {
  37232. for (var key in src) {
  37233. if (src.hasOwnProperty(key)) {
  37234. dest[key] = src[key];
  37235. }
  37236. }
  37237. return dest;
  37238. };
  37239. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  37240. /**
  37241. * @license
  37242. * cardboard-vr-display
  37243. * Copyright (c) 2015-2017 Google
  37244. * Licensed under the Apache License, Version 2.0 (the "License");
  37245. * you may not use this file except in compliance with the License.
  37246. * You may obtain a copy of the License at
  37247. *
  37248. * http://www.apache.org/licenses/LICENSE-2.0
  37249. *
  37250. * Unless required by applicable law or agreed to in writing, software
  37251. * distributed under the License is distributed on an "AS IS" BASIS,
  37252. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37253. * See the License for the specific language governing permissions and
  37254. * limitations under the License.
  37255. */
  37256. /**
  37257. * @license
  37258. * gl-preserve-state
  37259. * Copyright (c) 2016, Brandon Jones.
  37260. *
  37261. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37262. * of this software and associated documentation files (the "Software"), to deal
  37263. * in the Software without restriction, including without limitation the rights
  37264. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37265. * copies of the Software, and to permit persons to whom the Software is
  37266. * furnished to do so, subject to the following conditions:
  37267. *
  37268. * The above copyright notice and this permission notice shall be included in
  37269. * all copies or substantial portions of the Software.
  37270. *
  37271. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37272. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37273. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37274. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37275. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37276. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37277. * THE SOFTWARE.
  37278. */
  37279. /**
  37280. * @license
  37281. * webvr-polyfill-dpdb
  37282. * Copyright (c) 2015-2017 Google
  37283. * Licensed under the Apache License, Version 2.0 (the "License");
  37284. * you may not use this file except in compliance with the License.
  37285. * You may obtain a copy of the License at
  37286. *
  37287. * http://www.apache.org/licenses/LICENSE-2.0
  37288. *
  37289. * Unless required by applicable law or agreed to in writing, software
  37290. * distributed under the License is distributed on an "AS IS" BASIS,
  37291. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37292. * See the License for the specific language governing permissions and
  37293. * limitations under the License.
  37294. */
  37295. /**
  37296. * @license
  37297. * nosleep.js
  37298. * Copyright (c) 2017, Rich Tibbett
  37299. *
  37300. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37301. * of this software and associated documentation files (the "Software"), to deal
  37302. * in the Software without restriction, including without limitation the rights
  37303. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37304. * copies of the Software, and to permit persons to whom the Software is
  37305. * furnished to do so, subject to the following conditions:
  37306. *
  37307. * The above copyright notice and this permission notice shall be included in
  37308. * all copies or substantial portions of the Software.
  37309. *
  37310. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37311. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37312. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37313. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37314. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37315. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37316. * THE SOFTWARE.
  37317. */
  37318. (function (global, factory) {
  37319. module.exports = factory();
  37320. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  37321. if (!(instance instanceof Constructor)) {
  37322. throw new TypeError("Cannot call a class as a function");
  37323. }
  37324. };
  37325. var createClass = function () {
  37326. function defineProperties(target, props) {
  37327. for (var i = 0; i < props.length; i++) {
  37328. var descriptor = props[i];
  37329. descriptor.enumerable = descriptor.enumerable || false;
  37330. descriptor.configurable = true;
  37331. if ("value" in descriptor) descriptor.writable = true;
  37332. Object.defineProperty(target, descriptor.key, descriptor);
  37333. }
  37334. }
  37335. return function (Constructor, protoProps, staticProps) {
  37336. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  37337. if (staticProps) defineProperties(Constructor, staticProps);
  37338. return Constructor;
  37339. };
  37340. }();
  37341. var slicedToArray = function () {
  37342. function sliceIterator(arr, i) {
  37343. var _arr = [];
  37344. var _n = true;
  37345. var _d = false;
  37346. var _e = undefined;
  37347. try {
  37348. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  37349. _arr.push(_s.value);
  37350. if (i && _arr.length === i) break;
  37351. }
  37352. } catch (err) {
  37353. _d = true;
  37354. _e = err;
  37355. } finally {
  37356. try {
  37357. if (!_n && _i["return"]) _i["return"]();
  37358. } finally {
  37359. if (_d) throw _e;
  37360. }
  37361. }
  37362. return _arr;
  37363. }
  37364. return function (arr, i) {
  37365. if (Array.isArray(arr)) {
  37366. return arr;
  37367. } else if (Symbol.iterator in Object(arr)) {
  37368. return sliceIterator(arr, i);
  37369. } else {
  37370. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  37371. }
  37372. };
  37373. }();
  37374. var MIN_TIMESTEP = 0.001;
  37375. var MAX_TIMESTEP = 1;
  37376. var base64 = function base64(mimeType, _base) {
  37377. return 'data:' + mimeType + ';base64,' + _base;
  37378. };
  37379. var lerp = function lerp(a, b, t) {
  37380. return a + (b - a) * t;
  37381. };
  37382. var isIOS = function () {
  37383. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  37384. return function () {
  37385. return isIOS;
  37386. };
  37387. }();
  37388. var isWebViewAndroid = function () {
  37389. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  37390. return function () {
  37391. return isWebViewAndroid;
  37392. };
  37393. }();
  37394. var isSafari = function () {
  37395. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  37396. return function () {
  37397. return isSafari;
  37398. };
  37399. }();
  37400. var isFirefoxAndroid = function () {
  37401. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  37402. return function () {
  37403. return isFirefoxAndroid;
  37404. };
  37405. }();
  37406. var getChromeVersion = function () {
  37407. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  37408. var value = match ? parseInt(match[1], 10) : null;
  37409. return function () {
  37410. return value;
  37411. };
  37412. }();
  37413. var isChromeWithoutDeviceMotion = function () {
  37414. var value = false;
  37415. if (getChromeVersion() === 65) {
  37416. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  37417. if (match) {
  37418. var _match$1$split = match[1].split('.'),
  37419. _match$1$split2 = slicedToArray(_match$1$split, 4),
  37420. major = _match$1$split2[0],
  37421. minor = _match$1$split2[1],
  37422. branch = _match$1$split2[2],
  37423. build = _match$1$split2[3];
  37424. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  37425. }
  37426. }
  37427. return function () {
  37428. return value;
  37429. };
  37430. }();
  37431. var isR7 = function () {
  37432. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  37433. return function () {
  37434. return isR7;
  37435. };
  37436. }();
  37437. var isLandscapeMode = function isLandscapeMode() {
  37438. var rtn = window.orientation == 90 || window.orientation == -90;
  37439. return isR7() ? !rtn : rtn;
  37440. };
  37441. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  37442. if (isNaN(timestampDeltaS)) {
  37443. return false;
  37444. }
  37445. if (timestampDeltaS <= MIN_TIMESTEP) {
  37446. return false;
  37447. }
  37448. if (timestampDeltaS > MAX_TIMESTEP) {
  37449. return false;
  37450. }
  37451. return true;
  37452. };
  37453. var getScreenWidth = function getScreenWidth() {
  37454. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  37455. };
  37456. var getScreenHeight = function getScreenHeight() {
  37457. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  37458. };
  37459. var requestFullscreen = function requestFullscreen(element) {
  37460. if (isWebViewAndroid()) {
  37461. return false;
  37462. }
  37463. if (element.requestFullscreen) {
  37464. element.requestFullscreen();
  37465. } else if (element.webkitRequestFullscreen) {
  37466. element.webkitRequestFullscreen();
  37467. } else if (element.mozRequestFullScreen) {
  37468. element.mozRequestFullScreen();
  37469. } else if (element.msRequestFullscreen) {
  37470. element.msRequestFullscreen();
  37471. } else {
  37472. return false;
  37473. }
  37474. return true;
  37475. };
  37476. var exitFullscreen = function exitFullscreen() {
  37477. if (document.exitFullscreen) {
  37478. document.exitFullscreen();
  37479. } else if (document.webkitExitFullscreen) {
  37480. document.webkitExitFullscreen();
  37481. } else if (document.mozCancelFullScreen) {
  37482. document.mozCancelFullScreen();
  37483. } else if (document.msExitFullscreen) {
  37484. document.msExitFullscreen();
  37485. } else {
  37486. return false;
  37487. }
  37488. return true;
  37489. };
  37490. var getFullscreenElement = function getFullscreenElement() {
  37491. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  37492. };
  37493. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  37494. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  37495. gl.shaderSource(vertexShader, vertexSource);
  37496. gl.compileShader(vertexShader);
  37497. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  37498. gl.shaderSource(fragmentShader, fragmentSource);
  37499. gl.compileShader(fragmentShader);
  37500. var program = gl.createProgram();
  37501. gl.attachShader(program, vertexShader);
  37502. gl.attachShader(program, fragmentShader);
  37503. for (var attribName in attribLocationMap) {
  37504. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  37505. }gl.linkProgram(program);
  37506. gl.deleteShader(vertexShader);
  37507. gl.deleteShader(fragmentShader);
  37508. return program;
  37509. };
  37510. var getProgramUniforms = function getProgramUniforms(gl, program) {
  37511. var uniforms = {};
  37512. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  37513. var uniformName = '';
  37514. for (var i = 0; i < uniformCount; i++) {
  37515. var uniformInfo = gl.getActiveUniform(program, i);
  37516. uniformName = uniformInfo.name.replace('[0]', '');
  37517. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  37518. }
  37519. return uniforms;
  37520. };
  37521. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  37522. var lr = 1 / (left - right),
  37523. bt = 1 / (bottom - top),
  37524. nf = 1 / (near - far);
  37525. out[0] = -2 * lr;
  37526. out[1] = 0;
  37527. out[2] = 0;
  37528. out[3] = 0;
  37529. out[4] = 0;
  37530. out[5] = -2 * bt;
  37531. out[6] = 0;
  37532. out[7] = 0;
  37533. out[8] = 0;
  37534. out[9] = 0;
  37535. out[10] = 2 * nf;
  37536. out[11] = 0;
  37537. out[12] = (left + right) * lr;
  37538. out[13] = (top + bottom) * bt;
  37539. out[14] = (far + near) * nf;
  37540. out[15] = 1;
  37541. return out;
  37542. };
  37543. var isMobile = function isMobile() {
  37544. var check = false;
  37545. (function (a) {
  37546. 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;
  37547. })(navigator.userAgent || navigator.vendor || window.opera);
  37548. return check;
  37549. };
  37550. var extend = function extend(dest, src) {
  37551. for (var key in src) {
  37552. if (src.hasOwnProperty(key)) {
  37553. dest[key] = src[key];
  37554. }
  37555. }
  37556. return dest;
  37557. };
  37558. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  37559. if (isIOS()) {
  37560. var width = canvas.style.width;
  37561. var height = canvas.style.height;
  37562. canvas.style.width = parseInt(width) + 1 + 'px';
  37563. canvas.style.height = parseInt(height) + 'px';
  37564. setTimeout(function () {
  37565. canvas.style.width = width;
  37566. canvas.style.height = height;
  37567. }, 100);
  37568. }
  37569. window.canvas = canvas;
  37570. };
  37571. var frameDataFromPose = function () {
  37572. var piOver180 = Math.PI / 180.0;
  37573. var rad45 = Math.PI * 0.25;
  37574. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  37575. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  37576. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  37577. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  37578. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  37579. xScale = 2.0 / (leftTan + rightTan),
  37580. yScale = 2.0 / (upTan + downTan);
  37581. out[0] = xScale;
  37582. out[1] = 0.0;
  37583. out[2] = 0.0;
  37584. out[3] = 0.0;
  37585. out[4] = 0.0;
  37586. out[5] = yScale;
  37587. out[6] = 0.0;
  37588. out[7] = 0.0;
  37589. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  37590. out[9] = (upTan - downTan) * yScale * 0.5;
  37591. out[10] = far / (near - far);
  37592. out[11] = -1.0;
  37593. out[12] = 0.0;
  37594. out[13] = 0.0;
  37595. out[14] = far * near / (near - far);
  37596. out[15] = 0.0;
  37597. return out;
  37598. }
  37599. function mat4_fromRotationTranslation(out, q, v) {
  37600. var x = q[0],
  37601. y = q[1],
  37602. z = q[2],
  37603. w = q[3],
  37604. x2 = x + x,
  37605. y2 = y + y,
  37606. z2 = z + z,
  37607. xx = x * x2,
  37608. xy = x * y2,
  37609. xz = x * z2,
  37610. yy = y * y2,
  37611. yz = y * z2,
  37612. zz = z * z2,
  37613. wx = w * x2,
  37614. wy = w * y2,
  37615. wz = w * z2;
  37616. out[0] = 1 - (yy + zz);
  37617. out[1] = xy + wz;
  37618. out[2] = xz - wy;
  37619. out[3] = 0;
  37620. out[4] = xy - wz;
  37621. out[5] = 1 - (xx + zz);
  37622. out[6] = yz + wx;
  37623. out[7] = 0;
  37624. out[8] = xz + wy;
  37625. out[9] = yz - wx;
  37626. out[10] = 1 - (xx + yy);
  37627. out[11] = 0;
  37628. out[12] = v[0];
  37629. out[13] = v[1];
  37630. out[14] = v[2];
  37631. out[15] = 1;
  37632. return out;
  37633. }
  37634. function mat4_translate(out, a, v) {
  37635. var x = v[0],
  37636. y = v[1],
  37637. z = v[2],
  37638. a00,
  37639. a01,
  37640. a02,
  37641. a03,
  37642. a10,
  37643. a11,
  37644. a12,
  37645. a13,
  37646. a20,
  37647. a21,
  37648. a22,
  37649. a23;
  37650. if (a === out) {
  37651. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  37652. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  37653. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  37654. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  37655. } else {
  37656. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  37657. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  37658. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  37659. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  37660. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  37661. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  37662. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  37663. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  37664. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  37665. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  37666. }
  37667. return out;
  37668. }
  37669. function mat4_invert(out, a) {
  37670. var a00 = a[0],
  37671. a01 = a[1],
  37672. a02 = a[2],
  37673. a03 = a[3],
  37674. a10 = a[4],
  37675. a11 = a[5],
  37676. a12 = a[6],
  37677. a13 = a[7],
  37678. a20 = a[8],
  37679. a21 = a[9],
  37680. a22 = a[10],
  37681. a23 = a[11],
  37682. a30 = a[12],
  37683. a31 = a[13],
  37684. a32 = a[14],
  37685. a33 = a[15],
  37686. b00 = a00 * a11 - a01 * a10,
  37687. b01 = a00 * a12 - a02 * a10,
  37688. b02 = a00 * a13 - a03 * a10,
  37689. b03 = a01 * a12 - a02 * a11,
  37690. b04 = a01 * a13 - a03 * a11,
  37691. b05 = a02 * a13 - a03 * a12,
  37692. b06 = a20 * a31 - a21 * a30,
  37693. b07 = a20 * a32 - a22 * a30,
  37694. b08 = a20 * a33 - a23 * a30,
  37695. b09 = a21 * a32 - a22 * a31,
  37696. b10 = a21 * a33 - a23 * a31,
  37697. b11 = a22 * a33 - a23 * a32,
  37698. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  37699. if (!det) {
  37700. return null;
  37701. }
  37702. det = 1.0 / det;
  37703. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  37704. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  37705. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  37706. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  37707. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  37708. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  37709. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  37710. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  37711. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  37712. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  37713. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  37714. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  37715. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  37716. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  37717. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  37718. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  37719. return out;
  37720. }
  37721. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  37722. var defaultPosition = new Float32Array([0, 0, 0]);
  37723. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  37724. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  37725. var orientation = pose.orientation || defaultOrientation;
  37726. var position = pose.position || defaultPosition;
  37727. mat4_fromRotationTranslation(view, orientation, position);
  37728. if (offset) mat4_translate(view, view, offset);
  37729. mat4_invert(view, view);
  37730. }
  37731. return function (frameData, pose, vrDisplay) {
  37732. if (!frameData || !pose) return false;
  37733. frameData.pose = pose;
  37734. frameData.timestamp = pose.timestamp;
  37735. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  37736. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  37737. return true;
  37738. };
  37739. }();
  37740. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  37741. var isFramed = window.self !== window.top;
  37742. var refOrigin = getOriginFromUrl(document.referrer);
  37743. var thisOrigin = getOriginFromUrl(window.location.href);
  37744. return isFramed && refOrigin !== thisOrigin;
  37745. };
  37746. var getOriginFromUrl = function getOriginFromUrl(url) {
  37747. var domainIdx;
  37748. var protoSepIdx = url.indexOf("://");
  37749. if (protoSepIdx !== -1) {
  37750. domainIdx = protoSepIdx + 3;
  37751. } else {
  37752. domainIdx = 0;
  37753. }
  37754. var domainEndIdx = url.indexOf('/', domainIdx);
  37755. if (domainEndIdx === -1) {
  37756. domainEndIdx = url.length;
  37757. }
  37758. return url.substring(0, domainEndIdx);
  37759. };
  37760. var getQuaternionAngle = function getQuaternionAngle(quat) {
  37761. if (quat.w > 1) {
  37762. console.warn('getQuaternionAngle: w > 1');
  37763. return 0;
  37764. }
  37765. var angle = 2 * Math.acos(quat.w);
  37766. return angle;
  37767. };
  37768. var warnOnce = function () {
  37769. var observedWarnings = {};
  37770. return function (key, message) {
  37771. if (observedWarnings[key] === undefined) {
  37772. console.warn('webvr-polyfill: ' + message);
  37773. observedWarnings[key] = true;
  37774. }
  37775. };
  37776. }();
  37777. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  37778. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  37779. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  37780. };
  37781. function WGLUPreserveGLState(gl, bindings, callback) {
  37782. if (!bindings) {
  37783. callback(gl);
  37784. return;
  37785. }
  37786. var boundValues = [];
  37787. var activeTexture = null;
  37788. for (var i = 0; i < bindings.length; ++i) {
  37789. var binding = bindings[i];
  37790. switch (binding) {
  37791. case gl.TEXTURE_BINDING_2D:
  37792. case gl.TEXTURE_BINDING_CUBE_MAP:
  37793. var textureUnit = bindings[++i];
  37794. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  37795. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  37796. boundValues.push(null, null);
  37797. break;
  37798. }
  37799. if (!activeTexture) {
  37800. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  37801. }
  37802. gl.activeTexture(textureUnit);
  37803. boundValues.push(gl.getParameter(binding), null);
  37804. break;
  37805. case gl.ACTIVE_TEXTURE:
  37806. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  37807. boundValues.push(null);
  37808. break;
  37809. default:
  37810. boundValues.push(gl.getParameter(binding));
  37811. break;
  37812. }
  37813. }
  37814. callback(gl);
  37815. for (var i = 0; i < bindings.length; ++i) {
  37816. var binding = bindings[i];
  37817. var boundValue = boundValues[i];
  37818. switch (binding) {
  37819. case gl.ACTIVE_TEXTURE:
  37820. break;
  37821. case gl.ARRAY_BUFFER_BINDING:
  37822. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  37823. break;
  37824. case gl.COLOR_CLEAR_VALUE:
  37825. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  37826. break;
  37827. case gl.COLOR_WRITEMASK:
  37828. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  37829. break;
  37830. case gl.CURRENT_PROGRAM:
  37831. gl.useProgram(boundValue);
  37832. break;
  37833. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  37834. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  37835. break;
  37836. case gl.FRAMEBUFFER_BINDING:
  37837. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  37838. break;
  37839. case gl.RENDERBUFFER_BINDING:
  37840. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  37841. break;
  37842. case gl.TEXTURE_BINDING_2D:
  37843. var textureUnit = bindings[++i];
  37844. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  37845. break;
  37846. gl.activeTexture(textureUnit);
  37847. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  37848. break;
  37849. case gl.TEXTURE_BINDING_CUBE_MAP:
  37850. var textureUnit = bindings[++i];
  37851. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  37852. break;
  37853. gl.activeTexture(textureUnit);
  37854. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  37855. break;
  37856. case gl.VIEWPORT:
  37857. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  37858. break;
  37859. case gl.BLEND:
  37860. case gl.CULL_FACE:
  37861. case gl.DEPTH_TEST:
  37862. case gl.SCISSOR_TEST:
  37863. case gl.STENCIL_TEST:
  37864. if (boundValue) {
  37865. gl.enable(binding);
  37866. } else {
  37867. gl.disable(binding);
  37868. }
  37869. break;
  37870. default:
  37871. console.log("No GL restore behavior for 0x" + binding.toString(16));
  37872. break;
  37873. }
  37874. if (activeTexture) {
  37875. gl.activeTexture(activeTexture);
  37876. }
  37877. }
  37878. }
  37879. var glPreserveState = WGLUPreserveGLState;
  37880. 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');
  37881. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  37882. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  37883. this.gl = gl;
  37884. this.cardboardUI = cardboardUI;
  37885. this.bufferScale = bufferScale;
  37886. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  37887. this.ctxAttribs = gl.getContextAttributes();
  37888. this.meshWidth = 20;
  37889. this.meshHeight = 20;
  37890. this.bufferWidth = gl.drawingBufferWidth;
  37891. this.bufferHeight = gl.drawingBufferHeight;
  37892. this.realBindFramebuffer = gl.bindFramebuffer;
  37893. this.realEnable = gl.enable;
  37894. this.realDisable = gl.disable;
  37895. this.realColorMask = gl.colorMask;
  37896. this.realClearColor = gl.clearColor;
  37897. this.realViewport = gl.viewport;
  37898. if (!isIOS()) {
  37899. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  37900. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  37901. }
  37902. this.isPatched = false;
  37903. this.lastBoundFramebuffer = null;
  37904. this.cullFace = false;
  37905. this.depthTest = false;
  37906. this.blend = false;
  37907. this.scissorTest = false;
  37908. this.stencilTest = false;
  37909. this.viewport = [0, 0, 0, 0];
  37910. this.colorMask = [true, true, true, true];
  37911. this.clearColor = [0, 0, 0, 0];
  37912. this.attribs = {
  37913. position: 0,
  37914. texCoord: 1
  37915. };
  37916. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  37917. this.uniforms = getProgramUniforms(gl, this.program);
  37918. this.viewportOffsetScale = new Float32Array(8);
  37919. this.setTextureBounds();
  37920. this.vertexBuffer = gl.createBuffer();
  37921. this.indexBuffer = gl.createBuffer();
  37922. this.indexCount = 0;
  37923. this.renderTarget = gl.createTexture();
  37924. this.framebuffer = gl.createFramebuffer();
  37925. this.depthStencilBuffer = null;
  37926. this.depthBuffer = null;
  37927. this.stencilBuffer = null;
  37928. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  37929. this.depthStencilBuffer = gl.createRenderbuffer();
  37930. } else if (this.ctxAttribs.depth) {
  37931. this.depthBuffer = gl.createRenderbuffer();
  37932. } else if (this.ctxAttribs.stencil) {
  37933. this.stencilBuffer = gl.createRenderbuffer();
  37934. }
  37935. this.patch();
  37936. this.onResize();
  37937. }
  37938. CardboardDistorter.prototype.destroy = function () {
  37939. var gl = this.gl;
  37940. this.unpatch();
  37941. gl.deleteProgram(this.program);
  37942. gl.deleteBuffer(this.vertexBuffer);
  37943. gl.deleteBuffer(this.indexBuffer);
  37944. gl.deleteTexture(this.renderTarget);
  37945. gl.deleteFramebuffer(this.framebuffer);
  37946. if (this.depthStencilBuffer) {
  37947. gl.deleteRenderbuffer(this.depthStencilBuffer);
  37948. }
  37949. if (this.depthBuffer) {
  37950. gl.deleteRenderbuffer(this.depthBuffer);
  37951. }
  37952. if (this.stencilBuffer) {
  37953. gl.deleteRenderbuffer(this.stencilBuffer);
  37954. }
  37955. if (this.cardboardUI) {
  37956. this.cardboardUI.destroy();
  37957. }
  37958. };
  37959. CardboardDistorter.prototype.onResize = function () {
  37960. var gl = this.gl;
  37961. var self = this;
  37962. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  37963. glPreserveState(gl, glState, function (gl) {
  37964. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  37965. if (self.scissorTest) {
  37966. self.realDisable.call(gl, gl.SCISSOR_TEST);
  37967. }
  37968. self.realColorMask.call(gl, true, true, true, true);
  37969. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37970. self.realClearColor.call(gl, 0, 0, 0, 1);
  37971. gl.clear(gl.COLOR_BUFFER_BIT);
  37972. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  37973. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  37974. 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);
  37975. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  37976. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  37977. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  37978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  37979. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  37980. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  37981. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  37982. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  37983. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  37984. } else if (self.ctxAttribs.depth) {
  37985. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  37986. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  37987. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  37988. } else if (self.ctxAttribs.stencil) {
  37989. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  37990. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  37991. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  37992. }
  37993. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  37994. console.error('Framebuffer incomplete!');
  37995. }
  37996. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  37997. if (self.scissorTest) {
  37998. self.realEnable.call(gl, gl.SCISSOR_TEST);
  37999. }
  38000. self.realColorMask.apply(gl, self.colorMask);
  38001. self.realViewport.apply(gl, self.viewport);
  38002. self.realClearColor.apply(gl, self.clearColor);
  38003. });
  38004. if (this.cardboardUI) {
  38005. this.cardboardUI.onResize();
  38006. }
  38007. };
  38008. CardboardDistorter.prototype.patch = function () {
  38009. if (this.isPatched) {
  38010. return;
  38011. }
  38012. var self = this;
  38013. var canvas = this.gl.canvas;
  38014. var gl = this.gl;
  38015. if (!isIOS()) {
  38016. canvas.width = getScreenWidth() * this.bufferScale;
  38017. canvas.height = getScreenHeight() * this.bufferScale;
  38018. Object.defineProperty(canvas, 'width', {
  38019. configurable: true,
  38020. enumerable: true,
  38021. get: function get() {
  38022. return self.bufferWidth;
  38023. },
  38024. set: function set(value) {
  38025. self.bufferWidth = value;
  38026. self.realCanvasWidth.set.call(canvas, value);
  38027. self.onResize();
  38028. }
  38029. });
  38030. Object.defineProperty(canvas, 'height', {
  38031. configurable: true,
  38032. enumerable: true,
  38033. get: function get() {
  38034. return self.bufferHeight;
  38035. },
  38036. set: function set(value) {
  38037. self.bufferHeight = value;
  38038. self.realCanvasHeight.set.call(canvas, value);
  38039. self.onResize();
  38040. }
  38041. });
  38042. }
  38043. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  38044. if (this.lastBoundFramebuffer == null) {
  38045. this.lastBoundFramebuffer = this.framebuffer;
  38046. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  38047. }
  38048. this.gl.bindFramebuffer = function (target, framebuffer) {
  38049. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  38050. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  38051. };
  38052. this.cullFace = gl.getParameter(gl.CULL_FACE);
  38053. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  38054. this.blend = gl.getParameter(gl.BLEND);
  38055. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  38056. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  38057. gl.enable = function (pname) {
  38058. switch (pname) {
  38059. case gl.CULL_FACE:
  38060. self.cullFace = true;break;
  38061. case gl.DEPTH_TEST:
  38062. self.depthTest = true;break;
  38063. case gl.BLEND:
  38064. self.blend = true;break;
  38065. case gl.SCISSOR_TEST:
  38066. self.scissorTest = true;break;
  38067. case gl.STENCIL_TEST:
  38068. self.stencilTest = true;break;
  38069. }
  38070. self.realEnable.call(gl, pname);
  38071. };
  38072. gl.disable = function (pname) {
  38073. switch (pname) {
  38074. case gl.CULL_FACE:
  38075. self.cullFace = false;break;
  38076. case gl.DEPTH_TEST:
  38077. self.depthTest = false;break;
  38078. case gl.BLEND:
  38079. self.blend = false;break;
  38080. case gl.SCISSOR_TEST:
  38081. self.scissorTest = false;break;
  38082. case gl.STENCIL_TEST:
  38083. self.stencilTest = false;break;
  38084. }
  38085. self.realDisable.call(gl, pname);
  38086. };
  38087. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  38088. gl.colorMask = function (r, g, b, a) {
  38089. self.colorMask[0] = r;
  38090. self.colorMask[1] = g;
  38091. self.colorMask[2] = b;
  38092. self.colorMask[3] = a;
  38093. self.realColorMask.call(gl, r, g, b, a);
  38094. };
  38095. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  38096. gl.clearColor = function (r, g, b, a) {
  38097. self.clearColor[0] = r;
  38098. self.clearColor[1] = g;
  38099. self.clearColor[2] = b;
  38100. self.clearColor[3] = a;
  38101. self.realClearColor.call(gl, r, g, b, a);
  38102. };
  38103. this.viewport = gl.getParameter(gl.VIEWPORT);
  38104. gl.viewport = function (x, y, w, h) {
  38105. self.viewport[0] = x;
  38106. self.viewport[1] = y;
  38107. self.viewport[2] = w;
  38108. self.viewport[3] = h;
  38109. self.realViewport.call(gl, x, y, w, h);
  38110. };
  38111. this.isPatched = true;
  38112. safariCssSizeWorkaround(canvas);
  38113. };
  38114. CardboardDistorter.prototype.unpatch = function () {
  38115. if (!this.isPatched) {
  38116. return;
  38117. }
  38118. var gl = this.gl;
  38119. var canvas = this.gl.canvas;
  38120. if (!isIOS()) {
  38121. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  38122. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  38123. }
  38124. canvas.width = this.bufferWidth;
  38125. canvas.height = this.bufferHeight;
  38126. gl.bindFramebuffer = this.realBindFramebuffer;
  38127. gl.enable = this.realEnable;
  38128. gl.disable = this.realDisable;
  38129. gl.colorMask = this.realColorMask;
  38130. gl.clearColor = this.realClearColor;
  38131. gl.viewport = this.realViewport;
  38132. if (this.lastBoundFramebuffer == this.framebuffer) {
  38133. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  38134. }
  38135. this.isPatched = false;
  38136. setTimeout(function () {
  38137. safariCssSizeWorkaround(canvas);
  38138. }, 1);
  38139. };
  38140. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  38141. if (!leftBounds) {
  38142. leftBounds = [0, 0, 0.5, 1];
  38143. }
  38144. if (!rightBounds) {
  38145. rightBounds = [0.5, 0, 0.5, 1];
  38146. }
  38147. this.viewportOffsetScale[0] = leftBounds[0];
  38148. this.viewportOffsetScale[1] = leftBounds[1];
  38149. this.viewportOffsetScale[2] = leftBounds[2];
  38150. this.viewportOffsetScale[3] = leftBounds[3];
  38151. this.viewportOffsetScale[4] = rightBounds[0];
  38152. this.viewportOffsetScale[5] = rightBounds[1];
  38153. this.viewportOffsetScale[6] = rightBounds[2];
  38154. this.viewportOffsetScale[7] = rightBounds[3];
  38155. };
  38156. CardboardDistorter.prototype.submitFrame = function () {
  38157. var gl = this.gl;
  38158. var self = this;
  38159. var glState = [];
  38160. if (!this.dirtySubmitFrameBindings) {
  38161. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  38162. }
  38163. glPreserveState(gl, glState, function (gl) {
  38164. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  38165. if (self.cullFace) {
  38166. self.realDisable.call(gl, gl.CULL_FACE);
  38167. }
  38168. if (self.depthTest) {
  38169. self.realDisable.call(gl, gl.DEPTH_TEST);
  38170. }
  38171. if (self.blend) {
  38172. self.realDisable.call(gl, gl.BLEND);
  38173. }
  38174. if (self.scissorTest) {
  38175. self.realDisable.call(gl, gl.SCISSOR_TEST);
  38176. }
  38177. if (self.stencilTest) {
  38178. self.realDisable.call(gl, gl.STENCIL_TEST);
  38179. }
  38180. self.realColorMask.call(gl, true, true, true, true);
  38181. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  38182. if (self.ctxAttribs.alpha || isIOS()) {
  38183. self.realClearColor.call(gl, 0, 0, 0, 1);
  38184. gl.clear(gl.COLOR_BUFFER_BIT);
  38185. }
  38186. gl.useProgram(self.program);
  38187. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  38188. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38189. gl.enableVertexAttribArray(self.attribs.position);
  38190. gl.enableVertexAttribArray(self.attribs.texCoord);
  38191. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  38192. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  38193. gl.activeTexture(gl.TEXTURE0);
  38194. gl.uniform1i(self.uniforms.diffuse, 0);
  38195. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  38196. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  38197. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  38198. if (self.cardboardUI) {
  38199. self.cardboardUI.renderNoState();
  38200. }
  38201. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  38202. if (!self.ctxAttribs.preserveDrawingBuffer) {
  38203. self.realClearColor.call(gl, 0, 0, 0, 0);
  38204. gl.clear(gl.COLOR_BUFFER_BIT);
  38205. }
  38206. if (!self.dirtySubmitFrameBindings) {
  38207. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  38208. }
  38209. if (self.cullFace) {
  38210. self.realEnable.call(gl, gl.CULL_FACE);
  38211. }
  38212. if (self.depthTest) {
  38213. self.realEnable.call(gl, gl.DEPTH_TEST);
  38214. }
  38215. if (self.blend) {
  38216. self.realEnable.call(gl, gl.BLEND);
  38217. }
  38218. if (self.scissorTest) {
  38219. self.realEnable.call(gl, gl.SCISSOR_TEST);
  38220. }
  38221. if (self.stencilTest) {
  38222. self.realEnable.call(gl, gl.STENCIL_TEST);
  38223. }
  38224. self.realColorMask.apply(gl, self.colorMask);
  38225. self.realViewport.apply(gl, self.viewport);
  38226. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  38227. self.realClearColor.apply(gl, self.clearColor);
  38228. }
  38229. });
  38230. if (isIOS()) {
  38231. var canvas = gl.canvas;
  38232. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  38233. self.bufferWidth = canvas.width;
  38234. self.bufferHeight = canvas.height;
  38235. self.onResize();
  38236. }
  38237. }
  38238. };
  38239. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  38240. var gl = this.gl;
  38241. var self = this;
  38242. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  38243. glPreserveState(gl, glState, function (gl) {
  38244. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  38245. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38246. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  38247. if (!self.indexCount) {
  38248. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  38249. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  38250. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  38251. self.indexCount = indices.length;
  38252. }
  38253. });
  38254. };
  38255. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  38256. var vertices = new Float32Array(2 * width * height * 5);
  38257. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  38258. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  38259. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  38260. var vidx = 0;
  38261. for (var e = 0; e < 2; e++) {
  38262. for (var j = 0; j < height; j++) {
  38263. for (var i = 0; i < width; i++, vidx++) {
  38264. var u = i / (width - 1);
  38265. var v = j / (height - 1);
  38266. var s = u;
  38267. var t = v;
  38268. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  38269. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  38270. var d = Math.sqrt(x * x + y * y);
  38271. var r = deviceInfo.distortion.distortInverse(d);
  38272. var p = x * r / d;
  38273. var q = y * r / d;
  38274. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  38275. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  38276. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  38277. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  38278. vertices[vidx * 5 + 0] = u;
  38279. vertices[vidx * 5 + 1] = v;
  38280. vertices[vidx * 5 + 2] = s;
  38281. vertices[vidx * 5 + 3] = t;
  38282. vertices[vidx * 5 + 4] = e;
  38283. }
  38284. }
  38285. var w = lensFrustum[2] - lensFrustum[0];
  38286. lensFrustum[0] = -(w + lensFrustum[0]);
  38287. lensFrustum[2] = w - lensFrustum[2];
  38288. w = noLensFrustum[2] - noLensFrustum[0];
  38289. noLensFrustum[0] = -(w + noLensFrustum[0]);
  38290. noLensFrustum[2] = w - noLensFrustum[2];
  38291. viewport.x = 1 - (viewport.x + viewport.width);
  38292. }
  38293. return vertices;
  38294. };
  38295. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  38296. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  38297. var halfwidth = width / 2;
  38298. var halfheight = height / 2;
  38299. var vidx = 0;
  38300. var iidx = 0;
  38301. for (var e = 0; e < 2; e++) {
  38302. for (var j = 0; j < height; j++) {
  38303. for (var i = 0; i < width; i++, vidx++) {
  38304. if (i == 0 || j == 0) continue;
  38305. if (i <= halfwidth == j <= halfheight) {
  38306. indices[iidx++] = vidx;
  38307. indices[iidx++] = vidx - width - 1;
  38308. indices[iidx++] = vidx - width;
  38309. indices[iidx++] = vidx - width - 1;
  38310. indices[iidx++] = vidx;
  38311. indices[iidx++] = vidx - 1;
  38312. } else {
  38313. indices[iidx++] = vidx - 1;
  38314. indices[iidx++] = vidx - width;
  38315. indices[iidx++] = vidx;
  38316. indices[iidx++] = vidx - width;
  38317. indices[iidx++] = vidx - 1;
  38318. indices[iidx++] = vidx - width - 1;
  38319. }
  38320. }
  38321. }
  38322. }
  38323. return indices;
  38324. };
  38325. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  38326. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  38327. if (descriptor.get === undefined || descriptor.set === undefined) {
  38328. descriptor.configurable = true;
  38329. descriptor.enumerable = true;
  38330. descriptor.get = function () {
  38331. return this.getAttribute(attrName);
  38332. };
  38333. descriptor.set = function (val) {
  38334. this.setAttribute(attrName, val);
  38335. };
  38336. }
  38337. return descriptor;
  38338. };
  38339. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  38340. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  38341. var DEG2RAD = Math.PI / 180.0;
  38342. var kAnglePerGearSection = 60;
  38343. var kOuterRimEndAngle = 12;
  38344. var kInnerRimBeginAngle = 20;
  38345. var kOuterRadius = 1;
  38346. var kMiddleRadius = 0.75;
  38347. var kInnerRadius = 0.3125;
  38348. var kCenterLineThicknessDp = 4;
  38349. var kButtonWidthDp = 28;
  38350. var kTouchSlopFactor = 1.5;
  38351. function CardboardUI(gl) {
  38352. this.gl = gl;
  38353. this.attribs = {
  38354. position: 0
  38355. };
  38356. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  38357. this.uniforms = getProgramUniforms(gl, this.program);
  38358. this.vertexBuffer = gl.createBuffer();
  38359. this.gearOffset = 0;
  38360. this.gearVertexCount = 0;
  38361. this.arrowOffset = 0;
  38362. this.arrowVertexCount = 0;
  38363. this.projMat = new Float32Array(16);
  38364. this.listener = null;
  38365. this.onResize();
  38366. }
  38367. CardboardUI.prototype.destroy = function () {
  38368. var gl = this.gl;
  38369. if (this.listener) {
  38370. gl.canvas.removeEventListener('click', this.listener, false);
  38371. }
  38372. gl.deleteProgram(this.program);
  38373. gl.deleteBuffer(this.vertexBuffer);
  38374. };
  38375. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  38376. var canvas = this.gl.canvas;
  38377. this.listener = function (event) {
  38378. var midline = canvas.clientWidth / 2;
  38379. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  38380. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  38381. optionsCallback(event);
  38382. }
  38383. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  38384. backCallback(event);
  38385. }
  38386. };
  38387. canvas.addEventListener('click', this.listener, false);
  38388. };
  38389. CardboardUI.prototype.onResize = function () {
  38390. var gl = this.gl;
  38391. var self = this;
  38392. var glState = [gl.ARRAY_BUFFER_BINDING];
  38393. glPreserveState(gl, glState, function (gl) {
  38394. var vertices = [];
  38395. var midline = gl.drawingBufferWidth / 2;
  38396. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  38397. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  38398. var dps = scalingRatio * window.devicePixelRatio;
  38399. var lineWidth = kCenterLineThicknessDp * dps / 2;
  38400. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  38401. var buttonScale = kButtonWidthDp * dps / 2;
  38402. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  38403. vertices.push(midline - lineWidth, buttonSize);
  38404. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  38405. vertices.push(midline + lineWidth, buttonSize);
  38406. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  38407. self.gearOffset = vertices.length / 2;
  38408. function addGearSegment(theta, r) {
  38409. var angle = (90 - theta) * DEG2RAD;
  38410. var x = Math.cos(angle);
  38411. var y = Math.sin(angle);
  38412. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  38413. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  38414. }
  38415. for (var i = 0; i <= 6; i++) {
  38416. var segmentTheta = i * kAnglePerGearSection;
  38417. addGearSegment(segmentTheta, kOuterRadius);
  38418. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  38419. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  38420. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  38421. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  38422. }
  38423. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  38424. self.arrowOffset = vertices.length / 2;
  38425. function addArrowVertex(x, y) {
  38426. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  38427. }
  38428. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  38429. addArrowVertex(0, buttonScale);
  38430. addArrowVertex(buttonScale, 0);
  38431. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  38432. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  38433. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  38434. addArrowVertex(0, buttonScale);
  38435. addArrowVertex(buttonScale, buttonScale * 2);
  38436. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  38437. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  38438. addArrowVertex(0, buttonScale);
  38439. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  38440. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  38441. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  38442. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  38443. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  38444. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38445. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  38446. });
  38447. };
  38448. CardboardUI.prototype.render = function () {
  38449. var gl = this.gl;
  38450. var self = this;
  38451. 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];
  38452. glPreserveState(gl, glState, function (gl) {
  38453. gl.disable(gl.CULL_FACE);
  38454. gl.disable(gl.DEPTH_TEST);
  38455. gl.disable(gl.BLEND);
  38456. gl.disable(gl.SCISSOR_TEST);
  38457. gl.disable(gl.STENCIL_TEST);
  38458. gl.colorMask(true, true, true, true);
  38459. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  38460. self.renderNoState();
  38461. });
  38462. };
  38463. CardboardUI.prototype.renderNoState = function () {
  38464. var gl = this.gl;
  38465. gl.useProgram(this.program);
  38466. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  38467. gl.enableVertexAttribArray(this.attribs.position);
  38468. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  38469. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  38470. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  38471. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  38472. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  38473. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  38474. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  38475. };
  38476. function Distortion(coefficients) {
  38477. this.coefficients = coefficients;
  38478. }
  38479. Distortion.prototype.distortInverse = function (radius) {
  38480. var r0 = 0;
  38481. var r1 = 1;
  38482. var dr0 = radius - this.distort(r0);
  38483. while (Math.abs(r1 - r0) > 0.0001 ) {
  38484. var dr1 = radius - this.distort(r1);
  38485. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  38486. r0 = r1;
  38487. r1 = r2;
  38488. dr0 = dr1;
  38489. }
  38490. return r1;
  38491. };
  38492. Distortion.prototype.distort = function (radius) {
  38493. var r2 = radius * radius;
  38494. var ret = 0;
  38495. for (var i = 0; i < this.coefficients.length; i++) {
  38496. ret = r2 * (ret + this.coefficients[i]);
  38497. }
  38498. return (ret + 1) * radius;
  38499. };
  38500. var degToRad = Math.PI / 180;
  38501. var radToDeg = 180 / Math.PI;
  38502. var Vector3 = function Vector3(x, y, z) {
  38503. this.x = x || 0;
  38504. this.y = y || 0;
  38505. this.z = z || 0;
  38506. };
  38507. Vector3.prototype = {
  38508. constructor: Vector3,
  38509. set: function set(x, y, z) {
  38510. this.x = x;
  38511. this.y = y;
  38512. this.z = z;
  38513. return this;
  38514. },
  38515. copy: function copy(v) {
  38516. this.x = v.x;
  38517. this.y = v.y;
  38518. this.z = v.z;
  38519. return this;
  38520. },
  38521. length: function length() {
  38522. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  38523. },
  38524. normalize: function normalize() {
  38525. var scalar = this.length();
  38526. if (scalar !== 0) {
  38527. var invScalar = 1 / scalar;
  38528. this.multiplyScalar(invScalar);
  38529. } else {
  38530. this.x = 0;
  38531. this.y = 0;
  38532. this.z = 0;
  38533. }
  38534. return this;
  38535. },
  38536. multiplyScalar: function multiplyScalar(scalar) {
  38537. this.x *= scalar;
  38538. this.y *= scalar;
  38539. this.z *= scalar;
  38540. },
  38541. applyQuaternion: function applyQuaternion(q) {
  38542. var x = this.x;
  38543. var y = this.y;
  38544. var z = this.z;
  38545. var qx = q.x;
  38546. var qy = q.y;
  38547. var qz = q.z;
  38548. var qw = q.w;
  38549. var ix = qw * x + qy * z - qz * y;
  38550. var iy = qw * y + qz * x - qx * z;
  38551. var iz = qw * z + qx * y - qy * x;
  38552. var iw = -qx * x - qy * y - qz * z;
  38553. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  38554. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  38555. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  38556. return this;
  38557. },
  38558. dot: function dot(v) {
  38559. return this.x * v.x + this.y * v.y + this.z * v.z;
  38560. },
  38561. crossVectors: function crossVectors(a, b) {
  38562. var ax = a.x,
  38563. ay = a.y,
  38564. az = a.z;
  38565. var bx = b.x,
  38566. by = b.y,
  38567. bz = b.z;
  38568. this.x = ay * bz - az * by;
  38569. this.y = az * bx - ax * bz;
  38570. this.z = ax * by - ay * bx;
  38571. return this;
  38572. }
  38573. };
  38574. var Quaternion = function Quaternion(x, y, z, w) {
  38575. this.x = x || 0;
  38576. this.y = y || 0;
  38577. this.z = z || 0;
  38578. this.w = w !== undefined ? w : 1;
  38579. };
  38580. Quaternion.prototype = {
  38581. constructor: Quaternion,
  38582. set: function set(x, y, z, w) {
  38583. this.x = x;
  38584. this.y = y;
  38585. this.z = z;
  38586. this.w = w;
  38587. return this;
  38588. },
  38589. copy: function copy(quaternion) {
  38590. this.x = quaternion.x;
  38591. this.y = quaternion.y;
  38592. this.z = quaternion.z;
  38593. this.w = quaternion.w;
  38594. return this;
  38595. },
  38596. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  38597. var c1 = Math.cos(x / 2);
  38598. var c2 = Math.cos(y / 2);
  38599. var c3 = Math.cos(z / 2);
  38600. var s1 = Math.sin(x / 2);
  38601. var s2 = Math.sin(y / 2);
  38602. var s3 = Math.sin(z / 2);
  38603. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  38604. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  38605. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  38606. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  38607. return this;
  38608. },
  38609. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  38610. var c1 = Math.cos(x / 2);
  38611. var c2 = Math.cos(y / 2);
  38612. var c3 = Math.cos(z / 2);
  38613. var s1 = Math.sin(x / 2);
  38614. var s2 = Math.sin(y / 2);
  38615. var s3 = Math.sin(z / 2);
  38616. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  38617. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  38618. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  38619. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  38620. return this;
  38621. },
  38622. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  38623. var halfAngle = angle / 2,
  38624. s = Math.sin(halfAngle);
  38625. this.x = axis.x * s;
  38626. this.y = axis.y * s;
  38627. this.z = axis.z * s;
  38628. this.w = Math.cos(halfAngle);
  38629. return this;
  38630. },
  38631. multiply: function multiply(q) {
  38632. return this.multiplyQuaternions(this, q);
  38633. },
  38634. multiplyQuaternions: function multiplyQuaternions(a, b) {
  38635. var qax = a.x,
  38636. qay = a.y,
  38637. qaz = a.z,
  38638. qaw = a.w;
  38639. var qbx = b.x,
  38640. qby = b.y,
  38641. qbz = b.z,
  38642. qbw = b.w;
  38643. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  38644. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  38645. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  38646. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  38647. return this;
  38648. },
  38649. inverse: function inverse() {
  38650. this.x *= -1;
  38651. this.y *= -1;
  38652. this.z *= -1;
  38653. this.normalize();
  38654. return this;
  38655. },
  38656. normalize: function normalize() {
  38657. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  38658. if (l === 0) {
  38659. this.x = 0;
  38660. this.y = 0;
  38661. this.z = 0;
  38662. this.w = 1;
  38663. } else {
  38664. l = 1 / l;
  38665. this.x = this.x * l;
  38666. this.y = this.y * l;
  38667. this.z = this.z * l;
  38668. this.w = this.w * l;
  38669. }
  38670. return this;
  38671. },
  38672. slerp: function slerp(qb, t) {
  38673. if (t === 0) return this;
  38674. if (t === 1) return this.copy(qb);
  38675. var x = this.x,
  38676. y = this.y,
  38677. z = this.z,
  38678. w = this.w;
  38679. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  38680. if (cosHalfTheta < 0) {
  38681. this.w = -qb.w;
  38682. this.x = -qb.x;
  38683. this.y = -qb.y;
  38684. this.z = -qb.z;
  38685. cosHalfTheta = -cosHalfTheta;
  38686. } else {
  38687. this.copy(qb);
  38688. }
  38689. if (cosHalfTheta >= 1.0) {
  38690. this.w = w;
  38691. this.x = x;
  38692. this.y = y;
  38693. this.z = z;
  38694. return this;
  38695. }
  38696. var halfTheta = Math.acos(cosHalfTheta);
  38697. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  38698. if (Math.abs(sinHalfTheta) < 0.001) {
  38699. this.w = 0.5 * (w + this.w);
  38700. this.x = 0.5 * (x + this.x);
  38701. this.y = 0.5 * (y + this.y);
  38702. this.z = 0.5 * (z + this.z);
  38703. return this;
  38704. }
  38705. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  38706. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  38707. this.w = w * ratioA + this.w * ratioB;
  38708. this.x = x * ratioA + this.x * ratioB;
  38709. this.y = y * ratioA + this.y * ratioB;
  38710. this.z = z * ratioA + this.z * ratioB;
  38711. return this;
  38712. },
  38713. setFromUnitVectors: function () {
  38714. var v1, r;
  38715. var EPS = 0.000001;
  38716. return function (vFrom, vTo) {
  38717. if (v1 === undefined) v1 = new Vector3();
  38718. r = vFrom.dot(vTo) + 1;
  38719. if (r < EPS) {
  38720. r = 0;
  38721. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  38722. v1.set(-vFrom.y, vFrom.x, 0);
  38723. } else {
  38724. v1.set(0, -vFrom.z, vFrom.y);
  38725. }
  38726. } else {
  38727. v1.crossVectors(vFrom, vTo);
  38728. }
  38729. this.x = v1.x;
  38730. this.y = v1.y;
  38731. this.z = v1.z;
  38732. this.w = r;
  38733. this.normalize();
  38734. return this;
  38735. };
  38736. }()
  38737. };
  38738. function Device(params) {
  38739. this.width = params.width || getScreenWidth();
  38740. this.height = params.height || getScreenHeight();
  38741. this.widthMeters = params.widthMeters;
  38742. this.heightMeters = params.heightMeters;
  38743. this.bevelMeters = params.bevelMeters;
  38744. }
  38745. var DEFAULT_ANDROID = new Device({
  38746. widthMeters: 0.110,
  38747. heightMeters: 0.062,
  38748. bevelMeters: 0.004
  38749. });
  38750. var DEFAULT_IOS = new Device({
  38751. widthMeters: 0.1038,
  38752. heightMeters: 0.0584,
  38753. bevelMeters: 0.004
  38754. });
  38755. var Viewers = {
  38756. CardboardV1: new CardboardViewer({
  38757. id: 'CardboardV1',
  38758. label: 'Cardboard I/O 2014',
  38759. fov: 40,
  38760. interLensDistance: 0.060,
  38761. baselineLensDistance: 0.035,
  38762. screenLensDistance: 0.042,
  38763. distortionCoefficients: [0.441, 0.156],
  38764. 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]
  38765. }),
  38766. CardboardV2: new CardboardViewer({
  38767. id: 'CardboardV2',
  38768. label: 'Cardboard I/O 2015',
  38769. fov: 60,
  38770. interLensDistance: 0.064,
  38771. baselineLensDistance: 0.035,
  38772. screenLensDistance: 0.039,
  38773. distortionCoefficients: [0.34, 0.55],
  38774. 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]
  38775. })
  38776. };
  38777. function DeviceInfo(deviceParams) {
  38778. this.viewer = Viewers.CardboardV2;
  38779. this.updateDeviceParams(deviceParams);
  38780. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  38781. }
  38782. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  38783. this.device = this.determineDevice_(deviceParams) || this.device;
  38784. };
  38785. DeviceInfo.prototype.getDevice = function () {
  38786. return this.device;
  38787. };
  38788. DeviceInfo.prototype.setViewer = function (viewer) {
  38789. this.viewer = viewer;
  38790. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  38791. };
  38792. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  38793. if (!deviceParams) {
  38794. if (isIOS()) {
  38795. console.warn('Using fallback iOS device measurements.');
  38796. return DEFAULT_IOS;
  38797. } else {
  38798. console.warn('Using fallback Android device measurements.');
  38799. return DEFAULT_ANDROID;
  38800. }
  38801. }
  38802. var METERS_PER_INCH = 0.0254;
  38803. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  38804. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  38805. var width = getScreenWidth();
  38806. var height = getScreenHeight();
  38807. return new Device({
  38808. widthMeters: metersPerPixelX * width,
  38809. heightMeters: metersPerPixelY * height,
  38810. bevelMeters: deviceParams.bevelMm * 0.001
  38811. });
  38812. };
  38813. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  38814. var viewer = this.viewer;
  38815. var device = this.device;
  38816. var distortion = this.distortion;
  38817. var eyeToScreenDistance = viewer.screenLensDistance;
  38818. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  38819. var innerDist = viewer.interLensDistance / 2;
  38820. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  38821. var topDist = device.heightMeters - bottomDist;
  38822. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  38823. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  38824. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  38825. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  38826. return {
  38827. leftDegrees: Math.min(outerAngle, viewer.fov),
  38828. rightDegrees: Math.min(innerAngle, viewer.fov),
  38829. downDegrees: Math.min(bottomAngle, viewer.fov),
  38830. upDegrees: Math.min(topAngle, viewer.fov)
  38831. };
  38832. };
  38833. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  38834. var viewer = this.viewer;
  38835. var device = this.device;
  38836. var distortion = this.distortion;
  38837. var fovLeft = Math.tan(-degToRad * viewer.fov);
  38838. var fovTop = Math.tan(degToRad * viewer.fov);
  38839. var fovRight = Math.tan(degToRad * viewer.fov);
  38840. var fovBottom = Math.tan(-degToRad * viewer.fov);
  38841. var halfWidth = device.widthMeters / 4;
  38842. var halfHeight = device.heightMeters / 2;
  38843. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  38844. var centerX = viewer.interLensDistance / 2 - halfWidth;
  38845. var centerY = -verticalLensOffset;
  38846. var centerZ = viewer.screenLensDistance;
  38847. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  38848. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  38849. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  38850. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  38851. var result = new Float32Array(4);
  38852. result[0] = Math.max(fovLeft, screenLeft);
  38853. result[1] = Math.min(fovTop, screenTop);
  38854. result[2] = Math.min(fovRight, screenRight);
  38855. result[3] = Math.max(fovBottom, screenBottom);
  38856. return result;
  38857. };
  38858. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  38859. var viewer = this.viewer;
  38860. var device = this.device;
  38861. var distortion = this.distortion;
  38862. var result = new Float32Array(4);
  38863. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  38864. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  38865. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  38866. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  38867. var halfWidth = device.widthMeters / 4;
  38868. var halfHeight = device.heightMeters / 2;
  38869. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  38870. var centerX = viewer.interLensDistance / 2 - halfWidth;
  38871. var centerY = -verticalLensOffset;
  38872. var centerZ = viewer.screenLensDistance;
  38873. var screenLeft = (centerX - halfWidth) / centerZ;
  38874. var screenTop = (centerY + halfHeight) / centerZ;
  38875. var screenRight = (centerX + halfWidth) / centerZ;
  38876. var screenBottom = (centerY - halfHeight) / centerZ;
  38877. result[0] = Math.max(fovLeft, screenLeft);
  38878. result[1] = Math.min(fovTop, screenTop);
  38879. result[2] = Math.min(fovRight, screenRight);
  38880. result[3] = Math.max(fovBottom, screenBottom);
  38881. return result;
  38882. };
  38883. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  38884. var viewer = this.viewer;
  38885. var device = this.device;
  38886. var dist = viewer.screenLensDistance;
  38887. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  38888. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  38889. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  38890. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  38891. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  38892. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  38893. return {
  38894. x: left,
  38895. y: bottom,
  38896. width: right - left,
  38897. height: top - bottom
  38898. };
  38899. };
  38900. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  38901. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  38902. };
  38903. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  38904. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  38905. return {
  38906. leftDegrees: fov.rightDegrees,
  38907. rightDegrees: fov.leftDegrees,
  38908. upDegrees: fov.upDegrees,
  38909. downDegrees: fov.downDegrees
  38910. };
  38911. };
  38912. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  38913. var p = this.getUndistortedParams_();
  38914. return {
  38915. leftDegrees: radToDeg * Math.atan(p.outerDist),
  38916. rightDegrees: radToDeg * Math.atan(p.innerDist),
  38917. downDegrees: radToDeg * Math.atan(p.bottomDist),
  38918. upDegrees: radToDeg * Math.atan(p.topDist)
  38919. };
  38920. };
  38921. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  38922. var p = this.getUndistortedParams_();
  38923. var viewer = this.viewer;
  38924. var device = this.device;
  38925. var eyeToScreenDistance = viewer.screenLensDistance;
  38926. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38927. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38928. var xPxPerTanAngle = device.width / screenWidth;
  38929. var yPxPerTanAngle = device.height / screenHeight;
  38930. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  38931. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  38932. return {
  38933. x: x,
  38934. y: y,
  38935. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  38936. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  38937. };
  38938. };
  38939. DeviceInfo.prototype.getUndistortedParams_ = function () {
  38940. var viewer = this.viewer;
  38941. var device = this.device;
  38942. var distortion = this.distortion;
  38943. var eyeToScreenDistance = viewer.screenLensDistance;
  38944. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  38945. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38946. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38947. var eyePosX = screenWidth / 2 - halfLensDistance;
  38948. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  38949. var maxFov = viewer.fov;
  38950. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  38951. var outerDist = Math.min(eyePosX, viewerMax);
  38952. var innerDist = Math.min(halfLensDistance, viewerMax);
  38953. var bottomDist = Math.min(eyePosY, viewerMax);
  38954. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  38955. return {
  38956. outerDist: outerDist,
  38957. innerDist: innerDist,
  38958. topDist: topDist,
  38959. bottomDist: bottomDist,
  38960. eyePosX: eyePosX,
  38961. eyePosY: eyePosY
  38962. };
  38963. };
  38964. function CardboardViewer(params) {
  38965. this.id = params.id;
  38966. this.label = params.label;
  38967. this.fov = params.fov;
  38968. this.interLensDistance = params.interLensDistance;
  38969. this.baselineLensDistance = params.baselineLensDistance;
  38970. this.screenLensDistance = params.screenLensDistance;
  38971. this.distortionCoefficients = params.distortionCoefficients;
  38972. this.inverseCoefficients = params.inverseCoefficients;
  38973. }
  38974. DeviceInfo.Viewers = Viewers;
  38975. var format = 1;
  38976. var last_updated = "2018-02-20T22:55:10Z";
  38977. 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}];
  38978. var DPDB_CACHE = {
  38979. format: format,
  38980. last_updated: last_updated,
  38981. devices: devices
  38982. };
  38983. function Dpdb(url, onDeviceParamsUpdated) {
  38984. this.dpdb = DPDB_CACHE;
  38985. this.recalculateDeviceParams_();
  38986. if (url) {
  38987. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  38988. var xhr = new XMLHttpRequest();
  38989. var obj = this;
  38990. xhr.open('GET', url, true);
  38991. xhr.addEventListener('load', function () {
  38992. obj.loading = false;
  38993. if (xhr.status >= 200 && xhr.status <= 299) {
  38994. obj.dpdb = JSON.parse(xhr.response);
  38995. obj.recalculateDeviceParams_();
  38996. } else {
  38997. console.error('Error loading online DPDB!');
  38998. }
  38999. });
  39000. xhr.send();
  39001. }
  39002. }
  39003. Dpdb.prototype.getDeviceParams = function () {
  39004. return this.deviceParams;
  39005. };
  39006. Dpdb.prototype.recalculateDeviceParams_ = function () {
  39007. var newDeviceParams = this.calcDeviceParams_();
  39008. if (newDeviceParams) {
  39009. this.deviceParams = newDeviceParams;
  39010. if (this.onDeviceParamsUpdated) {
  39011. this.onDeviceParamsUpdated(this.deviceParams);
  39012. }
  39013. } else {
  39014. console.error('Failed to recalculate device parameters.');
  39015. }
  39016. };
  39017. Dpdb.prototype.calcDeviceParams_ = function () {
  39018. var db = this.dpdb;
  39019. if (!db) {
  39020. console.error('DPDB not available.');
  39021. return null;
  39022. }
  39023. if (db.format != 1) {
  39024. console.error('DPDB has unexpected format version.');
  39025. return null;
  39026. }
  39027. if (!db.devices || !db.devices.length) {
  39028. console.error('DPDB does not have a devices section.');
  39029. return null;
  39030. }
  39031. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  39032. var width = getScreenWidth();
  39033. var height = getScreenHeight();
  39034. if (!db.devices) {
  39035. console.error('DPDB has no devices section.');
  39036. return null;
  39037. }
  39038. for (var i = 0; i < db.devices.length; i++) {
  39039. var device = db.devices[i];
  39040. if (!device.rules) {
  39041. console.warn('Device[' + i + '] has no rules section.');
  39042. continue;
  39043. }
  39044. if (device.type != 'ios' && device.type != 'android') {
  39045. console.warn('Device[' + i + '] has invalid type.');
  39046. continue;
  39047. }
  39048. if (isIOS() != (device.type == 'ios')) continue;
  39049. var matched = false;
  39050. for (var j = 0; j < device.rules.length; j++) {
  39051. var rule = device.rules[j];
  39052. if (this.matchRule_(rule, userAgent, width, height)) {
  39053. matched = true;
  39054. break;
  39055. }
  39056. }
  39057. if (!matched) continue;
  39058. var xdpi = device.dpi[0] || device.dpi;
  39059. var ydpi = device.dpi[1] || device.dpi;
  39060. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  39061. }
  39062. console.warn('No DPDB device match.');
  39063. return null;
  39064. };
  39065. Dpdb.prototype.matchRule_ = function (rule, ua, screenWidth, screenHeight) {
  39066. if (!rule.ua && !rule.res) return false;
  39067. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  39068. if (rule.res) {
  39069. if (!rule.res[0] || !rule.res[1]) return false;
  39070. var resX = rule.res[0];
  39071. var resY = rule.res[1];
  39072. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  39073. return false;
  39074. }
  39075. }
  39076. return true;
  39077. };
  39078. function DeviceParams(params) {
  39079. this.xdpi = params.xdpi;
  39080. this.ydpi = params.ydpi;
  39081. this.bevelMm = params.bevelMm;
  39082. }
  39083. function SensorSample(sample, timestampS) {
  39084. this.set(sample, timestampS);
  39085. }
  39086. SensorSample.prototype.set = function (sample, timestampS) {
  39087. this.sample = sample;
  39088. this.timestampS = timestampS;
  39089. };
  39090. SensorSample.prototype.copy = function (sensorSample) {
  39091. this.set(sensorSample.sample, sensorSample.timestampS);
  39092. };
  39093. function ComplementaryFilter(kFilter, isDebug) {
  39094. this.kFilter = kFilter;
  39095. this.isDebug = isDebug;
  39096. this.currentAccelMeasurement = new SensorSample();
  39097. this.currentGyroMeasurement = new SensorSample();
  39098. this.previousGyroMeasurement = new SensorSample();
  39099. if (isIOS()) {
  39100. this.filterQ = new Quaternion(-1, 0, 0, 1);
  39101. } else {
  39102. this.filterQ = new Quaternion(1, 0, 0, 1);
  39103. }
  39104. this.previousFilterQ = new Quaternion();
  39105. this.previousFilterQ.copy(this.filterQ);
  39106. this.accelQ = new Quaternion();
  39107. this.isOrientationInitialized = false;
  39108. this.estimatedGravity = new Vector3();
  39109. this.measuredGravity = new Vector3();
  39110. this.gyroIntegralQ = new Quaternion();
  39111. }
  39112. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  39113. this.currentAccelMeasurement.set(vector, timestampS);
  39114. };
  39115. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  39116. this.currentGyroMeasurement.set(vector, timestampS);
  39117. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  39118. if (isTimestampDeltaValid(deltaT)) {
  39119. this.run_();
  39120. }
  39121. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  39122. };
  39123. ComplementaryFilter.prototype.run_ = function () {
  39124. if (!this.isOrientationInitialized) {
  39125. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  39126. this.previousFilterQ.copy(this.accelQ);
  39127. this.isOrientationInitialized = true;
  39128. return;
  39129. }
  39130. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  39131. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  39132. this.gyroIntegralQ.multiply(gyroDeltaQ);
  39133. this.filterQ.copy(this.previousFilterQ);
  39134. this.filterQ.multiply(gyroDeltaQ);
  39135. var invFilterQ = new Quaternion();
  39136. invFilterQ.copy(this.filterQ);
  39137. invFilterQ.inverse();
  39138. this.estimatedGravity.set(0, 0, -1);
  39139. this.estimatedGravity.applyQuaternion(invFilterQ);
  39140. this.estimatedGravity.normalize();
  39141. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  39142. this.measuredGravity.normalize();
  39143. var deltaQ = new Quaternion();
  39144. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  39145. deltaQ.inverse();
  39146. if (this.isDebug) {
  39147. 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));
  39148. }
  39149. var targetQ = new Quaternion();
  39150. targetQ.copy(this.filterQ);
  39151. targetQ.multiply(deltaQ);
  39152. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  39153. this.previousFilterQ.copy(this.filterQ);
  39154. };
  39155. ComplementaryFilter.prototype.getOrientation = function () {
  39156. return this.filterQ;
  39157. };
  39158. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  39159. var normAccel = new Vector3();
  39160. normAccel.copy(accel);
  39161. normAccel.normalize();
  39162. var quat = new Quaternion();
  39163. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  39164. quat.inverse();
  39165. return quat;
  39166. };
  39167. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  39168. var quat = new Quaternion();
  39169. var axis = new Vector3();
  39170. axis.copy(gyro);
  39171. axis.normalize();
  39172. quat.setFromAxisAngle(axis, gyro.length() * dt);
  39173. return quat;
  39174. };
  39175. function PosePredictor(predictionTimeS, isDebug) {
  39176. this.predictionTimeS = predictionTimeS;
  39177. this.isDebug = isDebug;
  39178. this.previousQ = new Quaternion();
  39179. this.previousTimestampS = null;
  39180. this.deltaQ = new Quaternion();
  39181. this.outQ = new Quaternion();
  39182. }
  39183. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  39184. if (!this.previousTimestampS) {
  39185. this.previousQ.copy(currentQ);
  39186. this.previousTimestampS = timestampS;
  39187. return currentQ;
  39188. }
  39189. var axis = new Vector3();
  39190. axis.copy(gyro);
  39191. axis.normalize();
  39192. var angularSpeed = gyro.length();
  39193. if (angularSpeed < degToRad * 20) {
  39194. if (this.isDebug) {
  39195. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  39196. }
  39197. this.outQ.copy(currentQ);
  39198. this.previousQ.copy(currentQ);
  39199. return this.outQ;
  39200. }
  39201. var predictAngle = angularSpeed * this.predictionTimeS;
  39202. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  39203. this.outQ.copy(this.previousQ);
  39204. this.outQ.multiply(this.deltaQ);
  39205. this.previousQ.copy(currentQ);
  39206. this.previousTimestampS = timestampS;
  39207. return this.outQ;
  39208. };
  39209. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  39210. this.yawOnly = yawOnly;
  39211. this.accelerometer = new Vector3();
  39212. this.gyroscope = new Vector3();
  39213. this.filter = new ComplementaryFilter(kFilter, isDebug);
  39214. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  39215. this.isFirefoxAndroid = isFirefoxAndroid();
  39216. this.isIOS = isIOS();
  39217. var chromeVersion = getChromeVersion();
  39218. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  39219. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion();
  39220. this.filterToWorldQ = new Quaternion();
  39221. if (isIOS()) {
  39222. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  39223. } else {
  39224. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  39225. }
  39226. this.inverseWorldToScreenQ = new Quaternion();
  39227. this.worldToScreenQ = new Quaternion();
  39228. this.originalPoseAdjustQ = new Quaternion();
  39229. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  39230. this.setScreenTransform_();
  39231. if (isLandscapeMode()) {
  39232. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  39233. }
  39234. this.resetQ = new Quaternion();
  39235. this.orientationOut_ = new Float32Array(4);
  39236. this.start();
  39237. }
  39238. FusionPoseSensor.prototype.getPosition = function () {
  39239. return null;
  39240. };
  39241. FusionPoseSensor.prototype.getOrientation = function () {
  39242. var orientation = void 0;
  39243. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  39244. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  39245. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  39246. var y = new Quaternion();
  39247. if (window.orientation === -90) {
  39248. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  39249. } else {
  39250. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  39251. }
  39252. return z.multiply(y);
  39253. }();
  39254. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  39255. var q = new Quaternion();
  39256. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  39257. return q;
  39258. }();
  39259. orientation = this._deviceOrientationQ;
  39260. var out = new Quaternion();
  39261. out.copy(orientation);
  39262. out.multiply(this.deviceOrientationFilterToWorldQ);
  39263. out.multiply(this.resetQ);
  39264. out.multiply(this.worldToScreenQ);
  39265. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  39266. if (this.yawOnly) {
  39267. out.x = 0;
  39268. out.z = 0;
  39269. out.normalize();
  39270. }
  39271. this.orientationOut_[0] = out.x;
  39272. this.orientationOut_[1] = out.y;
  39273. this.orientationOut_[2] = out.z;
  39274. this.orientationOut_[3] = out.w;
  39275. return this.orientationOut_;
  39276. } else {
  39277. var filterOrientation = this.filter.getOrientation();
  39278. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  39279. }
  39280. var out = new Quaternion();
  39281. out.copy(this.filterToWorldQ);
  39282. out.multiply(this.resetQ);
  39283. out.multiply(orientation);
  39284. out.multiply(this.worldToScreenQ);
  39285. if (this.yawOnly) {
  39286. out.x = 0;
  39287. out.z = 0;
  39288. out.normalize();
  39289. }
  39290. this.orientationOut_[0] = out.x;
  39291. this.orientationOut_[1] = out.y;
  39292. this.orientationOut_[2] = out.z;
  39293. this.orientationOut_[3] = out.w;
  39294. return this.orientationOut_;
  39295. };
  39296. FusionPoseSensor.prototype.resetPose = function () {
  39297. this.resetQ.copy(this.filter.getOrientation());
  39298. this.resetQ.x = 0;
  39299. this.resetQ.y = 0;
  39300. this.resetQ.z *= -1;
  39301. this.resetQ.normalize();
  39302. if (isLandscapeMode()) {
  39303. this.resetQ.multiply(this.inverseWorldToScreenQ);
  39304. }
  39305. this.resetQ.multiply(this.originalPoseAdjustQ);
  39306. };
  39307. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  39308. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  39309. var alpha = e.alpha,
  39310. beta = e.beta,
  39311. gamma = e.gamma;
  39312. alpha = (alpha || 0) * Math.PI / 180;
  39313. beta = (beta || 0) * Math.PI / 180;
  39314. gamma = (gamma || 0) * Math.PI / 180;
  39315. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  39316. };
  39317. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  39318. this.updateDeviceMotion_(deviceMotion);
  39319. };
  39320. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  39321. var accGravity = deviceMotion.accelerationIncludingGravity;
  39322. var rotRate = deviceMotion.rotationRate;
  39323. var timestampS = deviceMotion.timeStamp / 1000;
  39324. var deltaS = timestampS - this.previousTimestampS;
  39325. if (deltaS < 0) {
  39326. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  39327. this.previousTimestampS = timestampS;
  39328. return;
  39329. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  39330. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  39331. this.previousTimestampS = timestampS;
  39332. return;
  39333. }
  39334. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  39335. if (isR7()) {
  39336. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  39337. } else {
  39338. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  39339. }
  39340. if (!this.isDeviceMotionInRadians) {
  39341. this.gyroscope.multiplyScalar(Math.PI / 180);
  39342. }
  39343. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  39344. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  39345. this.previousTimestampS = timestampS;
  39346. };
  39347. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  39348. this.setScreenTransform_();
  39349. };
  39350. FusionPoseSensor.prototype.onMessage_ = function (event) {
  39351. var message = event.data;
  39352. if (!message || !message.type) {
  39353. return;
  39354. }
  39355. var type = message.type.toLowerCase();
  39356. if (type !== 'devicemotion') {
  39357. return;
  39358. }
  39359. this.updateDeviceMotion_(message.deviceMotionEvent);
  39360. };
  39361. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  39362. this.worldToScreenQ.set(0, 0, 0, 1);
  39363. switch (window.orientation) {
  39364. case 0:
  39365. break;
  39366. case 90:
  39367. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  39368. break;
  39369. case -90:
  39370. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  39371. break;
  39372. case 180:
  39373. break;
  39374. }
  39375. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  39376. this.inverseWorldToScreenQ.inverse();
  39377. };
  39378. FusionPoseSensor.prototype.start = function () {
  39379. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  39380. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  39381. this.onMessageCallback_ = this.onMessage_.bind(this);
  39382. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  39383. if (isIOS() && isInsideCrossOriginIFrame()) {
  39384. window.addEventListener('message', this.onMessageCallback_);
  39385. }
  39386. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  39387. if (this.isWithoutDeviceMotion) {
  39388. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  39389. } else {
  39390. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  39391. }
  39392. };
  39393. FusionPoseSensor.prototype.stop = function () {
  39394. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  39395. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  39396. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  39397. window.removeEventListener('message', this.onMessageCallback_);
  39398. };
  39399. var SENSOR_FREQUENCY = 60;
  39400. var X_AXIS = new Vector3(1, 0, 0);
  39401. var Z_AXIS = new Vector3(0, 0, 1);
  39402. var orientation = {};
  39403. if (screen.orientation) {
  39404. orientation = screen.orientation;
  39405. } else if (screen.msOrientation) {
  39406. orientation = screen.msOrientation;
  39407. } else {
  39408. Object.defineProperty(orientation, 'angle', {
  39409. get: function get$$1() {
  39410. return window.orientation || 0;
  39411. }
  39412. });
  39413. }
  39414. var SENSOR_TO_VR = new Quaternion();
  39415. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  39416. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  39417. var PoseSensor = function () {
  39418. function PoseSensor(config) {
  39419. classCallCheck(this, PoseSensor);
  39420. this.config = config;
  39421. this.sensor = null;
  39422. this.fusionSensor = null;
  39423. this._out = new Float32Array(4);
  39424. this.api = null;
  39425. this.errors = [];
  39426. this._sensorQ = new Quaternion();
  39427. this._worldToScreenQ = new Quaternion();
  39428. this._outQ = new Quaternion();
  39429. this._onSensorRead = this._onSensorRead.bind(this);
  39430. this._onSensorError = this._onSensorError.bind(this);
  39431. this._onOrientationChange = this._onOrientationChange.bind(this);
  39432. this._onOrientationChange();
  39433. this.init();
  39434. }
  39435. createClass(PoseSensor, [{
  39436. key: 'init',
  39437. value: function init() {
  39438. var sensor = null;
  39439. try {
  39440. sensor = new RelativeOrientationSensor({ frequency: SENSOR_FREQUENCY });
  39441. sensor.addEventListener('error', this._onSensorError);
  39442. } catch (error) {
  39443. this.errors.push(error);
  39444. if (error.name === 'SecurityError') {
  39445. console.error('Cannot construct sensors due to the Feature Policy');
  39446. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  39447. this.useDeviceMotion();
  39448. } else if (error.name === 'ReferenceError') {
  39449. this.useDeviceMotion();
  39450. } else {
  39451. console.error(error);
  39452. }
  39453. }
  39454. if (sensor) {
  39455. this.api = 'sensor';
  39456. this.sensor = sensor;
  39457. this.sensor.addEventListener('reading', this._onSensorRead);
  39458. this.sensor.start();
  39459. }
  39460. window.addEventListener('orientationchange', this._onOrientationChange);
  39461. }
  39462. }, {
  39463. key: 'useDeviceMotion',
  39464. value: function useDeviceMotion() {
  39465. this.api = 'devicemotion';
  39466. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  39467. }
  39468. }, {
  39469. key: 'getOrientation',
  39470. value: function getOrientation() {
  39471. if (this.fusionSensor) {
  39472. return this.fusionSensor.getOrientation();
  39473. }
  39474. if (!this.sensor || !this.sensor.quaternion) {
  39475. this._out[0] = this._out[1] = this._out[2] = 0;
  39476. this._out[3] = 1;
  39477. return this._out;
  39478. }
  39479. var q = this.sensor.quaternion;
  39480. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  39481. var out = this._outQ;
  39482. out.copy(SENSOR_TO_VR);
  39483. out.multiply(this._sensorQ);
  39484. out.multiply(this._worldToScreenQ);
  39485. if (this.config.YAW_ONLY) {
  39486. out.x = out.z = 0;
  39487. out.normalize();
  39488. }
  39489. this._out[0] = out.x;
  39490. this._out[1] = out.y;
  39491. this._out[2] = out.z;
  39492. this._out[3] = out.w;
  39493. return this._out;
  39494. }
  39495. }, {
  39496. key: '_onSensorError',
  39497. value: function _onSensorError(event) {
  39498. this.errors.push(event.error);
  39499. if (event.error.name === 'NotAllowedError') {
  39500. console.error('Permission to access sensor was denied');
  39501. } else if (event.error.name === 'NotReadableError') {
  39502. console.error('Sensor could not be read');
  39503. } else {
  39504. console.error(event.error);
  39505. }
  39506. }
  39507. }, {
  39508. key: '_onSensorRead',
  39509. value: function _onSensorRead() {}
  39510. }, {
  39511. key: '_onOrientationChange',
  39512. value: function _onOrientationChange() {
  39513. var angle = -orientation.angle * Math.PI / 180;
  39514. this._worldToScreenQ.setFromAxisAngle(Z_AXIS, angle);
  39515. }
  39516. }]);
  39517. return PoseSensor;
  39518. }();
  39519. 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+';
  39520. function RotateInstructions() {
  39521. this.loadIcon_();
  39522. var overlay = document.createElement('div');
  39523. var s = overlay.style;
  39524. s.position = 'fixed';
  39525. s.top = 0;
  39526. s.right = 0;
  39527. s.bottom = 0;
  39528. s.left = 0;
  39529. s.backgroundColor = 'gray';
  39530. s.fontFamily = 'sans-serif';
  39531. s.zIndex = 1000000;
  39532. var img = document.createElement('img');
  39533. img.src = this.icon;
  39534. var s = img.style;
  39535. s.marginLeft = '25%';
  39536. s.marginTop = '25%';
  39537. s.width = '50%';
  39538. overlay.appendChild(img);
  39539. var text = document.createElement('div');
  39540. var s = text.style;
  39541. s.textAlign = 'center';
  39542. s.fontSize = '16px';
  39543. s.lineHeight = '24px';
  39544. s.margin = '24px 25%';
  39545. s.width = '50%';
  39546. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  39547. overlay.appendChild(text);
  39548. var snackbar = document.createElement('div');
  39549. var s = snackbar.style;
  39550. s.backgroundColor = '#CFD8DC';
  39551. s.position = 'fixed';
  39552. s.bottom = 0;
  39553. s.width = '100%';
  39554. s.height = '48px';
  39555. s.padding = '14px 24px';
  39556. s.boxSizing = 'border-box';
  39557. s.color = '#656A6B';
  39558. overlay.appendChild(snackbar);
  39559. var snackbarText = document.createElement('div');
  39560. snackbarText.style.float = 'left';
  39561. snackbarText.innerHTML = 'No Cardboard viewer?';
  39562. var snackbarButton = document.createElement('a');
  39563. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  39564. snackbarButton.innerHTML = 'get one';
  39565. snackbarButton.target = '_blank';
  39566. var s = snackbarButton.style;
  39567. s.float = 'right';
  39568. s.fontWeight = 600;
  39569. s.textTransform = 'uppercase';
  39570. s.borderLeft = '1px solid gray';
  39571. s.paddingLeft = '24px';
  39572. s.textDecoration = 'none';
  39573. s.color = '#656A6B';
  39574. snackbar.appendChild(snackbarText);
  39575. snackbar.appendChild(snackbarButton);
  39576. this.overlay = overlay;
  39577. this.text = text;
  39578. this.hide();
  39579. }
  39580. RotateInstructions.prototype.show = function (parent) {
  39581. if (!parent && !this.overlay.parentElement) {
  39582. document.body.appendChild(this.overlay);
  39583. } else if (parent) {
  39584. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  39585. parent.appendChild(this.overlay);
  39586. }
  39587. this.overlay.style.display = 'block';
  39588. var img = this.overlay.querySelector('img');
  39589. var s = img.style;
  39590. if (isLandscapeMode()) {
  39591. s.width = '20%';
  39592. s.marginLeft = '40%';
  39593. s.marginTop = '3%';
  39594. } else {
  39595. s.width = '50%';
  39596. s.marginLeft = '25%';
  39597. s.marginTop = '25%';
  39598. }
  39599. };
  39600. RotateInstructions.prototype.hide = function () {
  39601. this.overlay.style.display = 'none';
  39602. };
  39603. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  39604. this.show(parent);
  39605. this.timer = setTimeout(this.hide.bind(this), ms);
  39606. };
  39607. RotateInstructions.prototype.disableShowTemporarily = function () {
  39608. clearTimeout(this.timer);
  39609. };
  39610. RotateInstructions.prototype.update = function () {
  39611. this.disableShowTemporarily();
  39612. if (!isLandscapeMode() && isMobile()) {
  39613. this.show();
  39614. } else {
  39615. this.hide();
  39616. }
  39617. };
  39618. RotateInstructions.prototype.loadIcon_ = function () {
  39619. this.icon = base64('image/svg+xml', rotateInstructionsAsset);
  39620. };
  39621. var DEFAULT_VIEWER = 'CardboardV1';
  39622. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  39623. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  39624. function ViewerSelector() {
  39625. try {
  39626. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  39627. } catch (error) {
  39628. console.error('Failed to load viewer profile: %s', error);
  39629. }
  39630. if (!this.selectedKey) {
  39631. this.selectedKey = DEFAULT_VIEWER;
  39632. }
  39633. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  39634. this.root = null;
  39635. this.onChangeCallbacks_ = [];
  39636. }
  39637. ViewerSelector.prototype.show = function (root) {
  39638. this.root = root;
  39639. root.appendChild(this.dialog);
  39640. var selected = this.dialog.querySelector('#' + this.selectedKey);
  39641. selected.checked = true;
  39642. this.dialog.style.display = 'block';
  39643. };
  39644. ViewerSelector.prototype.hide = function () {
  39645. if (this.root && this.root.contains(this.dialog)) {
  39646. this.root.removeChild(this.dialog);
  39647. }
  39648. this.dialog.style.display = 'none';
  39649. };
  39650. ViewerSelector.prototype.getCurrentViewer = function () {
  39651. return DeviceInfo.Viewers[this.selectedKey];
  39652. };
  39653. ViewerSelector.prototype.getSelectedKey_ = function () {
  39654. var input = this.dialog.querySelector('input[name=field]:checked');
  39655. if (input) {
  39656. return input.id;
  39657. }
  39658. return null;
  39659. };
  39660. ViewerSelector.prototype.onChange = function (cb) {
  39661. this.onChangeCallbacks_.push(cb);
  39662. };
  39663. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  39664. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  39665. this.onChangeCallbacks_[i](viewer);
  39666. }
  39667. };
  39668. ViewerSelector.prototype.onSave_ = function () {
  39669. this.selectedKey = this.getSelectedKey_();
  39670. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  39671. console.error('ViewerSelector.onSave_: this should never happen!');
  39672. return;
  39673. }
  39674. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  39675. try {
  39676. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  39677. } catch (error) {
  39678. console.error('Failed to save viewer profile: %s', error);
  39679. }
  39680. this.hide();
  39681. };
  39682. ViewerSelector.prototype.createDialog_ = function (options) {
  39683. var container = document.createElement('div');
  39684. container.classList.add(CLASS_NAME);
  39685. container.style.display = 'none';
  39686. var overlay = document.createElement('div');
  39687. var s = overlay.style;
  39688. s.position = 'fixed';
  39689. s.left = 0;
  39690. s.top = 0;
  39691. s.width = '100%';
  39692. s.height = '100%';
  39693. s.background = 'rgba(0, 0, 0, 0.3)';
  39694. overlay.addEventListener('click', this.hide.bind(this));
  39695. var width = 280;
  39696. var dialog = document.createElement('div');
  39697. var s = dialog.style;
  39698. s.boxSizing = 'border-box';
  39699. s.position = 'fixed';
  39700. s.top = '24px';
  39701. s.left = '50%';
  39702. s.marginLeft = -width / 2 + 'px';
  39703. s.width = width + 'px';
  39704. s.padding = '24px';
  39705. s.overflow = 'hidden';
  39706. s.background = '#fafafa';
  39707. s.fontFamily = "'Roboto', sans-serif";
  39708. s.boxShadow = '0px 5px 20px #666';
  39709. dialog.appendChild(this.createH1_('Select your viewer'));
  39710. for (var id in options) {
  39711. dialog.appendChild(this.createChoice_(id, options[id].label));
  39712. }
  39713. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  39714. container.appendChild(overlay);
  39715. container.appendChild(dialog);
  39716. return container;
  39717. };
  39718. ViewerSelector.prototype.createH1_ = function (name) {
  39719. var h1 = document.createElement('h1');
  39720. var s = h1.style;
  39721. s.color = 'black';
  39722. s.fontSize = '20px';
  39723. s.fontWeight = 'bold';
  39724. s.marginTop = 0;
  39725. s.marginBottom = '24px';
  39726. h1.innerHTML = name;
  39727. return h1;
  39728. };
  39729. ViewerSelector.prototype.createChoice_ = function (id, name) {
  39730. var div = document.createElement('div');
  39731. div.style.marginTop = '8px';
  39732. div.style.color = 'black';
  39733. var input = document.createElement('input');
  39734. input.style.fontSize = '30px';
  39735. input.setAttribute('id', id);
  39736. input.setAttribute('type', 'radio');
  39737. input.setAttribute('value', id);
  39738. input.setAttribute('name', 'field');
  39739. var label = document.createElement('label');
  39740. label.style.marginLeft = '4px';
  39741. label.setAttribute('for', id);
  39742. label.innerHTML = name;
  39743. div.appendChild(input);
  39744. div.appendChild(label);
  39745. return div;
  39746. };
  39747. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  39748. var button = document.createElement('button');
  39749. button.innerHTML = label;
  39750. var s = button.style;
  39751. s.float = 'right';
  39752. s.textTransform = 'uppercase';
  39753. s.color = '#1094f7';
  39754. s.fontSize = '14px';
  39755. s.letterSpacing = 0;
  39756. s.border = 0;
  39757. s.background = 'none';
  39758. s.marginTop = '16px';
  39759. button.addEventListener('click', onclick);
  39760. return button;
  39761. };
  39762. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  39763. function unwrapExports$$1 (x) {
  39764. return x && x.__esModule ? x['default'] : x;
  39765. }
  39766. function createCommonjsModule$$1(fn, module) {
  39767. return module = { exports: {} }, fn(module, module.exports), module.exports;
  39768. }
  39769. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  39770. (function webpackUniversalModuleDefinition(root, factory) {
  39771. module.exports = factory();
  39772. })(commonjsGlobal$$1, function() {
  39773. return (function(modules) {
  39774. var installedModules = {};
  39775. function __webpack_require__(moduleId) {
  39776. if(installedModules[moduleId]) {
  39777. return installedModules[moduleId].exports;
  39778. }
  39779. var module = installedModules[moduleId] = {
  39780. i: moduleId,
  39781. l: false,
  39782. exports: {}
  39783. };
  39784. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  39785. module.l = true;
  39786. return module.exports;
  39787. }
  39788. __webpack_require__.m = modules;
  39789. __webpack_require__.c = installedModules;
  39790. __webpack_require__.d = function(exports, name, getter) {
  39791. if(!__webpack_require__.o(exports, name)) {
  39792. Object.defineProperty(exports, name, {
  39793. configurable: false,
  39794. enumerable: true,
  39795. get: getter
  39796. });
  39797. }
  39798. };
  39799. __webpack_require__.n = function(module) {
  39800. var getter = module && module.__esModule ?
  39801. function getDefault() { return module['default']; } :
  39802. function getModuleExports() { return module; };
  39803. __webpack_require__.d(getter, 'a', getter);
  39804. return getter;
  39805. };
  39806. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  39807. __webpack_require__.p = "";
  39808. return __webpack_require__(__webpack_require__.s = 0);
  39809. })
  39810. ([
  39811. (function(module, exports, __webpack_require__) {
  39812. 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; }; }();
  39813. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  39814. var mediaFile = __webpack_require__(1);
  39815. 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;
  39816. var NoSleep = function () {
  39817. function NoSleep() {
  39818. _classCallCheck(this, NoSleep);
  39819. if (oldIOS) {
  39820. this.noSleepTimer = null;
  39821. } else {
  39822. this.noSleepVideo = document.createElement('video');
  39823. this.noSleepVideo.setAttribute('playsinline', '');
  39824. this.noSleepVideo.setAttribute('src', mediaFile);
  39825. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  39826. if (this.noSleepVideo.currentTime > 0.5) {
  39827. this.noSleepVideo.currentTime = Math.random();
  39828. }
  39829. }.bind(this));
  39830. }
  39831. }
  39832. _createClass(NoSleep, [{
  39833. key: 'enable',
  39834. value: function enable() {
  39835. if (oldIOS) {
  39836. this.disable();
  39837. this.noSleepTimer = window.setInterval(function () {
  39838. window.location.href = '/';
  39839. window.setTimeout(window.stop, 0);
  39840. }, 15000);
  39841. } else {
  39842. this.noSleepVideo.play();
  39843. }
  39844. }
  39845. }, {
  39846. key: 'disable',
  39847. value: function disable() {
  39848. if (oldIOS) {
  39849. if (this.noSleepTimer) {
  39850. window.clearInterval(this.noSleepTimer);
  39851. this.noSleepTimer = null;
  39852. }
  39853. } else {
  39854. this.noSleepVideo.pause();
  39855. }
  39856. }
  39857. }]);
  39858. return NoSleep;
  39859. }();
  39860. module.exports = NoSleep;
  39861. }),
  39862. (function(module, exports, __webpack_require__) {
  39863. 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=';
  39864. })
  39865. ]);
  39866. });
  39867. });
  39868. var NoSleep$1 = unwrapExports$$1(NoSleep);
  39869. var nextDisplayId = 1000;
  39870. var defaultLeftBounds = [0, 0, 0.5, 1];
  39871. var defaultRightBounds = [0.5, 0, 0.5, 1];
  39872. var raf = window.requestAnimationFrame;
  39873. var caf = window.cancelAnimationFrame;
  39874. function VRFrameData() {
  39875. this.leftProjectionMatrix = new Float32Array(16);
  39876. this.leftViewMatrix = new Float32Array(16);
  39877. this.rightProjectionMatrix = new Float32Array(16);
  39878. this.rightViewMatrix = new Float32Array(16);
  39879. this.pose = null;
  39880. }
  39881. function VRDisplayCapabilities(config) {
  39882. Object.defineProperties(this, {
  39883. hasPosition: {
  39884. writable: false, enumerable: true, value: config.hasPosition
  39885. },
  39886. hasExternalDisplay: {
  39887. writable: false, enumerable: true, value: config.hasExternalDisplay
  39888. },
  39889. canPresent: {
  39890. writable: false, enumerable: true, value: config.canPresent
  39891. },
  39892. maxLayers: {
  39893. writable: false, enumerable: true, value: config.maxLayers
  39894. },
  39895. hasOrientation: {
  39896. enumerable: true, get: function get() {
  39897. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  39898. return config.hasOrientation;
  39899. }
  39900. }
  39901. });
  39902. }
  39903. function VRDisplay(config) {
  39904. config = config || {};
  39905. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  39906. this.isPolyfilled = true;
  39907. this.displayId = nextDisplayId++;
  39908. this.displayName = '';
  39909. this.depthNear = 0.01;
  39910. this.depthFar = 10000.0;
  39911. this.isPresenting = false;
  39912. Object.defineProperty(this, 'isConnected', {
  39913. get: function get() {
  39914. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  39915. return false;
  39916. }
  39917. });
  39918. this.capabilities = new VRDisplayCapabilities({
  39919. hasPosition: false,
  39920. hasOrientation: false,
  39921. hasExternalDisplay: false,
  39922. canPresent: false,
  39923. maxLayers: 1
  39924. });
  39925. this.stageParameters = null;
  39926. this.waitingForPresent_ = false;
  39927. this.layer_ = null;
  39928. this.originalParent_ = null;
  39929. this.fullscreenElement_ = null;
  39930. this.fullscreenWrapper_ = null;
  39931. this.fullscreenElementCachedStyle_ = null;
  39932. this.fullscreenEventTarget_ = null;
  39933. this.fullscreenChangeHandler_ = null;
  39934. this.fullscreenErrorHandler_ = null;
  39935. if (USE_WAKELOCK && isMobile()) {
  39936. this.wakelock_ = new NoSleep$1();
  39937. }
  39938. }
  39939. VRDisplay.prototype.getFrameData = function (frameData) {
  39940. return frameDataFromPose(frameData, this._getPose(), this);
  39941. };
  39942. VRDisplay.prototype.getPose = function () {
  39943. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  39944. return this._getPose();
  39945. };
  39946. VRDisplay.prototype.resetPose = function () {
  39947. deprecateWarning('VRDisplay.prototype.resetPose');
  39948. return this._resetPose();
  39949. };
  39950. VRDisplay.prototype.getImmediatePose = function () {
  39951. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  39952. return this._getPose();
  39953. };
  39954. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  39955. return raf(callback);
  39956. };
  39957. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  39958. return caf(id);
  39959. };
  39960. VRDisplay.prototype.wrapForFullscreen = function (element) {
  39961. if (isIOS()) {
  39962. return element;
  39963. }
  39964. if (!this.fullscreenWrapper_) {
  39965. this.fullscreenWrapper_ = document.createElement('div');
  39966. 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'];
  39967. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  39968. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  39969. }
  39970. if (this.fullscreenElement_ == element) {
  39971. return this.fullscreenWrapper_;
  39972. }
  39973. if (this.fullscreenElement_) {
  39974. if (this.originalParent_) {
  39975. this.originalParent_.appendChild(this.fullscreenElement_);
  39976. } else {
  39977. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  39978. }
  39979. }
  39980. this.fullscreenElement_ = element;
  39981. this.originalParent_ = element.parentElement;
  39982. if (!this.originalParent_) {
  39983. document.body.appendChild(element);
  39984. }
  39985. if (!this.fullscreenWrapper_.parentElement) {
  39986. var parent = this.fullscreenElement_.parentElement;
  39987. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  39988. parent.removeChild(this.fullscreenElement_);
  39989. }
  39990. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  39991. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  39992. var self = this;
  39993. function applyFullscreenElementStyle() {
  39994. if (!self.fullscreenElement_) {
  39995. return;
  39996. }
  39997. 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'];
  39998. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  39999. }
  40000. applyFullscreenElementStyle();
  40001. return this.fullscreenWrapper_;
  40002. };
  40003. VRDisplay.prototype.removeFullscreenWrapper = function () {
  40004. if (!this.fullscreenElement_) {
  40005. return;
  40006. }
  40007. var element = this.fullscreenElement_;
  40008. if (this.fullscreenElementCachedStyle_) {
  40009. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  40010. } else {
  40011. element.removeAttribute('style');
  40012. }
  40013. this.fullscreenElement_ = null;
  40014. this.fullscreenElementCachedStyle_ = null;
  40015. var parent = this.fullscreenWrapper_.parentElement;
  40016. this.fullscreenWrapper_.removeChild(element);
  40017. if (this.originalParent_ === parent) {
  40018. parent.insertBefore(element, this.fullscreenWrapper_);
  40019. }
  40020. else if (this.originalParent_) {
  40021. this.originalParent_.appendChild(element);
  40022. }
  40023. parent.removeChild(this.fullscreenWrapper_);
  40024. return element;
  40025. };
  40026. VRDisplay.prototype.requestPresent = function (layers) {
  40027. var wasPresenting = this.isPresenting;
  40028. var self = this;
  40029. if (!(layers instanceof Array)) {
  40030. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  40031. layers = [layers];
  40032. }
  40033. return new Promise(function (resolve, reject) {
  40034. if (!self.capabilities.canPresent) {
  40035. reject(new Error('VRDisplay is not capable of presenting.'));
  40036. return;
  40037. }
  40038. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  40039. reject(new Error('Invalid number of layers.'));
  40040. return;
  40041. }
  40042. var incomingLayer = layers[0];
  40043. if (!incomingLayer.source) {
  40044. resolve();
  40045. return;
  40046. }
  40047. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  40048. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  40049. if (wasPresenting) {
  40050. var layer = self.layer_;
  40051. if (layer.source !== incomingLayer.source) {
  40052. layer.source = incomingLayer.source;
  40053. }
  40054. for (var i = 0; i < 4; i++) {
  40055. layer.leftBounds[i] = leftBounds[i];
  40056. layer.rightBounds[i] = rightBounds[i];
  40057. }
  40058. self.wrapForFullscreen(self.layer_.source);
  40059. self.updatePresent_();
  40060. resolve();
  40061. return;
  40062. }
  40063. self.layer_ = {
  40064. predistorted: incomingLayer.predistorted,
  40065. source: incomingLayer.source,
  40066. leftBounds: leftBounds.slice(0),
  40067. rightBounds: rightBounds.slice(0)
  40068. };
  40069. self.waitingForPresent_ = false;
  40070. if (self.layer_ && self.layer_.source) {
  40071. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  40072. var onFullscreenChange = function onFullscreenChange() {
  40073. var actualFullscreenElement = getFullscreenElement();
  40074. self.isPresenting = fullscreenElement === actualFullscreenElement;
  40075. if (self.isPresenting) {
  40076. if (screen.orientation && screen.orientation.lock) {
  40077. screen.orientation.lock('landscape-primary').catch(function (error) {
  40078. console.error('screen.orientation.lock() failed due to', error.message);
  40079. });
  40080. }
  40081. self.waitingForPresent_ = false;
  40082. self.beginPresent_();
  40083. resolve();
  40084. } else {
  40085. if (screen.orientation && screen.orientation.unlock) {
  40086. screen.orientation.unlock();
  40087. }
  40088. self.removeFullscreenWrapper();
  40089. self.disableWakeLock();
  40090. self.endPresent_();
  40091. self.removeFullscreenListeners_();
  40092. }
  40093. self.fireVRDisplayPresentChange_();
  40094. };
  40095. var onFullscreenError = function onFullscreenError() {
  40096. if (!self.waitingForPresent_) {
  40097. return;
  40098. }
  40099. self.removeFullscreenWrapper();
  40100. self.removeFullscreenListeners_();
  40101. self.disableWakeLock();
  40102. self.waitingForPresent_ = false;
  40103. self.isPresenting = false;
  40104. reject(new Error('Unable to present.'));
  40105. };
  40106. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  40107. if (requestFullscreen(fullscreenElement)) {
  40108. self.enableWakeLock();
  40109. self.waitingForPresent_ = true;
  40110. } else if (isIOS() || isWebViewAndroid()) {
  40111. self.enableWakeLock();
  40112. self.isPresenting = true;
  40113. self.beginPresent_();
  40114. self.fireVRDisplayPresentChange_();
  40115. resolve();
  40116. }
  40117. }
  40118. if (!self.waitingForPresent_ && !isIOS()) {
  40119. exitFullscreen();
  40120. reject(new Error('Unable to present.'));
  40121. }
  40122. });
  40123. };
  40124. VRDisplay.prototype.exitPresent = function () {
  40125. var wasPresenting = this.isPresenting;
  40126. var self = this;
  40127. this.isPresenting = false;
  40128. this.layer_ = null;
  40129. this.disableWakeLock();
  40130. return new Promise(function (resolve, reject) {
  40131. if (wasPresenting) {
  40132. if (!exitFullscreen() && isIOS()) {
  40133. self.endPresent_();
  40134. self.fireVRDisplayPresentChange_();
  40135. }
  40136. if (isWebViewAndroid()) {
  40137. self.removeFullscreenWrapper();
  40138. self.removeFullscreenListeners_();
  40139. self.endPresent_();
  40140. self.fireVRDisplayPresentChange_();
  40141. }
  40142. resolve();
  40143. } else {
  40144. reject(new Error('Was not presenting to VRDisplay.'));
  40145. }
  40146. });
  40147. };
  40148. VRDisplay.prototype.getLayers = function () {
  40149. if (this.layer_) {
  40150. return [this.layer_];
  40151. }
  40152. return [];
  40153. };
  40154. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  40155. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  40156. window.dispatchEvent(event);
  40157. };
  40158. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  40159. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  40160. window.dispatchEvent(event);
  40161. };
  40162. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  40163. this.removeFullscreenListeners_();
  40164. this.fullscreenEventTarget_ = element;
  40165. this.fullscreenChangeHandler_ = changeHandler;
  40166. this.fullscreenErrorHandler_ = errorHandler;
  40167. if (changeHandler) {
  40168. if (document.fullscreenEnabled) {
  40169. element.addEventListener('fullscreenchange', changeHandler, false);
  40170. } else if (document.webkitFullscreenEnabled) {
  40171. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  40172. } else if (document.mozFullScreenEnabled) {
  40173. document.addEventListener('mozfullscreenchange', changeHandler, false);
  40174. } else if (document.msFullscreenEnabled) {
  40175. element.addEventListener('msfullscreenchange', changeHandler, false);
  40176. }
  40177. }
  40178. if (errorHandler) {
  40179. if (document.fullscreenEnabled) {
  40180. element.addEventListener('fullscreenerror', errorHandler, false);
  40181. } else if (document.webkitFullscreenEnabled) {
  40182. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  40183. } else if (document.mozFullScreenEnabled) {
  40184. document.addEventListener('mozfullscreenerror', errorHandler, false);
  40185. } else if (document.msFullscreenEnabled) {
  40186. element.addEventListener('msfullscreenerror', errorHandler, false);
  40187. }
  40188. }
  40189. };
  40190. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  40191. if (!this.fullscreenEventTarget_) return;
  40192. var element = this.fullscreenEventTarget_;
  40193. if (this.fullscreenChangeHandler_) {
  40194. var changeHandler = this.fullscreenChangeHandler_;
  40195. element.removeEventListener('fullscreenchange', changeHandler, false);
  40196. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  40197. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  40198. element.removeEventListener('msfullscreenchange', changeHandler, false);
  40199. }
  40200. if (this.fullscreenErrorHandler_) {
  40201. var errorHandler = this.fullscreenErrorHandler_;
  40202. element.removeEventListener('fullscreenerror', errorHandler, false);
  40203. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  40204. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  40205. element.removeEventListener('msfullscreenerror', errorHandler, false);
  40206. }
  40207. this.fullscreenEventTarget_ = null;
  40208. this.fullscreenChangeHandler_ = null;
  40209. this.fullscreenErrorHandler_ = null;
  40210. };
  40211. VRDisplay.prototype.enableWakeLock = function () {
  40212. if (this.wakelock_) {
  40213. this.wakelock_.enable();
  40214. }
  40215. };
  40216. VRDisplay.prototype.disableWakeLock = function () {
  40217. if (this.wakelock_) {
  40218. this.wakelock_.disable();
  40219. }
  40220. };
  40221. VRDisplay.prototype.beginPresent_ = function () {
  40222. };
  40223. VRDisplay.prototype.endPresent_ = function () {
  40224. };
  40225. VRDisplay.prototype.submitFrame = function (pose) {
  40226. };
  40227. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  40228. return null;
  40229. };
  40230. var config = {
  40231. MOBILE_WAKE_LOCK: true,
  40232. DEBUG: false,
  40233. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  40234. K_FILTER: 0.98,
  40235. PREDICTION_TIME_S: 0.040,
  40236. CARDBOARD_UI_DISABLED: false,
  40237. ROTATE_INSTRUCTIONS_DISABLED: false,
  40238. YAW_ONLY: false,
  40239. BUFFER_SCALE: 0.5,
  40240. DIRTY_SUBMIT_FRAME_BINDINGS: false
  40241. };
  40242. var Eye = {
  40243. LEFT: 'left',
  40244. RIGHT: 'right'
  40245. };
  40246. function CardboardVRDisplay(config$$1) {
  40247. var defaults = extend({}, config);
  40248. config$$1 = extend(defaults, config$$1 || {});
  40249. VRDisplay.call(this, {
  40250. wakelock: config$$1.MOBILE_WAKE_LOCK
  40251. });
  40252. this.config = config$$1;
  40253. this.displayName = 'Cardboard VRDisplay';
  40254. this.capabilities = new VRDisplayCapabilities({
  40255. hasPosition: false,
  40256. hasOrientation: true,
  40257. hasExternalDisplay: false,
  40258. canPresent: true,
  40259. maxLayers: 1
  40260. });
  40261. this.stageParameters = null;
  40262. this.bufferScale_ = this.config.BUFFER_SCALE;
  40263. this.poseSensor_ = new PoseSensor(this.config);
  40264. this.distorter_ = null;
  40265. this.cardboardUI_ = null;
  40266. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  40267. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams());
  40268. this.viewerSelector_ = new ViewerSelector();
  40269. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  40270. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  40271. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  40272. this.rotateInstructions_ = new RotateInstructions();
  40273. }
  40274. if (isIOS()) {
  40275. window.addEventListener('resize', this.onResize_.bind(this));
  40276. }
  40277. }
  40278. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  40279. CardboardVRDisplay.prototype._getPose = function () {
  40280. return {
  40281. position: null,
  40282. orientation: this.poseSensor_.getOrientation(),
  40283. linearVelocity: null,
  40284. linearAcceleration: null,
  40285. angularVelocity: null,
  40286. angularAcceleration: null
  40287. };
  40288. };
  40289. CardboardVRDisplay.prototype._resetPose = function () {
  40290. if (this.poseSensor_.resetPose) {
  40291. this.poseSensor_.resetPose();
  40292. }
  40293. };
  40294. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  40295. var fieldOfView;
  40296. if (whichEye == Eye.LEFT) {
  40297. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  40298. } else if (whichEye == Eye.RIGHT) {
  40299. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  40300. } else {
  40301. console.error('Invalid eye provided: %s', whichEye);
  40302. return null;
  40303. }
  40304. return fieldOfView;
  40305. };
  40306. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  40307. var offset;
  40308. if (whichEye == Eye.LEFT) {
  40309. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  40310. } else if (whichEye == Eye.RIGHT) {
  40311. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  40312. } else {
  40313. console.error('Invalid eye provided: %s', whichEye);
  40314. return null;
  40315. }
  40316. return offset;
  40317. };
  40318. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  40319. var offset = this._getEyeOffset(whichEye);
  40320. var fieldOfView = this._getFieldOfView(whichEye);
  40321. var eyeParams = {
  40322. offset: offset,
  40323. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  40324. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  40325. };
  40326. Object.defineProperty(eyeParams, 'fieldOfView', {
  40327. enumerable: true,
  40328. get: function get() {
  40329. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  40330. return fieldOfView;
  40331. }
  40332. });
  40333. return eyeParams;
  40334. };
  40335. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  40336. if (this.config.DEBUG) {
  40337. console.log('DPDB reported that device params were updated.');
  40338. }
  40339. this.deviceInfo_.updateDeviceParams(newParams);
  40340. if (this.distorter_) {
  40341. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40342. }
  40343. };
  40344. CardboardVRDisplay.prototype.updateBounds_ = function () {
  40345. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  40346. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  40347. }
  40348. };
  40349. CardboardVRDisplay.prototype.beginPresent_ = function () {
  40350. var gl = this.layer_.source.getContext('webgl');
  40351. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  40352. if (!gl) gl = this.layer_.source.getContext('webgl2');
  40353. if (!gl) return;
  40354. if (this.layer_.predistorted) {
  40355. if (!this.config.CARDBOARD_UI_DISABLED) {
  40356. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  40357. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  40358. this.cardboardUI_ = new CardboardUI(gl);
  40359. }
  40360. } else {
  40361. if (!this.config.CARDBOARD_UI_DISABLED) {
  40362. this.cardboardUI_ = new CardboardUI(gl);
  40363. }
  40364. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  40365. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40366. }
  40367. if (this.cardboardUI_) {
  40368. this.cardboardUI_.listen(function (e) {
  40369. this.viewerSelector_.show(this.layer_.source.parentElement);
  40370. e.stopPropagation();
  40371. e.preventDefault();
  40372. }.bind(this), function (e) {
  40373. this.exitPresent();
  40374. e.stopPropagation();
  40375. e.preventDefault();
  40376. }.bind(this));
  40377. }
  40378. if (this.rotateInstructions_) {
  40379. if (isLandscapeMode() && isMobile()) {
  40380. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  40381. } else {
  40382. this.rotateInstructions_.update();
  40383. }
  40384. }
  40385. this.orientationHandler = this.onOrientationChange_.bind(this);
  40386. window.addEventListener('orientationchange', this.orientationHandler);
  40387. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  40388. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  40389. this.fireVRDisplayDeviceParamsChange_();
  40390. };
  40391. CardboardVRDisplay.prototype.endPresent_ = function () {
  40392. if (this.distorter_) {
  40393. this.distorter_.destroy();
  40394. this.distorter_ = null;
  40395. }
  40396. if (this.cardboardUI_) {
  40397. this.cardboardUI_.destroy();
  40398. this.cardboardUI_ = null;
  40399. }
  40400. if (this.rotateInstructions_) {
  40401. this.rotateInstructions_.hide();
  40402. }
  40403. this.viewerSelector_.hide();
  40404. window.removeEventListener('orientationchange', this.orientationHandler);
  40405. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  40406. };
  40407. CardboardVRDisplay.prototype.updatePresent_ = function () {
  40408. this.endPresent_();
  40409. this.beginPresent_();
  40410. };
  40411. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  40412. if (this.distorter_) {
  40413. this.updateBounds_();
  40414. this.distorter_.submitFrame();
  40415. } else if (this.cardboardUI_ && this.layer_) {
  40416. var canvas = this.layer_.source.getContext('webgl').canvas;
  40417. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  40418. this.cardboardUI_.onResize();
  40419. }
  40420. this.lastWidth = canvas.width;
  40421. this.lastHeight = canvas.height;
  40422. this.cardboardUI_.render();
  40423. }
  40424. };
  40425. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  40426. this.viewerSelector_.hide();
  40427. if (this.rotateInstructions_) {
  40428. this.rotateInstructions_.update();
  40429. }
  40430. this.onResize_();
  40431. };
  40432. CardboardVRDisplay.prototype.onResize_ = function (e) {
  40433. if (this.layer_) {
  40434. var gl = this.layer_.source.getContext('webgl');
  40435. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  40436. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  40437. 'padding: 0px', 'box-sizing: content-box'];
  40438. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  40439. safariCssSizeWorkaround(gl.canvas);
  40440. }
  40441. };
  40442. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  40443. this.deviceInfo_.setViewer(viewer);
  40444. if (this.distorter_) {
  40445. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40446. }
  40447. this.fireVRDisplayDeviceParamsChange_();
  40448. };
  40449. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  40450. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  40451. detail: {
  40452. vrdisplay: this,
  40453. deviceInfo: this.deviceInfo_
  40454. }
  40455. });
  40456. window.dispatchEvent(event);
  40457. };
  40458. CardboardVRDisplay.VRFrameData = VRFrameData;
  40459. CardboardVRDisplay.VRDisplay = VRDisplay;
  40460. return CardboardVRDisplay;
  40461. })));
  40462. });
  40463. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  40464. var version = "0.10.5";
  40465. var DefaultConfig = {
  40466. PROVIDE_MOBILE_VRDISPLAY: true,
  40467. GET_VR_DISPLAYS_TIMEOUT: 1000,
  40468. MOBILE_WAKE_LOCK: true,
  40469. DEBUG: false,
  40470. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  40471. K_FILTER: 0.98,
  40472. PREDICTION_TIME_S: 0.040,
  40473. TOUCH_PANNER_DISABLED: true,
  40474. CARDBOARD_UI_DISABLED: false,
  40475. ROTATE_INSTRUCTIONS_DISABLED: false,
  40476. YAW_ONLY: false,
  40477. BUFFER_SCALE: 0.5,
  40478. DIRTY_SUBMIT_FRAME_BINDINGS: false
  40479. };
  40480. function WebVRPolyfill(config) {
  40481. this.config = extend(extend({}, DefaultConfig), config);
  40482. this.polyfillDisplays = [];
  40483. this.enabled = false;
  40484. this.hasNative = 'getVRDisplays' in navigator;
  40485. this.native = {};
  40486. this.native.getVRDisplays = navigator.getVRDisplays;
  40487. this.native.VRFrameData = window.VRFrameData;
  40488. this.native.VRDisplay = window.VRDisplay;
  40489. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  40490. this.enable();
  40491. this.getVRDisplays().then(function (displays) {
  40492. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  40493. displays[0].fireVRDisplayConnect_();
  40494. }
  40495. });
  40496. }
  40497. }
  40498. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  40499. if (this._polyfillDisplaysPopulated) {
  40500. return this.polyfillDisplays;
  40501. }
  40502. if (isMobile()) {
  40503. var vrDisplay = new CardboardVRDisplay({
  40504. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  40505. DEBUG: this.config.DEBUG,
  40506. DPDB_URL: this.config.DPDB_URL,
  40507. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  40508. K_FILTER: this.config.K_FILTER,
  40509. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  40510. TOUCH_PANNER_DISABLED: this.config.TOUCH_PANNER_DISABLED,
  40511. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  40512. YAW_ONLY: this.config.YAW_ONLY,
  40513. BUFFER_SCALE: this.config.BUFFER_SCALE,
  40514. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  40515. });
  40516. this.polyfillDisplays.push(vrDisplay);
  40517. }
  40518. this._polyfillDisplaysPopulated = true;
  40519. return this.polyfillDisplays;
  40520. };
  40521. WebVRPolyfill.prototype.enable = function () {
  40522. this.enabled = true;
  40523. if (this.hasNative && this.native.VRFrameData) {
  40524. var NativeVRFrameData = this.native.VRFrameData;
  40525. var nativeFrameData = new this.native.VRFrameData();
  40526. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  40527. window.VRDisplay.prototype.getFrameData = function (frameData) {
  40528. if (frameData instanceof NativeVRFrameData) {
  40529. nativeGetFrameData.call(this, frameData);
  40530. return;
  40531. }
  40532. nativeGetFrameData.call(this, nativeFrameData);
  40533. frameData.pose = nativeFrameData.pose;
  40534. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  40535. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  40536. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  40537. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  40538. };
  40539. }
  40540. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  40541. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  40542. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  40543. };
  40544. WebVRPolyfill.prototype.getVRDisplays = function () {
  40545. var _this = this;
  40546. var config = this.config;
  40547. if (!this.hasNative) {
  40548. return Promise.resolve(this.getPolyfillDisplays());
  40549. }
  40550. var timeoutId;
  40551. var vrDisplaysNative = this.native.getVRDisplays.call(navigator);
  40552. var timeoutPromise = new Promise(function (resolve) {
  40553. timeoutId = setTimeout(function () {
  40554. console.warn('Native WebVR implementation detected, but `getVRDisplays()` failed to resolve. Falling back to polyfill.');
  40555. resolve([]);
  40556. }, config.GET_VR_DISPLAYS_TIMEOUT);
  40557. });
  40558. return race([vrDisplaysNative, timeoutPromise]).then(function (nativeDisplays) {
  40559. clearTimeout(timeoutId);
  40560. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  40561. });
  40562. };
  40563. WebVRPolyfill.version = version;
  40564. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  40565. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  40566. var webvrPolyfill = Object.freeze({
  40567. default: WebVRPolyfill
  40568. });
  40569. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  40570. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  40571. if (!commonjsGlobal.document) {
  40572. commonjsGlobal.document = commonjsGlobal.window.document;
  40573. }
  40574. if (!commonjsGlobal.navigator) {
  40575. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  40576. }
  40577. }
  40578. var src = require$$0;
  40579. return src;
  40580. })));
  40581. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  40582. },{}],47:[function(_dereq_,module,exports){
  40583. var newline = /\n/
  40584. var newlineChar = '\n'
  40585. var whitespace = /\s/
  40586. module.exports = function(text, opt) {
  40587. var lines = module.exports.lines(text, opt)
  40588. return lines.map(function(line) {
  40589. return text.substring(line.start, line.end)
  40590. }).join('\n')
  40591. }
  40592. module.exports.lines = function wordwrap(text, opt) {
  40593. opt = opt||{}
  40594. //zero width results in nothing visible
  40595. if (opt.width === 0 && opt.mode !== 'nowrap')
  40596. return []
  40597. text = text||''
  40598. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  40599. var start = Math.max(0, opt.start||0)
  40600. var end = typeof opt.end === 'number' ? opt.end : text.length
  40601. var mode = opt.mode
  40602. var measure = opt.measure || monospace
  40603. if (mode === 'pre')
  40604. return pre(measure, text, start, end, width)
  40605. else
  40606. return greedy(measure, text, start, end, width, mode)
  40607. }
  40608. function idxOf(text, chr, start, end) {
  40609. var idx = text.indexOf(chr, start)
  40610. if (idx === -1 || idx > end)
  40611. return end
  40612. return idx
  40613. }
  40614. function isWhitespace(chr) {
  40615. return whitespace.test(chr)
  40616. }
  40617. function pre(measure, text, start, end, width) {
  40618. var lines = []
  40619. var lineStart = start
  40620. for (var i=start; i<end && i<text.length; i++) {
  40621. var chr = text.charAt(i)
  40622. var isNewline = newline.test(chr)
  40623. //If we've reached a newline, then step down a line
  40624. //Or if we've reached the EOF
  40625. if (isNewline || i===end-1) {
  40626. var lineEnd = isNewline ? i : i+1
  40627. var measured = measure(text, lineStart, lineEnd, width)
  40628. lines.push(measured)
  40629. lineStart = i+1
  40630. }
  40631. }
  40632. return lines
  40633. }
  40634. function greedy(measure, text, start, end, width, mode) {
  40635. //A greedy word wrapper based on LibGDX algorithm
  40636. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  40637. var lines = []
  40638. var testWidth = width
  40639. //if 'nowrap' is specified, we only wrap on newline chars
  40640. if (mode === 'nowrap')
  40641. testWidth = Number.MAX_VALUE
  40642. while (start < end && start < text.length) {
  40643. //get next newline position
  40644. var newLine = idxOf(text, newlineChar, start, end)
  40645. //eat whitespace at start of line
  40646. while (start < newLine) {
  40647. if (!isWhitespace( text.charAt(start) ))
  40648. break
  40649. start++
  40650. }
  40651. //determine visible # of glyphs for the available width
  40652. var measured = measure(text, start, newLine, testWidth)
  40653. var lineEnd = start + (measured.end-measured.start)
  40654. var nextStart = lineEnd + newlineChar.length
  40655. //if we had to cut the line before the next newline...
  40656. if (lineEnd < newLine) {
  40657. //find char to break on
  40658. while (lineEnd > start) {
  40659. if (isWhitespace(text.charAt(lineEnd)))
  40660. break
  40661. lineEnd--
  40662. }
  40663. if (lineEnd === start) {
  40664. if (nextStart > start + newlineChar.length) nextStart--
  40665. lineEnd = nextStart // If no characters to break, show all.
  40666. } else {
  40667. nextStart = lineEnd
  40668. //eat whitespace at end of line
  40669. while (lineEnd > start) {
  40670. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  40671. break
  40672. lineEnd--
  40673. }
  40674. }
  40675. }
  40676. if (lineEnd >= start) {
  40677. var result = measure(text, start, lineEnd, testWidth)
  40678. lines.push(result)
  40679. }
  40680. start = nextStart
  40681. }
  40682. return lines
  40683. }
  40684. //determines the visible number of glyphs within a given width
  40685. function monospace(text, start, end, width) {
  40686. var glyphs = Math.min(width, end-start)
  40687. return {
  40688. start: start,
  40689. end: start+glyphs
  40690. }
  40691. }
  40692. },{}],48:[function(_dereq_,module,exports){
  40693. "use strict";
  40694. var window = _dereq_("global/window")
  40695. var isFunction = _dereq_("is-function")
  40696. var parseHeaders = _dereq_("parse-headers")
  40697. var xtend = _dereq_("xtend")
  40698. module.exports = createXHR
  40699. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  40700. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  40701. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  40702. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  40703. options = initParams(uri, options, callback)
  40704. options.method = method.toUpperCase()
  40705. return _createXHR(options)
  40706. }
  40707. })
  40708. function forEachArray(array, iterator) {
  40709. for (var i = 0; i < array.length; i++) {
  40710. iterator(array[i])
  40711. }
  40712. }
  40713. function isEmpty(obj){
  40714. for(var i in obj){
  40715. if(obj.hasOwnProperty(i)) return false
  40716. }
  40717. return true
  40718. }
  40719. function initParams(uri, options, callback) {
  40720. var params = uri
  40721. if (isFunction(options)) {
  40722. callback = options
  40723. if (typeof uri === "string") {
  40724. params = {uri:uri}
  40725. }
  40726. } else {
  40727. params = xtend(options, {uri: uri})
  40728. }
  40729. params.callback = callback
  40730. return params
  40731. }
  40732. function createXHR(uri, options, callback) {
  40733. options = initParams(uri, options, callback)
  40734. return _createXHR(options)
  40735. }
  40736. function _createXHR(options) {
  40737. if(typeof options.callback === "undefined"){
  40738. throw new Error("callback argument missing")
  40739. }
  40740. var called = false
  40741. var callback = function cbOnce(err, response, body){
  40742. if(!called){
  40743. called = true
  40744. options.callback(err, response, body)
  40745. }
  40746. }
  40747. function readystatechange() {
  40748. if (xhr.readyState === 4) {
  40749. setTimeout(loadFunc, 0)
  40750. }
  40751. }
  40752. function getBody() {
  40753. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  40754. var body = undefined
  40755. if (xhr.response) {
  40756. body = xhr.response
  40757. } else {
  40758. body = xhr.responseText || getXml(xhr)
  40759. }
  40760. if (isJson) {
  40761. try {
  40762. body = JSON.parse(body)
  40763. } catch (e) {}
  40764. }
  40765. return body
  40766. }
  40767. function errorFunc(evt) {
  40768. clearTimeout(timeoutTimer)
  40769. if(!(evt instanceof Error)){
  40770. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  40771. }
  40772. evt.statusCode = 0
  40773. return callback(evt, failureResponse)
  40774. }
  40775. // will load the data & process the response in a special response object
  40776. function loadFunc() {
  40777. if (aborted) return
  40778. var status
  40779. clearTimeout(timeoutTimer)
  40780. if(options.useXDR && xhr.status===undefined) {
  40781. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  40782. status = 200
  40783. } else {
  40784. status = (xhr.status === 1223 ? 204 : xhr.status)
  40785. }
  40786. var response = failureResponse
  40787. var err = null
  40788. if (status !== 0){
  40789. response = {
  40790. body: getBody(),
  40791. statusCode: status,
  40792. method: method,
  40793. headers: {},
  40794. url: uri,
  40795. rawRequest: xhr
  40796. }
  40797. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  40798. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  40799. }
  40800. } else {
  40801. err = new Error("Internal XMLHttpRequest Error")
  40802. }
  40803. return callback(err, response, response.body)
  40804. }
  40805. var xhr = options.xhr || null
  40806. if (!xhr) {
  40807. if (options.cors || options.useXDR) {
  40808. xhr = new createXHR.XDomainRequest()
  40809. }else{
  40810. xhr = new createXHR.XMLHttpRequest()
  40811. }
  40812. }
  40813. var key
  40814. var aborted
  40815. var uri = xhr.url = options.uri || options.url
  40816. var method = xhr.method = options.method || "GET"
  40817. var body = options.body || options.data
  40818. var headers = xhr.headers = options.headers || {}
  40819. var sync = !!options.sync
  40820. var isJson = false
  40821. var timeoutTimer
  40822. var failureResponse = {
  40823. body: undefined,
  40824. headers: {},
  40825. statusCode: 0,
  40826. method: method,
  40827. url: uri,
  40828. rawRequest: xhr
  40829. }
  40830. if ("json" in options && options.json !== false) {
  40831. isJson = true
  40832. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  40833. if (method !== "GET" && method !== "HEAD") {
  40834. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  40835. body = JSON.stringify(options.json === true ? body : options.json)
  40836. }
  40837. }
  40838. xhr.onreadystatechange = readystatechange
  40839. xhr.onload = loadFunc
  40840. xhr.onerror = errorFunc
  40841. // IE9 must have onprogress be set to a unique function.
  40842. xhr.onprogress = function () {
  40843. // IE must die
  40844. }
  40845. xhr.onabort = function(){
  40846. aborted = true;
  40847. }
  40848. xhr.ontimeout = errorFunc
  40849. xhr.open(method, uri, !sync, options.username, options.password)
  40850. //has to be after open
  40851. if(!sync) {
  40852. xhr.withCredentials = !!options.withCredentials
  40853. }
  40854. // Cannot set timeout with sync request
  40855. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  40856. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  40857. if (!sync && options.timeout > 0 ) {
  40858. timeoutTimer = setTimeout(function(){
  40859. if (aborted) return
  40860. aborted = true//IE9 may still call readystatechange
  40861. xhr.abort("timeout")
  40862. var e = new Error("XMLHttpRequest timeout")
  40863. e.code = "ETIMEDOUT"
  40864. errorFunc(e)
  40865. }, options.timeout )
  40866. }
  40867. if (xhr.setRequestHeader) {
  40868. for(key in headers){
  40869. if(headers.hasOwnProperty(key)){
  40870. xhr.setRequestHeader(key, headers[key])
  40871. }
  40872. }
  40873. } else if (options.headers && !isEmpty(options.headers)) {
  40874. throw new Error("Headers cannot be set on an XDomainRequest object")
  40875. }
  40876. if ("responseType" in options) {
  40877. xhr.responseType = options.responseType
  40878. }
  40879. if ("beforeSend" in options &&
  40880. typeof options.beforeSend === "function"
  40881. ) {
  40882. options.beforeSend(xhr)
  40883. }
  40884. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  40885. // XMLHttpRequest spec says to pass null as body to indicate no body
  40886. // See https://github.com/naugtur/xhr/issues/100.
  40887. xhr.send(body || null)
  40888. return xhr
  40889. }
  40890. function getXml(xhr) {
  40891. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  40892. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  40893. try {
  40894. if (xhr.responseType === "document") {
  40895. return xhr.responseXML
  40896. }
  40897. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  40898. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  40899. return xhr.responseXML
  40900. }
  40901. } catch (e) {}
  40902. return null
  40903. }
  40904. function noop() {}
  40905. },{"global/window":15,"is-function":19,"parse-headers":30,"xtend":50}],49:[function(_dereq_,module,exports){
  40906. module.exports = (function xmlparser() {
  40907. //common browsers
  40908. if (typeof self.DOMParser !== 'undefined') {
  40909. return function(str) {
  40910. var parser = new self.DOMParser()
  40911. return parser.parseFromString(str, 'application/xml')
  40912. }
  40913. }
  40914. //IE8 fallback
  40915. if (typeof self.ActiveXObject !== 'undefined'
  40916. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  40917. return function(str) {
  40918. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  40919. xmlDoc.async = "false"
  40920. xmlDoc.loadXML(str)
  40921. return xmlDoc
  40922. }
  40923. }
  40924. //last resort fallback
  40925. return function(str) {
  40926. var div = document.createElement('div')
  40927. div.innerHTML = str
  40928. return div
  40929. }
  40930. })()
  40931. },{}],50:[function(_dereq_,module,exports){
  40932. module.exports = extend
  40933. var hasOwnProperty = Object.prototype.hasOwnProperty;
  40934. function extend() {
  40935. var target = {}
  40936. for (var i = 0; i < arguments.length; i++) {
  40937. var source = arguments[i]
  40938. for (var key in source) {
  40939. if (hasOwnProperty.call(source, key)) {
  40940. target[key] = source[key]
  40941. }
  40942. }
  40943. }
  40944. return target
  40945. }
  40946. },{}],51:[function(_dereq_,module,exports){
  40947. module.exports={
  40948. "name": "aframe",
  40949. "version": "0.8.2",
  40950. "description": "A web framework for building virtual reality experiences.",
  40951. "homepage": "https://aframe.io/",
  40952. "main": "dist/aframe-master.js",
  40953. "scripts": {
  40954. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  40955. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [envify --INSPECTOR_VERSION dev] -o build/aframe.js",
  40956. "codecov": "codecov",
  40957. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  40958. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  40959. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  40960. "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",
  40961. "docs": "markserv --dir docs --port 9001",
  40962. "preghpages": "node ./scripts/preghpages.js",
  40963. "ghpages": "ghpages -p gh-pages/",
  40964. "lint": "semistandard -v | snazzy",
  40965. "lint:fix": "semistandard --fix",
  40966. "precommit": "npm run lint",
  40967. "prepush": "node scripts/testOnlyCheck.js",
  40968. "prerelease": "node scripts/release.js 0.7.1 0.8.0",
  40969. "start": "npm run dev",
  40970. "test": "karma start ./tests/karma.conf.js",
  40971. "test:docs": "node scripts/docsLint.js",
  40972. "test:firefox": "npm test -- --browsers Firefox",
  40973. "test:chrome": "npm test -- --browsers Chrome",
  40974. "test:node": "mocha --ui tdd tests/node"
  40975. },
  40976. "repository": "aframevr/aframe",
  40977. "license": "MIT",
  40978. "dependencies": {
  40979. "@tweenjs/tween.js": "^16.8.0",
  40980. "browserify-css": "^0.8.2",
  40981. "debug": "ngokevin/debug#noTimestamp",
  40982. "deep-assign": "^2.0.0",
  40983. "document-register-element": "dmarcos/document-register-element#8ccc532b7",
  40984. "envify": "^3.4.1",
  40985. "load-bmfont": "^1.2.3",
  40986. "object-assign": "^4.0.1",
  40987. "present": "0.0.6",
  40988. "promise-polyfill": "^3.1.0",
  40989. "style-attr": "^1.0.2",
  40990. "three": "0.92.0",
  40991. "three-bmfont-text": "^2.1.0",
  40992. "webvr-polyfill": "^0.10.5"
  40993. },
  40994. "devDependencies": {
  40995. "browserify": "^13.1.0",
  40996. "browserify-derequire": "^0.9.4",
  40997. "browserify-istanbul": "^2.0.0",
  40998. "budo": "^9.2.0",
  40999. "chai": "^3.5.0",
  41000. "chai-shallow-deep-equal": "^1.4.0",
  41001. "chalk": "^1.1.3",
  41002. "codecov": "^1.0.1",
  41003. "cross-env": "^5.0.1",
  41004. "exorcist": "^0.4.0",
  41005. "ghpages": "0.0.8",
  41006. "git-rev": "^0.2.1",
  41007. "glob": "^7.1.1",
  41008. "husky": "^0.11.7",
  41009. "istanbul": "^0.4.5",
  41010. "jsdom": "^9.11.0",
  41011. "karma": "1.4.1",
  41012. "karma-browserify": "^5.1.0",
  41013. "karma-chai-shallow-deep-equal": "0.0.4",
  41014. "karma-chrome-launcher": "^2.0.0",
  41015. "karma-coverage": "^1.1.1",
  41016. "karma-env-preprocessor": "^0.1.1",
  41017. "karma-firefox-launcher": "^1.0.0",
  41018. "karma-mocha": "^1.1.1",
  41019. "karma-mocha-reporter": "^2.1.0",
  41020. "karma-sinon-chai": "1.2.4",
  41021. "lolex": "^1.5.1",
  41022. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  41023. "minifyify": "^7.3.3",
  41024. "mocha": "^3.0.2",
  41025. "mozilla-download": "^1.1.1",
  41026. "replace-in-file": "^2.5.3",
  41027. "semistandard": "^9.0.0",
  41028. "shelljs": "^0.7.7",
  41029. "shx": "^0.2.2",
  41030. "sinon": "^1.17.5",
  41031. "sinon-chai": "2.8.0",
  41032. "snazzy": "^5.0.0",
  41033. "too-wordy": "ngokevin/too-wordy",
  41034. "uglifyjs": "^2.4.10",
  41035. "write-good": "^0.9.1"
  41036. },
  41037. "link": true,
  41038. "browserify": {
  41039. "transform": [
  41040. "browserify-css",
  41041. "envify"
  41042. ]
  41043. },
  41044. "semistandard": {
  41045. "ignore": [
  41046. "build/**",
  41047. "dist/**",
  41048. "examples/**/shaders/*.js",
  41049. "**/vendor/**"
  41050. ]
  41051. },
  41052. "keywords": [
  41053. "3d",
  41054. "aframe",
  41055. "cardboard",
  41056. "components",
  41057. "oculus",
  41058. "three",
  41059. "three.js",
  41060. "rift",
  41061. "vive",
  41062. "vr",
  41063. "web-components",
  41064. "webvr"
  41065. ],
  41066. "browserify-css": {
  41067. "minify": true
  41068. },
  41069. "engines": {
  41070. "node": ">= 4.6.0",
  41071. "npm": "^2.15.9"
  41072. }
  41073. }
  41074. },{}],52:[function(_dereq_,module,exports){
  41075. var registerComponent = _dereq_('../core/component').registerComponent;
  41076. var THREE = _dereq_('../lib/three');
  41077. /**
  41078. * Camera component.
  41079. * Pairs along with camera system to handle tracking the active camera.
  41080. */
  41081. module.exports.Component = registerComponent('camera', {
  41082. schema: {
  41083. active: {default: true},
  41084. far: {default: 10000},
  41085. fov: {default: 80, min: 0},
  41086. near: {default: 0.005, min: 0},
  41087. spectator: {default: false},
  41088. zoom: {default: 1, min: 0}
  41089. },
  41090. /**
  41091. * Initialize three.js camera and add it to the entity.
  41092. * Add reference from scene to this entity as the camera.
  41093. */
  41094. init: function () {
  41095. var camera;
  41096. var el = this.el;
  41097. // Create camera.
  41098. camera = this.camera = new THREE.PerspectiveCamera();
  41099. el.setObject3D('camera', camera);
  41100. },
  41101. /**
  41102. * Update three.js camera.
  41103. */
  41104. update: function (oldData) {
  41105. var data = this.data;
  41106. var camera = this.camera;
  41107. // Update properties.
  41108. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  41109. camera.far = data.far;
  41110. camera.fov = data.fov;
  41111. camera.near = data.near;
  41112. camera.zoom = data.zoom;
  41113. camera.updateProjectionMatrix();
  41114. this.updateActiveCamera(oldData);
  41115. this.updateSpectatorCamera(oldData);
  41116. },
  41117. updateActiveCamera: function (oldData) {
  41118. var data = this.data;
  41119. var el = this.el;
  41120. var system = this.system;
  41121. // Active property did not change.
  41122. if (oldData && oldData.active === data.active || data.spectator) { return; }
  41123. // If `active` property changes, or first update, handle active camera with system.
  41124. if (data.active && system.activeCameraEl !== el) {
  41125. // Camera enabled. Set camera to this camera.
  41126. system.setActiveCamera(el);
  41127. } else if (!data.active && system.activeCameraEl === el) {
  41128. // Camera disabled. Set camera to another camera.
  41129. system.disableActiveCamera();
  41130. }
  41131. },
  41132. updateSpectatorCamera: function (oldData) {
  41133. var data = this.data;
  41134. var el = this.el;
  41135. var system = this.system;
  41136. // spectator property did not change.
  41137. if (oldData && oldData.spectator === data.spectator) { return; }
  41138. // If `spectator` property changes, or first update, handle spectator camera with system.
  41139. if (data.spectator && system.spectatorCameraEl !== el) {
  41140. // Camera enabled. Set camera to this camera.
  41141. system.setSpectatorCamera(el);
  41142. } else if (!data.spectator && system.spectatorCameraEl === el) {
  41143. // Camera disabled. Set camera to another camera.
  41144. system.disableSpectatorCamera();
  41145. }
  41146. },
  41147. /**
  41148. * Remove camera on remove (callback).
  41149. */
  41150. remove: function () {
  41151. this.el.removeObject3D('camera');
  41152. }
  41153. });
  41154. },{"../core/component":103,"../lib/three":151}],53:[function(_dereq_,module,exports){
  41155. var registerComponent = _dereq_('../core/component').registerComponent;
  41156. var THREE = _dereq_('../lib/three');
  41157. module.exports.Component = registerComponent('collada-model', {
  41158. schema: {type: 'asset'},
  41159. init: function () {
  41160. this.model = null;
  41161. this.loader = new THREE.ColladaLoader();
  41162. this.loader.options.convertUpAxis = true;
  41163. },
  41164. update: function () {
  41165. var self = this;
  41166. var el = this.el;
  41167. var src = this.data;
  41168. if (!src) { return; }
  41169. this.remove();
  41170. this.loader.load(src, function (colladaModel) {
  41171. self.model = colladaModel.scene;
  41172. el.setObject3D('mesh', self.model);
  41173. el.emit('model-loaded', {format: 'collada', model: self.model});
  41174. });
  41175. },
  41176. remove: function () {
  41177. if (!this.model) { return; }
  41178. this.el.removeObject3D('mesh');
  41179. }
  41180. });
  41181. },{"../core/component":103,"../lib/three":151}],54:[function(_dereq_,module,exports){
  41182. /* global THREE */
  41183. var registerComponent = _dereq_('../core/component').registerComponent;
  41184. var utils = _dereq_('../utils/');
  41185. var bind = utils.bind;
  41186. var EVENTS = {
  41187. CLICK: 'click',
  41188. FUSING: 'fusing',
  41189. MOUSEENTER: 'mouseenter',
  41190. MOUSEDOWN: 'mousedown',
  41191. MOUSELEAVE: 'mouseleave',
  41192. MOUSEUP: 'mouseup'
  41193. };
  41194. var STATES = {
  41195. FUSING: 'cursor-fusing',
  41196. HOVERING: 'cursor-hovering',
  41197. HOVERED: 'cursor-hovered'
  41198. };
  41199. var CANVAS_EVENTS = {
  41200. DOWN: ['mousedown', 'touchstart'],
  41201. UP: ['mouseup', 'touchend']
  41202. };
  41203. /**
  41204. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  41205. * from the camera and pointing from camera's facing direction, and then only returning the
  41206. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  41207. *
  41208. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  41209. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  41210. * @member {object} intersection - Attributes of the current intersection event, including
  41211. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  41212. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  41213. * emit events when unintersecting.
  41214. */
  41215. module.exports.Component = registerComponent('cursor', {
  41216. dependencies: ['raycaster'],
  41217. schema: {
  41218. downEvents: {default: []},
  41219. fuse: {default: utils.device.isMobile()},
  41220. fuseTimeout: {default: 1500, min: 0},
  41221. upEvents: {default: []},
  41222. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  41223. },
  41224. init: function () {
  41225. var self = this;
  41226. this.fuseTimeout = undefined;
  41227. this.cursorDownEl = null;
  41228. this.intersectedEl = null;
  41229. this.canvasBounds = document.body.getBoundingClientRect();
  41230. // Debounce.
  41231. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  41232. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  41233. }, 1000);
  41234. this.eventDetail = {};
  41235. this.intersectedEventDetail = {cursorEl: this.el};
  41236. // Bind methods.
  41237. this.onCursorDown = bind(this.onCursorDown, this);
  41238. this.onCursorUp = bind(this.onCursorUp, this);
  41239. this.onIntersection = bind(this.onIntersection, this);
  41240. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  41241. this.onMouseMove = bind(this.onMouseMove, this);
  41242. },
  41243. update: function (oldData) {
  41244. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  41245. this.updateMouseEventListeners();
  41246. },
  41247. play: function () {
  41248. this.addEventListeners();
  41249. },
  41250. pause: function () {
  41251. this.removeEventListeners();
  41252. },
  41253. remove: function () {
  41254. var el = this.el;
  41255. el.removeState(STATES.HOVERING);
  41256. el.removeState(STATES.FUSING);
  41257. clearTimeout(this.fuseTimeout);
  41258. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  41259. this.removeEventListeners();
  41260. },
  41261. addEventListeners: function () {
  41262. var canvas;
  41263. var data = this.data;
  41264. var el = this.el;
  41265. var self = this;
  41266. function addCanvasListeners () {
  41267. canvas = el.sceneEl.canvas;
  41268. if (data.downEvents.length || data.upEvents.length) { return; }
  41269. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  41270. canvas.addEventListener(downEvent, self.onCursorDown);
  41271. });
  41272. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  41273. canvas.addEventListener(upEvent, self.onCursorUp);
  41274. });
  41275. }
  41276. canvas = el.sceneEl.canvas;
  41277. if (canvas) {
  41278. addCanvasListeners();
  41279. } else {
  41280. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  41281. }
  41282. data.downEvents.forEach(function (downEvent) {
  41283. el.addEventListener(downEvent, self.onCursorDown);
  41284. });
  41285. data.upEvents.forEach(function (upEvent) {
  41286. el.addEventListener(upEvent, self.onCursorUp);
  41287. });
  41288. el.addEventListener('raycaster-intersection', this.onIntersection);
  41289. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  41290. window.addEventListener('resize', this.updateCanvasBounds);
  41291. },
  41292. removeEventListeners: function () {
  41293. var canvas;
  41294. var data = this.data;
  41295. var el = this.el;
  41296. var self = this;
  41297. canvas = el.sceneEl.canvas;
  41298. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  41299. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  41300. canvas.removeEventListener(downEvent, self.onCursorDown);
  41301. });
  41302. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  41303. canvas.removeEventListener(upEvent, self.onCursorUp);
  41304. });
  41305. }
  41306. data.downEvents.forEach(function (downEvent) {
  41307. el.removeEventListener(downEvent, self.onCursorDown);
  41308. });
  41309. data.upEvents.forEach(function (upEvent) {
  41310. el.removeEventListener(upEvent, self.onCursorUp);
  41311. });
  41312. el.removeEventListener('raycaster-intersection', this.onIntersection);
  41313. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  41314. canvas.removeEventListener('mousemove', this.onMouseMove);
  41315. canvas.removeEventListener('touchstart', this.onMouseMove);
  41316. canvas.removeEventListener('touchmove', this.onMouseMove);
  41317. canvas.removeEventListener('resize', this.updateCanvasBounds);
  41318. },
  41319. updateMouseEventListeners: function () {
  41320. var canvas;
  41321. var el = this.el;
  41322. canvas = el.sceneEl.canvas;
  41323. canvas.removeEventListener('mousemove', this.onMouseMove);
  41324. canvas.removeEventListener('touchmove', this.onMouseMove);
  41325. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  41326. if (this.data.rayOrigin !== 'mouse') { return; }
  41327. canvas.addEventListener('mousemove', this.onMouseMove, false);
  41328. canvas.addEventListener('touchmove', this.onMouseMove, false);
  41329. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  41330. this.updateCanvasBounds();
  41331. },
  41332. onMouseMove: (function () {
  41333. var direction = new THREE.Vector3();
  41334. var mouse = new THREE.Vector2();
  41335. var origin = new THREE.Vector3();
  41336. var rayCasterConfig = {origin: origin, direction: direction};
  41337. return function (evt) {
  41338. var bounds = this.canvasBounds;
  41339. var camera = this.el.sceneEl.camera;
  41340. var left;
  41341. var point;
  41342. var top;
  41343. camera.parent.updateMatrixWorld();
  41344. // Calculate mouse position based on the canvas element
  41345. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  41346. // Track the first touch for simplicity.
  41347. point = evt.touches.item(0);
  41348. } else {
  41349. point = evt;
  41350. }
  41351. left = point.clientX - bounds.left;
  41352. top = point.clientY - bounds.top;
  41353. mouse.x = (left / bounds.width) * 2 - 1;
  41354. mouse.y = -(top / bounds.height) * 2 + 1;
  41355. origin.setFromMatrixPosition(camera.matrixWorld);
  41356. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  41357. this.el.setAttribute('raycaster', rayCasterConfig);
  41358. if (evt.type === 'touchmove') { evt.preventDefault(); }
  41359. };
  41360. })(),
  41361. /**
  41362. * Trigger mousedown and keep track of the mousedowned entity.
  41363. */
  41364. onCursorDown: function (evt) {
  41365. // Raycast again for touch.
  41366. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  41367. this.onMouseMove(evt);
  41368. this.el.components.raycaster.checkIntersections();
  41369. evt.preventDefault();
  41370. }
  41371. this.twoWayEmit(EVENTS.MOUSEDOWN);
  41372. this.cursorDownEl = this.intersectedEl;
  41373. },
  41374. /**
  41375. * Trigger mouseup if:
  41376. * - Not fusing (mobile has no mouse).
  41377. * - Currently intersecting an entity.
  41378. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  41379. * in case user mousedowned one entity, dragged to another, and mouseupped.
  41380. */
  41381. onCursorUp: function (evt) {
  41382. this.twoWayEmit(EVENTS.MOUSEUP);
  41383. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  41384. // previously cursorUp entity.
  41385. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  41386. this.intersectedEventDetail.intersection = null;
  41387. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  41388. }
  41389. if (!this.data.fuse && this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  41390. this.twoWayEmit(EVENTS.CLICK);
  41391. }
  41392. this.cursorDownEl = null;
  41393. if (evt.type === 'touchend') { evt.preventDefault(); }
  41394. },
  41395. /**
  41396. * Handle intersection.
  41397. */
  41398. onIntersection: function (evt) {
  41399. var currentIntersection;
  41400. var cursorEl = this.el;
  41401. var index;
  41402. var intersectedEl;
  41403. var intersection;
  41404. // Select closest object, excluding the cursor.
  41405. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  41406. intersection = evt.detail.intersections[index];
  41407. intersectedEl = evt.detail.els[index];
  41408. // If cursor is the only intersected object, ignore the event.
  41409. if (!intersectedEl) { return; }
  41410. // Already intersecting this entity.
  41411. if (this.intersectedEl === intersectedEl) { return; }
  41412. // Ignore events further away than active intersection.
  41413. if (this.intersectedEl) {
  41414. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  41415. if (currentIntersection.distance <= intersection.distance) { return; }
  41416. }
  41417. // Unset current intersection.
  41418. this.clearCurrentIntersection(true);
  41419. this.setIntersection(intersectedEl, intersection);
  41420. },
  41421. /**
  41422. * Handle intersection cleared.
  41423. */
  41424. onIntersectionCleared: function (evt) {
  41425. var clearedEls = evt.detail.clearedEls;
  41426. // Check if the current intersection has ended
  41427. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  41428. this.clearCurrentIntersection();
  41429. },
  41430. setIntersection: function (intersectedEl, intersection) {
  41431. var cursorEl = this.el;
  41432. var data = this.data;
  41433. var self = this;
  41434. // Already intersecting.
  41435. if (this.intersectedEl === intersectedEl) { return; }
  41436. // Set new intersection.
  41437. this.intersectedEl = intersectedEl;
  41438. // Hovering.
  41439. cursorEl.addState(STATES.HOVERING);
  41440. intersectedEl.addState(STATES.HOVERED);
  41441. this.twoWayEmit(EVENTS.MOUSEENTER);
  41442. // Begin fuse if necessary.
  41443. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  41444. cursorEl.addState(STATES.FUSING);
  41445. this.twoWayEmit(EVENTS.FUSING);
  41446. this.fuseTimeout = setTimeout(function fuse () {
  41447. cursorEl.removeState(STATES.FUSING);
  41448. self.twoWayEmit(EVENTS.CLICK);
  41449. }, data.fuseTimeout);
  41450. },
  41451. clearCurrentIntersection: function (ignoreRemaining) {
  41452. var index;
  41453. var intersection;
  41454. var intersections;
  41455. var cursorEl = this.el;
  41456. // Nothing to be cleared.
  41457. if (!this.intersectedEl) { return; }
  41458. // No longer hovering (or fusing).
  41459. this.intersectedEl.removeState(STATES.HOVERED);
  41460. cursorEl.removeState(STATES.HOVERING);
  41461. cursorEl.removeState(STATES.FUSING);
  41462. this.twoWayEmit(EVENTS.MOUSELEAVE);
  41463. // Unset intersected entity (after emitting the event).
  41464. this.intersectedEl = null;
  41465. // Clear fuseTimeout.
  41466. clearTimeout(this.fuseTimeout);
  41467. // Set intersection to another raycasted element if any.
  41468. if (ignoreRemaining === true) { return; }
  41469. intersections = this.el.components.raycaster.intersections;
  41470. if (intersections.length === 0) { return; }
  41471. // Exclude the cursor.
  41472. index = intersections[0].object.el === cursorEl ? 1 : 0;
  41473. intersection = intersections[index];
  41474. if (!intersection) { return; }
  41475. this.setIntersection(intersection.object.el, intersection);
  41476. },
  41477. /**
  41478. * Helper to emit on both the cursor and the intersected entity (if exists).
  41479. */
  41480. twoWayEmit: function (evtName) {
  41481. var el = this.el;
  41482. var intersectedEl = this.intersectedEl;
  41483. var intersection;
  41484. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  41485. this.eventDetail.intersectedEl = intersectedEl;
  41486. this.eventDetail.intersection = intersection;
  41487. el.emit(evtName, this.eventDetail);
  41488. if (!intersectedEl) { return; }
  41489. this.intersectedEventDetail.intersection = intersection;
  41490. intersectedEl.emit(evtName, this.intersectedEventDetail);
  41491. }
  41492. });
  41493. },{"../core/component":103,"../utils/":173}],55:[function(_dereq_,module,exports){
  41494. var registerComponent = _dereq_('../core/component').registerComponent;
  41495. var bind = _dereq_('../utils/bind');
  41496. var checkControllerPresentAndSetup = _dereq_('../utils/tracked-controls').checkControllerPresentAndSetup;
  41497. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  41498. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  41499. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  41500. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  41501. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  41502. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  41503. var GAMEPAD_ID_PREFIX = 'Daydream Controller';
  41504. /**
  41505. * Daydream controls.
  41506. * Interface with Daydream controller and map Gamepad events to
  41507. * controller buttons: trackpad, menu, system
  41508. * Load a controller model and highlight the pressed buttons.
  41509. */
  41510. module.exports.Component = registerComponent('daydream-controls', {
  41511. schema: {
  41512. hand: {default: ''}, // This informs the degenerate arm model.
  41513. buttonColor: {type: 'color', default: '#000000'},
  41514. buttonTouchedColor: {type: 'color', default: '#777777'},
  41515. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  41516. model: {default: true},
  41517. orientationOffset: {type: 'vec3'},
  41518. armModel: {default: true}
  41519. },
  41520. /**
  41521. * Button IDs:
  41522. * 0 - trackpad
  41523. * 1 - menu (never dispatched on this layer)
  41524. * 2 - system (never dispatched on this layer)
  41525. */
  41526. mapping: {
  41527. axes: {trackpad: [0, 1]},
  41528. buttons: ['trackpad', 'menu', 'system']
  41529. },
  41530. bindMethods: function () {
  41531. this.onModelLoaded = bind(this.onModelLoaded, this);
  41532. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  41533. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  41534. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  41535. this.onAxisMoved = bind(this.onAxisMoved, this);
  41536. },
  41537. init: function () {
  41538. var self = this;
  41539. this.animationActive = 'pointing';
  41540. this.onButtonChanged = bind(this.onButtonChanged, this);
  41541. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  41542. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  41543. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  41544. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  41545. this.onAxisMoved = bind(this.onAxisMoved, this);
  41546. this.controllerPresent = false;
  41547. this.lastControllerCheck = 0;
  41548. this.bindMethods();
  41549. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  41550. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  41551. },
  41552. addEventListeners: function () {
  41553. var el = this.el;
  41554. el.addEventListener('buttonchanged', this.onButtonChanged);
  41555. el.addEventListener('buttondown', this.onButtonDown);
  41556. el.addEventListener('buttonup', this.onButtonUp);
  41557. el.addEventListener('touchstart', this.onButtonTouchStart);
  41558. el.addEventListener('touchend', this.onButtonTouchEnd);
  41559. el.addEventListener('model-loaded', this.onModelLoaded);
  41560. el.addEventListener('axismove', this.onAxisMoved);
  41561. this.controllerEventsActive = true;
  41562. },
  41563. removeEventListeners: function () {
  41564. var el = this.el;
  41565. el.removeEventListener('buttonchanged', this.onButtonChanged);
  41566. el.removeEventListener('buttondown', this.onButtonDown);
  41567. el.removeEventListener('buttonup', this.onButtonUp);
  41568. el.removeEventListener('touchstart', this.onButtonTouchStart);
  41569. el.removeEventListener('touchend', this.onButtonTouchEnd);
  41570. el.removeEventListener('model-loaded', this.onModelLoaded);
  41571. el.removeEventListener('axismove', this.onAxisMoved);
  41572. this.controllerEventsActive = false;
  41573. },
  41574. checkIfControllerPresent: function () {
  41575. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {hand: this.data.hand});
  41576. },
  41577. play: function () {
  41578. this.checkIfControllerPresent();
  41579. this.addControllersUpdateListener();
  41580. },
  41581. pause: function () {
  41582. this.removeEventListeners();
  41583. this.removeControllersUpdateListener();
  41584. },
  41585. injectTrackedControls: function () {
  41586. var el = this.el;
  41587. var data = this.data;
  41588. el.setAttribute('tracked-controls', {
  41589. armModel: data.armModel,
  41590. hand: data.hand,
  41591. idPrefix: GAMEPAD_ID_PREFIX,
  41592. orientationOffset: data.orientationOffset
  41593. });
  41594. if (!this.data.model) { return; }
  41595. this.el.setAttribute('obj-model', {
  41596. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  41597. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  41598. });
  41599. },
  41600. addControllersUpdateListener: function () {
  41601. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  41602. },
  41603. removeControllersUpdateListener: function () {
  41604. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  41605. },
  41606. onControllersUpdate: function () {
  41607. this.checkIfControllerPresent();
  41608. },
  41609. onModelLoaded: function (evt) {
  41610. var controllerObject3D = evt.detail.model;
  41611. var buttonMeshes;
  41612. if (!this.data.model) { return; }
  41613. buttonMeshes = this.buttonMeshes = {};
  41614. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  41615. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  41616. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  41617. // Offset pivot point.
  41618. controllerObject3D.position.set(0, 0, -0.04);
  41619. },
  41620. onAxisMoved: function (evt) {
  41621. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  41622. },
  41623. onButtonChanged: function (evt) {
  41624. var button = this.mapping.buttons[evt.detail.id];
  41625. if (!button) return;
  41626. // Pass along changed event with button state, using button mapping for convenience.
  41627. this.el.emit(button + 'changed', evt.detail.state);
  41628. },
  41629. updateModel: function (buttonName, evtName) {
  41630. if (!this.data.model) { return; }
  41631. this.updateButtonModel(buttonName, evtName);
  41632. },
  41633. updateButtonModel: function (buttonName, state) {
  41634. var buttonMeshes = this.buttonMeshes;
  41635. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  41636. var color;
  41637. switch (state) {
  41638. case 'down':
  41639. color = this.data.buttonHighlightColor;
  41640. break;
  41641. case 'touchstart':
  41642. color = this.data.buttonTouchedColor;
  41643. break;
  41644. default:
  41645. color = this.data.buttonColor;
  41646. }
  41647. buttonMeshes[buttonName].material.color.set(color);
  41648. }
  41649. });
  41650. },{"../core/component":103,"../utils/bind":167,"../utils/tracked-controls":179}],56:[function(_dereq_,module,exports){
  41651. var registerComponent = _dereq_('../core/component').registerComponent;
  41652. var bind = _dereq_('../utils/bind');
  41653. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  41654. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  41655. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  41656. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  41657. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  41658. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  41659. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  41660. var GAMEPAD_ID_PREFIX = 'Gear VR';
  41661. /**
  41662. * Gear VR controls.
  41663. * Interface with Gear VR controller and map Gamepad events to
  41664. * controller buttons: trackpad, trigger
  41665. * Load a controller model and highlight the pressed buttons.
  41666. */
  41667. module.exports.Component = registerComponent('gearvr-controls', {
  41668. schema: {
  41669. hand: {default: ''}, // This informs the degenerate arm model.
  41670. buttonColor: {type: 'color', default: '#000000'},
  41671. buttonTouchedColor: {type: 'color', default: '#777777'},
  41672. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  41673. model: {default: true},
  41674. orientationOffset: {type: 'vec3'},
  41675. armModel: {default: true}
  41676. },
  41677. /**
  41678. * Button IDs:
  41679. * 0 - trackpad
  41680. * 1 - trigger
  41681. */
  41682. mapping: {
  41683. axes: {trackpad: [0, 1]},
  41684. buttons: ['trackpad', 'trigger']
  41685. },
  41686. bindMethods: function () {
  41687. this.onModelLoaded = bind(this.onModelLoaded, this);
  41688. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  41689. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  41690. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  41691. this.onAxisMoved = bind(this.onAxisMoved, this);
  41692. },
  41693. init: function () {
  41694. var self = this;
  41695. this.animationActive = 'pointing';
  41696. this.onButtonChanged = bind(this.onButtonChanged, this);
  41697. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  41698. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  41699. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  41700. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  41701. this.onAxisMoved = bind(this.onAxisMoved, this);
  41702. this.controllerPresent = false;
  41703. this.lastControllerCheck = 0;
  41704. this.bindMethods();
  41705. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  41706. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  41707. },
  41708. addEventListeners: function () {
  41709. var el = this.el;
  41710. el.addEventListener('buttonchanged', this.onButtonChanged);
  41711. el.addEventListener('buttondown', this.onButtonDown);
  41712. el.addEventListener('buttonup', this.onButtonUp);
  41713. el.addEventListener('touchstart', this.onButtonTouchStart);
  41714. el.addEventListener('touchend', this.onButtonTouchEnd);
  41715. el.addEventListener('model-loaded', this.onModelLoaded);
  41716. el.addEventListener('axismove', this.onAxisMoved);
  41717. this.controllerEventsActive = true;
  41718. this.addControllersUpdateListener();
  41719. },
  41720. removeEventListeners: function () {
  41721. var el = this.el;
  41722. el.removeEventListener('buttonchanged', this.onButtonChanged);
  41723. el.removeEventListener('buttondown', this.onButtonDown);
  41724. el.removeEventListener('buttonup', this.onButtonUp);
  41725. el.removeEventListener('touchstart', this.onButtonTouchStart);
  41726. el.removeEventListener('touchend', this.onButtonTouchEnd);
  41727. el.removeEventListener('model-loaded', this.onModelLoaded);
  41728. el.removeEventListener('axismove', this.onAxisMoved);
  41729. this.controllerEventsActive = false;
  41730. this.removeControllersUpdateListener();
  41731. },
  41732. checkIfControllerPresent: function () {
  41733. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  41734. this.data.hand ? {hand: this.data.hand} : {});
  41735. },
  41736. play: function () {
  41737. this.checkIfControllerPresent();
  41738. this.addControllersUpdateListener();
  41739. },
  41740. pause: function () {
  41741. this.removeEventListeners();
  41742. this.removeControllersUpdateListener();
  41743. },
  41744. injectTrackedControls: function () {
  41745. var el = this.el;
  41746. var data = this.data;
  41747. el.setAttribute('tracked-controls', {
  41748. armModel: data.armModel,
  41749. idPrefix: GAMEPAD_ID_PREFIX,
  41750. orientationOffset: data.orientationOffset
  41751. });
  41752. if (!this.data.model) { return; }
  41753. this.el.setAttribute('obj-model', {
  41754. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  41755. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  41756. });
  41757. },
  41758. addControllersUpdateListener: function () {
  41759. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  41760. },
  41761. removeControllersUpdateListener: function () {
  41762. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  41763. },
  41764. onControllersUpdate: function () {
  41765. this.checkIfControllerPresent();
  41766. },
  41767. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  41768. onModelLoaded: function (evt) {
  41769. var controllerObject3D = evt.detail.model;
  41770. var buttonMeshes;
  41771. if (!this.data.model) { return; }
  41772. buttonMeshes = this.buttonMeshes = {};
  41773. buttonMeshes.trigger = controllerObject3D.children[2];
  41774. buttonMeshes.trackpad = controllerObject3D.children[1];
  41775. },
  41776. onButtonChanged: function (evt) {
  41777. var button = this.mapping.buttons[evt.detail.id];
  41778. if (!button) return;
  41779. // Pass along changed event with button state, using button mapping for convenience.
  41780. this.el.emit(button + 'changed', evt.detail.state);
  41781. },
  41782. onAxisMoved: function (evt) {
  41783. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  41784. },
  41785. updateModel: function (buttonName, evtName) {
  41786. if (!this.data.model) { return; }
  41787. this.updateButtonModel(buttonName, evtName);
  41788. },
  41789. updateButtonModel: function (buttonName, state) {
  41790. var buttonMeshes = this.buttonMeshes;
  41791. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  41792. var color;
  41793. switch (state) {
  41794. case 'down':
  41795. color = this.data.buttonHighlightColor;
  41796. break;
  41797. case 'touchstart':
  41798. color = this.data.buttonTouchedColor;
  41799. break;
  41800. default:
  41801. color = this.data.buttonColor;
  41802. }
  41803. buttonMeshes[buttonName].material.color.set(color);
  41804. }
  41805. });
  41806. },{"../core/component":103,"../utils/bind":167,"../utils/tracked-controls":179}],57:[function(_dereq_,module,exports){
  41807. var geometries = _dereq_('../core/geometry').geometries;
  41808. var geometryNames = _dereq_('../core/geometry').geometryNames;
  41809. var registerComponent = _dereq_('../core/component').registerComponent;
  41810. var THREE = _dereq_('../lib/three');
  41811. var dummyGeometry = new THREE.Geometry();
  41812. /**
  41813. * Geometry component. Combined with material component to make a mesh in 3D object.
  41814. * Extended with registered geometries.
  41815. */
  41816. module.exports.Component = registerComponent('geometry', {
  41817. schema: {
  41818. buffer: {default: true},
  41819. primitive: {default: 'box', oneOf: geometryNames},
  41820. skipCache: {default: false}
  41821. },
  41822. init: function () {
  41823. this.geometry = null;
  41824. },
  41825. /**
  41826. * Talk to geometry system to get or create geometry.
  41827. */
  41828. update: function (previousData) {
  41829. var data = this.data;
  41830. var el = this.el;
  41831. var mesh;
  41832. var system = this.system;
  41833. // Dispose old geometry if we created one.
  41834. if (this.geometry) {
  41835. system.unuseGeometry(previousData);
  41836. this.geometry = null;
  41837. }
  41838. // Create new geometry.
  41839. this.geometry = system.getOrCreateGeometry(data);
  41840. // Set on mesh. If mesh does not exist, create it.
  41841. mesh = el.getObject3D('mesh');
  41842. if (mesh) {
  41843. mesh.geometry = this.geometry;
  41844. } else {
  41845. mesh = new THREE.Mesh();
  41846. mesh.geometry = this.geometry;
  41847. el.setObject3D('mesh', mesh);
  41848. }
  41849. },
  41850. /**
  41851. * Tell geometry system that entity is no longer using the geometry.
  41852. * Unset the geometry on the mesh
  41853. */
  41854. remove: function () {
  41855. this.system.unuseGeometry(this.data);
  41856. this.el.getObject3D('mesh').geometry = dummyGeometry;
  41857. this.geometry = null;
  41858. },
  41859. /**
  41860. * Update geometry component schema based on geometry type.
  41861. *
  41862. * @param {object} data - New data passed by Component.
  41863. */
  41864. updateSchema: function (data) {
  41865. var newGeometryType = data.primitive;
  41866. var currentGeometryType = this.data && this.data.primitive;
  41867. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  41868. // Geometry has no schema.
  41869. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  41870. // Nothing has changed.
  41871. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  41872. this.extendSchema(schema);
  41873. }
  41874. });
  41875. },{"../core/component":103,"../core/geometry":104,"../lib/three":151}],58:[function(_dereq_,module,exports){
  41876. var registerComponent = _dereq_('../core/component').registerComponent;
  41877. var THREE = _dereq_('../lib/three');
  41878. var utils = _dereq_('../utils/');
  41879. var warn = utils.debug('components:gltf-model:warn');
  41880. /**
  41881. * glTF model loader.
  41882. */
  41883. module.exports.Component = registerComponent('gltf-model', {
  41884. schema: {type: 'model'},
  41885. init: function () {
  41886. this.model = null;
  41887. this.loader = new THREE.GLTFLoader();
  41888. },
  41889. update: function () {
  41890. var self = this;
  41891. var el = this.el;
  41892. var src = this.data;
  41893. if (!src) { return; }
  41894. this.remove();
  41895. this.loader.load(src, function gltfLoaded (gltfModel) {
  41896. self.model = gltfModel.scene || gltfModel.scenes[0];
  41897. self.model.animations = gltfModel.animations;
  41898. el.setObject3D('mesh', self.model);
  41899. el.emit('model-loaded', {format: 'gltf', model: self.model});
  41900. }, undefined /* onProgress */, function gltfFailed (error) {
  41901. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  41902. warn(message);
  41903. el.emit('model-error', {format: 'gltf', src: src});
  41904. });
  41905. },
  41906. remove: function () {
  41907. if (!this.model) { return; }
  41908. this.el.removeObject3D('mesh');
  41909. }
  41910. });
  41911. },{"../core/component":103,"../lib/three":151,"../utils/":173}],59:[function(_dereq_,module,exports){
  41912. /* global THREE */
  41913. var registerComponent = _dereq_('../core/component').registerComponent;
  41914. // Found at https://github.com/aframevr/assets.
  41915. var MODEL_URLS = {
  41916. left: 'https://cdn.aframe.io/controllers/oculus-hands/v2/leftHand.json',
  41917. right: 'https://cdn.aframe.io/controllers/oculus-hands/v2/rightHand.json'
  41918. };
  41919. // Poses.
  41920. var ANIMATIONS = {
  41921. open: 'Open',
  41922. // point: grip active, trackpad surface active, trigger inactive.
  41923. point: 'Point',
  41924. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  41925. pointThumb: 'Point + Thumb',
  41926. // fist: grip active, trigger active, trackpad surface active.
  41927. fist: 'Fist',
  41928. // hold: trigger active, grip inactive.
  41929. hold: 'Hold',
  41930. // thumbUp: grip active, trigger active, trackpad surface inactive.
  41931. thumbUp: 'Thumb Up'
  41932. };
  41933. // Map animation to public events for the API.
  41934. var EVENTS = {};
  41935. EVENTS[ANIMATIONS.fist] = 'grip';
  41936. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  41937. EVENTS[ANIMATIONS.point] = 'pointing';
  41938. EVENTS[ANIMATIONS.thumb] = 'thumb';
  41939. /**
  41940. * Hand controls component that abstracts 6DoF controls:
  41941. * oculus-touch-controls, vive-controls, windows-motion-controls.
  41942. *
  41943. * Originally meant to be a sample implementation of applications-specific controls that
  41944. * abstracts multiple types of controllers.
  41945. *
  41946. * Auto-detect appropriate controller.
  41947. * Handle common events coming from the detected vendor-specific controls.
  41948. * Translate button events to semantic hand-related event names:
  41949. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  41950. * Load hand model with gestures that are applied based on the button pressed.
  41951. *
  41952. * @property {string} Hand mapping (`left`, `right`).
  41953. */
  41954. module.exports.Component = registerComponent('hand-controls', {
  41955. schema: {default: 'left'},
  41956. init: function () {
  41957. var self = this;
  41958. var el = this.el;
  41959. // Current pose.
  41960. this.gesture = ANIMATIONS.open;
  41961. // Active buttons populated by events provided by the attached controls.
  41962. this.pressedButtons = {};
  41963. this.touchedButtons = {};
  41964. this.loader = new THREE.ObjectLoader();
  41965. this.loader.setCrossOrigin('anonymous');
  41966. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  41967. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  41968. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  41969. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  41970. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  41971. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  41972. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  41973. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  41974. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  41975. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  41976. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  41977. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  41978. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  41979. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  41980. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  41981. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  41982. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  41983. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  41984. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  41985. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  41986. this.onControllerConnected = function () { self.setModelVisibility(true); };
  41987. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  41988. el.addEventListener('controllerconnected', this.onControllerConnected);
  41989. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  41990. },
  41991. play: function () {
  41992. this.addEventListeners();
  41993. },
  41994. pause: function () {
  41995. this.removeEventListeners();
  41996. },
  41997. tick: function (time, delta) {
  41998. var mesh = this.el.getObject3D('mesh');
  41999. if (!mesh || !mesh.mixer) { return; }
  42000. mesh.mixer.update(delta / 1000);
  42001. },
  42002. addEventListeners: function () {
  42003. var el = this.el;
  42004. el.addEventListener('gripdown', this.onGripDown);
  42005. el.addEventListener('gripup', this.onGripUp);
  42006. el.addEventListener('trackpaddown', this.onTrackpadDown);
  42007. el.addEventListener('trackpadup', this.onTrackpadUp);
  42008. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  42009. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  42010. el.addEventListener('triggerdown', this.onTriggerDown);
  42011. el.addEventListener('triggerup', this.onTriggerUp);
  42012. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  42013. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  42014. el.addEventListener('griptouchstart', this.onGripTouchStart);
  42015. el.addEventListener('griptouchend', this.onGripTouchEnd);
  42016. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  42017. el.addEventListener('thumbstickup', this.onThumbstickUp);
  42018. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  42019. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  42020. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  42021. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  42022. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  42023. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  42024. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  42025. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  42026. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  42027. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  42028. },
  42029. removeEventListeners: function () {
  42030. var el = this.el;
  42031. el.removeEventListener('gripdown', this.onGripDown);
  42032. el.removeEventListener('gripup', this.onGripUp);
  42033. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  42034. el.removeEventListener('trackpadup', this.onTrackpadUp);
  42035. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  42036. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  42037. el.removeEventListener('triggerdown', this.onTriggerDown);
  42038. el.removeEventListener('triggerup', this.onTriggerUp);
  42039. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  42040. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  42041. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  42042. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  42043. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  42044. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  42045. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  42046. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  42047. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  42048. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  42049. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  42050. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  42051. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  42052. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  42053. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  42054. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  42055. },
  42056. /**
  42057. * Update handler. More like the `init` handler since the only property is the hand, and
  42058. * that won't be changing much.
  42059. */
  42060. update: function (previousHand) {
  42061. var controlConfiguration;
  42062. var el = this.el;
  42063. var hand = this.data;
  42064. // Get common configuration to abstract different vendor controls.
  42065. controlConfiguration = {
  42066. hand: hand,
  42067. model: false,
  42068. orientationOffset: {x: 0, y: 0, z: hand === 'left' ? 90 : -90}
  42069. };
  42070. // Set model.
  42071. if (hand !== previousHand) {
  42072. this.loader.load(MODEL_URLS[hand], function (scene) {
  42073. var mesh = scene.getObjectByName('Hand');
  42074. mesh.material.skinning = true;
  42075. mesh.mixer = new THREE.AnimationMixer(mesh);
  42076. el.setObject3D('mesh', mesh);
  42077. mesh.position.set(0, 0, 0);
  42078. mesh.rotation.set(0, 0, 0);
  42079. // hidden by default
  42080. mesh.visible = false;
  42081. el.setAttribute('vive-controls', controlConfiguration);
  42082. el.setAttribute('oculus-touch-controls', controlConfiguration);
  42083. el.setAttribute('windows-motion-controls', controlConfiguration);
  42084. });
  42085. }
  42086. },
  42087. remove: function () {
  42088. this.el.removeObject3D('mesh');
  42089. },
  42090. /**
  42091. * Play model animation, based on which button was pressed and which kind of event.
  42092. *
  42093. * 1. Process buttons.
  42094. * 2. Determine gesture (this.determineGesture()).
  42095. * 3. Animation gesture (this.animationGesture()).
  42096. * 4. Emit gesture events (this.emitGestureEvents()).
  42097. *
  42098. * @param {string} button - Name of the button.
  42099. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  42100. */
  42101. handleButton: function (button, evt) {
  42102. var lastGesture;
  42103. var isPressed = evt === 'down';
  42104. var isTouched = evt === 'touchstart';
  42105. // Update objects.
  42106. if (evt.indexOf('touch') === 0) {
  42107. // Update touch object.
  42108. if (isTouched === this.touchedButtons[button]) { return; }
  42109. this.touchedButtons[button] = isTouched;
  42110. } else {
  42111. // Update button object.
  42112. if (isPressed === this.pressedButtons[button]) { return; }
  42113. this.pressedButtons[button] = isPressed;
  42114. }
  42115. // Determine the gesture.
  42116. lastGesture = this.gesture;
  42117. this.gesture = this.determineGesture();
  42118. // Same gesture.
  42119. if (this.gesture === lastGesture) { return; }
  42120. // Animate gesture.
  42121. this.animateGesture(this.gesture, lastGesture);
  42122. // Emit events.
  42123. this.emitGestureEvents(this.gesture, lastGesture);
  42124. },
  42125. /**
  42126. * Determine which pose hand should be in considering active and touched buttons.
  42127. */
  42128. determineGesture: function () {
  42129. var gesture;
  42130. var isGripActive = this.pressedButtons['grip'];
  42131. var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
  42132. var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
  42133. var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
  42134. var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
  42135. var isVive = isViveController(this.el.components['tracked-controls']);
  42136. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  42137. if (isGripActive) {
  42138. if (isVive) {
  42139. gesture = ANIMATIONS.fist;
  42140. } else
  42141. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  42142. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  42143. } else {
  42144. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  42145. }
  42146. } else {
  42147. if (isTriggerActive) {
  42148. gesture = !isVive ? ANIMATIONS.hold : ANIMATIONS.fist;
  42149. } else if (isVive && isTrackpadActive) {
  42150. gesture = ANIMATIONS.point;
  42151. }
  42152. }
  42153. return gesture;
  42154. },
  42155. /**
  42156. * Play gesture animation.
  42157. *
  42158. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  42159. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  42160. */
  42161. animateGesture: function (gesture, lastGesture) {
  42162. if (gesture) {
  42163. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  42164. return;
  42165. }
  42166. // If no gesture, then reverse the current gesture back to open pose.
  42167. this.playAnimation(lastGesture, lastGesture, true);
  42168. },
  42169. /**
  42170. * Emit `hand-controls`-specific events.
  42171. */
  42172. emitGestureEvents: function (gesture, lastGesture) {
  42173. var el = this.el;
  42174. var eventName;
  42175. if (lastGesture === gesture) { return; }
  42176. // Emit event for lastGesture not inactive.
  42177. eventName = getGestureEventName(lastGesture, false);
  42178. if (eventName) { el.emit(eventName); }
  42179. // Emit event for current gesture now active.
  42180. eventName = getGestureEventName(gesture, true);
  42181. if (eventName) { el.emit(eventName); }
  42182. },
  42183. /**
  42184. * Play hand animation based on button state.
  42185. *
  42186. * @param {string} gesture - Name of the animation as specified by the model.
  42187. * @param {string} lastGesture - Previous pose.
  42188. * @param {boolean} reverse - Whether animation should play in reverse.
  42189. */
  42190. playAnimation: function (gesture, lastGesture, reverse) {
  42191. var fromAction;
  42192. var mesh = this.el.getObject3D('mesh');
  42193. var toAction;
  42194. if (!mesh) { return; }
  42195. // Grab clip action.
  42196. toAction = mesh.mixer.clipAction(gesture);
  42197. toAction.clampWhenFinished = true;
  42198. toAction.loop = THREE.LoopRepeat;
  42199. toAction.repetitions = 0;
  42200. toAction.timeScale = reverse ? -1 : 1;
  42201. toAction.weight = 1;
  42202. // No gesture to gesture or gesture to no gesture.
  42203. if (!lastGesture || gesture === lastGesture) {
  42204. // Stop all current animations.
  42205. mesh.mixer.stopAllAction();
  42206. // Play animation.
  42207. toAction.play();
  42208. return;
  42209. }
  42210. // Animate or crossfade from gesture to gesture.
  42211. fromAction = mesh.mixer.clipAction(lastGesture);
  42212. mesh.mixer.stopAllAction();
  42213. fromAction.weight = 0.15;
  42214. fromAction.play();
  42215. toAction.play();
  42216. fromAction.crossFadeTo(toAction, 0.15, true);
  42217. },
  42218. setModelVisibility: function (visible) {
  42219. var model = this.el.getObject3D('mesh');
  42220. if (!model) { return; }
  42221. model.visible = visible;
  42222. }
  42223. });
  42224. /**
  42225. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  42226. *
  42227. * @param {string} gesture
  42228. * @param {boolean} active
  42229. */
  42230. function getGestureEventName (gesture, active) {
  42231. var eventName;
  42232. if (!gesture) { return; }
  42233. eventName = EVENTS[gesture];
  42234. if (eventName === 'grip') {
  42235. return eventName + (active ? 'close' : 'open');
  42236. }
  42237. if (eventName === 'point' || eventName === 'thumb') {
  42238. return eventName + (active ? 'up' : 'down');
  42239. }
  42240. if (eventName === 'pointing' || eventName === 'pistol') {
  42241. return eventName + (active ? 'start' : 'end');
  42242. }
  42243. return;
  42244. }
  42245. function isViveController (trackedControls) {
  42246. var controllerId = trackedControls && trackedControls.controller &&
  42247. trackedControls.controller.id;
  42248. return controllerId && controllerId.indexOf('OpenVR ') === 0;
  42249. }
  42250. },{"../core/component":103}],60:[function(_dereq_,module,exports){
  42251. _dereq_('./camera');
  42252. _dereq_('./collada-model');
  42253. _dereq_('./cursor');
  42254. _dereq_('./daydream-controls');
  42255. _dereq_('./gearvr-controls');
  42256. _dereq_('./geometry');
  42257. _dereq_('./gltf-model');
  42258. _dereq_('./hand-controls');
  42259. _dereq_('./laser-controls');
  42260. _dereq_('./light');
  42261. _dereq_('./line');
  42262. _dereq_('./link');
  42263. _dereq_('./look-controls');
  42264. _dereq_('./material');
  42265. _dereq_('./obj-model');
  42266. _dereq_('./oculus-go-controls');
  42267. _dereq_('./oculus-touch-controls');
  42268. _dereq_('./position');
  42269. _dereq_('./raycaster');
  42270. _dereq_('./rotation');
  42271. _dereq_('./scale');
  42272. _dereq_('./shadow');
  42273. _dereq_('./sound');
  42274. _dereq_('./text');
  42275. _dereq_('./tracked-controls');
  42276. _dereq_('./visible');
  42277. _dereq_('./vive-controls');
  42278. _dereq_('./wasd-controls');
  42279. _dereq_('./windows-motion-controls');
  42280. _dereq_('./scene/background');
  42281. _dereq_('./scene/debug');
  42282. _dereq_('./scene/embedded');
  42283. _dereq_('./scene/inspector');
  42284. _dereq_('./scene/fog');
  42285. _dereq_('./scene/keyboard-shortcuts');
  42286. _dereq_('./scene/pool');
  42287. _dereq_('./scene/renderer');
  42288. _dereq_('./scene/screenshot');
  42289. _dereq_('./scene/stats');
  42290. _dereq_('./scene/vr-mode-ui');
  42291. },{"./camera":52,"./collada-model":53,"./cursor":54,"./daydream-controls":55,"./gearvr-controls":56,"./geometry":57,"./gltf-model":58,"./hand-controls":59,"./laser-controls":61,"./light":62,"./line":63,"./link":64,"./look-controls":65,"./material":66,"./obj-model":67,"./oculus-go-controls":68,"./oculus-touch-controls":69,"./position":70,"./raycaster":71,"./rotation":72,"./scale":73,"./scene/background":74,"./scene/debug":75,"./scene/embedded":76,"./scene/fog":77,"./scene/inspector":78,"./scene/keyboard-shortcuts":79,"./scene/pool":80,"./scene/renderer":81,"./scene/screenshot":82,"./scene/stats":83,"./scene/vr-mode-ui":84,"./shadow":85,"./sound":86,"./text":87,"./tracked-controls":88,"./visible":89,"./vive-controls":90,"./wasd-controls":91,"./windows-motion-controls":92}],61:[function(_dereq_,module,exports){
  42292. var registerComponent = _dereq_('../core/component').registerComponent;
  42293. var utils = _dereq_('../utils/');
  42294. registerComponent('laser-controls', {
  42295. schema: {
  42296. hand: {default: 'right'}
  42297. },
  42298. init: function () {
  42299. var config = this.config;
  42300. var data = this.data;
  42301. var el = this.el;
  42302. var self = this;
  42303. // Set all controller models.
  42304. el.setAttribute('daydream-controls', {hand: data.hand});
  42305. el.setAttribute('gearvr-controls', {hand: data.hand});
  42306. el.setAttribute('oculus-go-controls', {hand: data.hand});
  42307. el.setAttribute('oculus-touch-controls', {hand: data.hand});
  42308. el.setAttribute('vive-controls', {hand: data.hand});
  42309. el.setAttribute('windows-motion-controls', {hand: data.hand});
  42310. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  42311. el.addEventListener('controllerconnected', createRay);
  42312. el.addEventListener('controllerdisconnected', hideRay);
  42313. el.addEventListener('controllermodelready', function (evt) {
  42314. createRay(evt);
  42315. self.modelReady = true;
  42316. });
  42317. function createRay (evt) {
  42318. var controllerConfig = config[evt.detail.name];
  42319. if (!controllerConfig) { return; }
  42320. // Show the line unless a particular config opts to hide it, until a controllermodelready
  42321. // event comes through.
  42322. var raycasterConfig = utils.extend({
  42323. showLine: true
  42324. }, controllerConfig.raycaster || {});
  42325. // The controllermodelready event contains a rayOrigin that takes into account
  42326. // offsets specific to the loaded model.
  42327. if (evt.detail.rayOrigin) {
  42328. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  42329. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  42330. raycasterConfig.showLine = true;
  42331. }
  42332. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  42333. // config applied from a controllermodelready event.
  42334. if (evt.detail.rayOrigin || !self.modelReady) {
  42335. el.setAttribute('raycaster', raycasterConfig);
  42336. } else {
  42337. el.setAttribute('raycaster', 'showLine', true);
  42338. }
  42339. el.setAttribute('cursor', utils.extend({
  42340. fuse: false
  42341. }, controllerConfig.cursor));
  42342. }
  42343. function hideRay () {
  42344. el.setAttribute('raycaster', 'showLine', false);
  42345. }
  42346. },
  42347. config: {
  42348. 'daydream-controls': {
  42349. cursor: {downEvents: ['trackpaddown'], upEvents: ['trackpadup']}
  42350. },
  42351. 'gearvr-controls': {
  42352. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']},
  42353. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  42354. },
  42355. 'oculus-go-controls': {
  42356. cursor: {downEvents: ['trackpaddown'], upEvents: ['trackpadup']},
  42357. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  42358. },
  42359. 'oculus-touch-controls': {
  42360. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  42361. raycaster: {origin: {x: 0, y: 0, z: 0}}
  42362. },
  42363. 'vive-controls': {
  42364. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  42365. },
  42366. 'windows-motion-controls': {
  42367. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  42368. raycaster: {showLine: false}
  42369. }
  42370. }
  42371. });
  42372. },{"../core/component":103,"../utils/":173}],62:[function(_dereq_,module,exports){
  42373. var bind = _dereq_('../utils/bind');
  42374. var diff = _dereq_('../utils').diff;
  42375. var debug = _dereq_('../utils/debug');
  42376. var registerComponent = _dereq_('../core/component').registerComponent;
  42377. var THREE = _dereq_('../lib/three');
  42378. var degToRad = THREE.Math.degToRad;
  42379. var warn = debug('components:light:warn');
  42380. /**
  42381. * Light component.
  42382. */
  42383. module.exports.Component = registerComponent('light', {
  42384. schema: {
  42385. angle: {default: 60, if: {type: ['spot']}},
  42386. color: {type: 'color'},
  42387. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  42388. decay: {default: 1, if: {type: ['point', 'spot']}},
  42389. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  42390. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  42391. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  42392. type: {default: 'directional', oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot']},
  42393. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  42394. // Shadows.
  42395. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  42396. shadowBias: {default: 0, if: {castShadow: true}},
  42397. shadowCameraFar: {default: 500, if: {castShadow: true}},
  42398. shadowCameraFov: {default: 90, if: {castShadow: true}},
  42399. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  42400. shadowCameraTop: {default: 5, if: {castShadow: true}},
  42401. shadowCameraRight: {default: 5, if: {castShadow: true}},
  42402. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  42403. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  42404. shadowCameraVisible: {default: false, if: {castShadow: true}},
  42405. shadowMapHeight: {default: 512, if: {castShadow: true}},
  42406. shadowMapWidth: {default: 512, if: {castShadow: true}},
  42407. shadowRadius: {default: 1, if: {castShadow: true}}
  42408. },
  42409. /**
  42410. * Notifies scene a light has been added to remove default lighting.
  42411. */
  42412. init: function () {
  42413. var el = this.el;
  42414. this.light = null;
  42415. this.defaultTarget = null;
  42416. this.system.registerLight(el);
  42417. },
  42418. /**
  42419. * (Re)create or update light.
  42420. */
  42421. update: function (oldData) {
  42422. var data = this.data;
  42423. var diffData = diff(data, oldData);
  42424. var light = this.light;
  42425. var self = this;
  42426. // Existing light.
  42427. if (light && !('type' in diffData)) {
  42428. var shadowsLoaded = false;
  42429. // Light type has not changed. Update light.
  42430. Object.keys(diffData).forEach(function (key) {
  42431. var value = data[key];
  42432. switch (key) {
  42433. case 'color': {
  42434. light.color.set(value);
  42435. break;
  42436. }
  42437. case 'groundColor': {
  42438. light.groundColor.set(value);
  42439. break;
  42440. }
  42441. case 'angle': {
  42442. light.angle = degToRad(value);
  42443. break;
  42444. }
  42445. case 'target': {
  42446. // Reset target if selector is null.
  42447. if (value === null) {
  42448. if (data.type === 'spot' || data.type === 'directional') {
  42449. light.target = self.defaultTarget;
  42450. }
  42451. } else {
  42452. // Target specified, set target to entity's `object3D` when it is loaded.
  42453. if (value.hasLoaded) {
  42454. self.onSetTarget(value, light);
  42455. } else {
  42456. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  42457. }
  42458. }
  42459. break;
  42460. }
  42461. case 'castShadow':
  42462. case 'shadowBias':
  42463. case 'shadowCameraFar':
  42464. case 'shadowCameraFov':
  42465. case 'shadowCameraNear':
  42466. case 'shadowCameraTop':
  42467. case 'shadowCameraRight':
  42468. case 'shadowCameraBottom':
  42469. case 'shadowCameraLeft':
  42470. case 'shadowCameraVisible':
  42471. case 'shadowMapHeight':
  42472. case 'shadowMapWidth':
  42473. case 'shadowRadius':
  42474. if (!shadowsLoaded) {
  42475. self.updateShadow();
  42476. shadowsLoaded = true;
  42477. }
  42478. break;
  42479. default: {
  42480. light[key] = value;
  42481. }
  42482. }
  42483. });
  42484. return;
  42485. }
  42486. // No light yet or light type has changed. Create and add light.
  42487. this.setLight(this.data);
  42488. this.updateShadow();
  42489. },
  42490. setLight: function (data) {
  42491. var el = this.el;
  42492. var newLight = this.getLight(data);
  42493. if (newLight) {
  42494. if (this.light) {
  42495. el.removeObject3D('light');
  42496. }
  42497. this.light = newLight;
  42498. this.light.el = el;
  42499. el.setObject3D('light', this.light);
  42500. // HACK solution for issue #1624
  42501. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  42502. el.getObject3D('light').translateY(-1);
  42503. }
  42504. // set and position default lighttarget as a child to enable spotlight orientation
  42505. if (data.type === 'spot') {
  42506. el.setObject3D('light-target', this.defaultTarget);
  42507. el.getObject3D('light-target').position.set(0, 0, -1);
  42508. }
  42509. }
  42510. },
  42511. /**
  42512. * Updates shadow-related properties on the current light.
  42513. */
  42514. updateShadow: function () {
  42515. var el = this.el;
  42516. var data = this.data;
  42517. var light = this.light;
  42518. light.castShadow = data.castShadow;
  42519. // Shadow camera helper.
  42520. var cameraHelper = el.getObject3D('cameraHelper');
  42521. if (data.shadowCameraVisible && !cameraHelper) {
  42522. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  42523. } else if (!data.shadowCameraVisible && cameraHelper) {
  42524. el.removeObject3D('cameraHelper');
  42525. }
  42526. if (!data.castShadow) { return light; }
  42527. // Shadow appearance.
  42528. light.shadow.bias = data.shadowBias;
  42529. light.shadow.radius = data.shadowRadius;
  42530. light.shadow.mapSize.height = data.shadowMapHeight;
  42531. light.shadow.mapSize.width = data.shadowMapWidth;
  42532. // Shadow camera.
  42533. light.shadow.camera.near = data.shadowCameraNear;
  42534. light.shadow.camera.far = data.shadowCameraFar;
  42535. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  42536. light.shadow.camera.top = data.shadowCameraTop;
  42537. light.shadow.camera.right = data.shadowCameraRight;
  42538. light.shadow.camera.bottom = data.shadowCameraBottom;
  42539. light.shadow.camera.left = data.shadowCameraLeft;
  42540. } else {
  42541. light.shadow.camera.fov = data.shadowCameraFov;
  42542. }
  42543. light.shadow.camera.updateProjectionMatrix();
  42544. if (cameraHelper) { cameraHelper.update(); }
  42545. },
  42546. /**
  42547. * Creates a new three.js light object given data object defining the light.
  42548. *
  42549. * @param {object} data
  42550. */
  42551. getLight: function (data) {
  42552. var angle = data.angle;
  42553. var color = new THREE.Color(data.color).getHex();
  42554. var decay = data.decay;
  42555. var distance = data.distance;
  42556. var groundColor = new THREE.Color(data.groundColor).getHex();
  42557. var intensity = data.intensity;
  42558. var type = data.type;
  42559. var target = data.target;
  42560. var light = null;
  42561. switch (type.toLowerCase()) {
  42562. case 'ambient': {
  42563. return new THREE.AmbientLight(color, intensity);
  42564. }
  42565. case 'directional': {
  42566. light = new THREE.DirectionalLight(color, intensity);
  42567. this.defaultTarget = light.target;
  42568. if (target) {
  42569. if (target.hasLoaded) {
  42570. this.onSetTarget(target, light);
  42571. } else {
  42572. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  42573. }
  42574. }
  42575. return light;
  42576. }
  42577. case 'hemisphere': {
  42578. return new THREE.HemisphereLight(color, groundColor, intensity);
  42579. }
  42580. case 'point': {
  42581. return new THREE.PointLight(color, intensity, distance, decay);
  42582. }
  42583. case 'spot': {
  42584. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  42585. this.defaultTarget = light.target;
  42586. if (target) {
  42587. if (target.hasLoaded) {
  42588. this.onSetTarget(target, light);
  42589. } else {
  42590. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  42591. }
  42592. }
  42593. return light;
  42594. }
  42595. default: {
  42596. warn('%s is not a valid light type. ' +
  42597. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  42598. }
  42599. }
  42600. },
  42601. onSetTarget: function (targetEl, light) {
  42602. light.target = targetEl.object3D;
  42603. },
  42604. /**
  42605. * Remove light on remove (callback).
  42606. */
  42607. remove: function () {
  42608. var el = this.el;
  42609. el.removeObject3D('light');
  42610. if (el.getObject3D('cameraHelper')) {
  42611. el.removeObject3D('cameraHelper');
  42612. }
  42613. }
  42614. });
  42615. },{"../core/component":103,"../lib/three":151,"../utils":173,"../utils/bind":167,"../utils/debug":169}],63:[function(_dereq_,module,exports){
  42616. /* global THREE */
  42617. var registerComponent = _dereq_('../core/component').registerComponent;
  42618. module.exports.Component = registerComponent('line', {
  42619. schema: {
  42620. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  42621. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  42622. color: {type: 'color', default: '#74BEC1'},
  42623. opacity: {type: 'number', default: 1},
  42624. visible: {default: true}
  42625. },
  42626. multiple: true,
  42627. init: function () {
  42628. var data = this.data;
  42629. var geometry;
  42630. var material;
  42631. material = this.material = new THREE.LineBasicMaterial({
  42632. color: data.color,
  42633. opacity: data.opacity,
  42634. transparent: data.opacity < 1,
  42635. visible: data.visible
  42636. });
  42637. geometry = this.geometry = new THREE.BufferGeometry();
  42638. geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  42639. this.line = new THREE.Line(geometry, material);
  42640. this.el.setObject3D(this.attrName, this.line);
  42641. },
  42642. update: function (oldData) {
  42643. var data = this.data;
  42644. var geometry = this.geometry;
  42645. var geoNeedsUpdate = false;
  42646. var material = this.material;
  42647. var positionArray = geometry.attributes.position.array;
  42648. // Update geometry.
  42649. if (!isEqualVec3(data.start, oldData.start)) {
  42650. positionArray[0] = data.start.x;
  42651. positionArray[1] = data.start.y;
  42652. positionArray[2] = data.start.z;
  42653. geoNeedsUpdate = true;
  42654. }
  42655. if (!isEqualVec3(data.end, oldData.end)) {
  42656. positionArray[3] = data.end.x;
  42657. positionArray[4] = data.end.y;
  42658. positionArray[5] = data.end.z;
  42659. geoNeedsUpdate = true;
  42660. }
  42661. if (geoNeedsUpdate) {
  42662. geometry.attributes.position.needsUpdate = true;
  42663. geometry.computeBoundingSphere();
  42664. }
  42665. material.color.setStyle(data.color);
  42666. material.opacity = data.opacity;
  42667. material.transparent = data.opacity < 1;
  42668. material.visible = data.visible;
  42669. },
  42670. remove: function () {
  42671. this.el.removeObject3D('line', this.line);
  42672. }
  42673. });
  42674. function isEqualVec3 (a, b) {
  42675. if (!a || !b) { return false; }
  42676. return (a.x === b.x && a.y === b.y && a.z === b.z);
  42677. }
  42678. },{"../core/component":103}],64:[function(_dereq_,module,exports){
  42679. var registerComponent = _dereq_('../core/component').registerComponent;
  42680. var registerShader = _dereq_('../core/shader').registerShader;
  42681. var THREE = _dereq_('../lib/three');
  42682. /**
  42683. * Link component. Connect experiences and traverse between them in VR
  42684. *
  42685. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  42686. */
  42687. module.exports.Component = registerComponent('link', {
  42688. schema: {
  42689. backgroundColor: {default: 'red', type: 'color'},
  42690. borderColor: {default: 'white', type: 'color'},
  42691. highlighted: {default: false},
  42692. highlightedColor: {default: '#24CAFF', type: 'color'},
  42693. href: {default: ''},
  42694. image: {type: 'asset'},
  42695. on: {default: 'click'},
  42696. peekMode: {default: false},
  42697. title: {default: ''},
  42698. titleColor: {default: 'white', type: 'color'},
  42699. visualAspectEnabled: {default: true}
  42700. },
  42701. init: function () {
  42702. this.navigate = this.navigate.bind(this);
  42703. this.previousQuaternion = undefined;
  42704. this.quaternionClone = new THREE.Quaternion();
  42705. // Store hidden elements during peek mode so we can show them again later.
  42706. this.hiddenEls = [];
  42707. this.initVisualAspect();
  42708. },
  42709. update: function (oldData) {
  42710. var data = this.data;
  42711. var el = this.el;
  42712. var backgroundColor;
  42713. var strokeColor;
  42714. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  42715. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  42716. el.setAttribute('material', 'backgroundColor', backgroundColor);
  42717. el.setAttribute('material', 'strokeColor', strokeColor);
  42718. if (data.on !== oldData.on) { this.updateEventListener(); }
  42719. if (data.visualAspectEnabled && oldData.peekMode !== undefined &&
  42720. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  42721. if (!data.image || oldData.image === data.image) { return; }
  42722. el.setAttribute('material', 'pano',
  42723. typeof data.image === 'string' ? data.image : data.image.src);
  42724. },
  42725. /*
  42726. * Toggle all elements and full 360 preview of the linked page.
  42727. */
  42728. updatePeekMode: function () {
  42729. var el = this.el;
  42730. var sphereEl = this.sphereEl;
  42731. if (this.data.peekMode) {
  42732. this.hideAll();
  42733. el.getObject3D('mesh').visible = false;
  42734. sphereEl.setAttribute('visible', true);
  42735. } else {
  42736. this.showAll();
  42737. el.getObject3D('mesh').visible = true;
  42738. sphereEl.setAttribute('visible', false);
  42739. }
  42740. },
  42741. play: function () {
  42742. this.updateEventListener();
  42743. },
  42744. pause: function () {
  42745. this.removeEventListener();
  42746. },
  42747. updateEventListener: function () {
  42748. var el = this.el;
  42749. if (!el.isPlaying) { return; }
  42750. this.removeEventListener();
  42751. el.addEventListener(this.data.on, this.navigate);
  42752. },
  42753. removeEventListener: function () {
  42754. var on = this.data.on;
  42755. if (!on) { return; }
  42756. this.el.removeEventListener(on, this.navigate);
  42757. },
  42758. initVisualAspect: function () {
  42759. var el = this.el;
  42760. var semiSphereEl;
  42761. var sphereEl;
  42762. var textEl;
  42763. if (!this.data.visualAspectEnabled) { return; }
  42764. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  42765. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  42766. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  42767. // Set portal.
  42768. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  42769. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  42770. // Set text that displays the link title and URL.
  42771. textEl.setAttribute('text', {
  42772. color: this.data.titleColor,
  42773. align: 'center',
  42774. font: 'kelsonsans',
  42775. value: this.data.title || this.data.href,
  42776. width: 4
  42777. });
  42778. textEl.setAttribute('position', '0 1.5 0');
  42779. el.appendChild(textEl);
  42780. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  42781. semiSphereEl.setAttribute('geometry', {
  42782. primitive: 'sphere',
  42783. radius: 1.0,
  42784. phiStart: 0,
  42785. segmentsWidth: 64,
  42786. segmentsHeight: 64,
  42787. phiLength: 180,
  42788. thetaStart: 0,
  42789. thetaLength: 360
  42790. });
  42791. semiSphereEl.setAttribute('material', {
  42792. shader: 'portal',
  42793. borderEnabled: 0.0,
  42794. pano: this.data.image,
  42795. side: 'back'
  42796. });
  42797. semiSphereEl.setAttribute('rotation', '0 180 0');
  42798. semiSphereEl.setAttribute('position', '0 0 0');
  42799. semiSphereEl.setAttribute('visible', false);
  42800. el.appendChild(semiSphereEl);
  42801. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  42802. sphereEl.setAttribute('geometry', {
  42803. primitive: 'sphere',
  42804. radius: 10,
  42805. segmentsWidth: 64,
  42806. segmentsHeight: 64
  42807. });
  42808. sphereEl.setAttribute('material', {
  42809. shader: 'portal',
  42810. borderEnabled: 0.0,
  42811. pano: this.data.image,
  42812. side: 'back'
  42813. });
  42814. sphereEl.setAttribute('visible', false);
  42815. el.appendChild(sphereEl);
  42816. },
  42817. navigate: function () {
  42818. window.location = this.data.href;
  42819. },
  42820. /**
  42821. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  42822. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  42823. * from where user enters.
  42824. * 2. Place the url/title above or inside portal depending on distance to camera.
  42825. * 3. Face portal to camera when far away from user.
  42826. */
  42827. tick: (function () {
  42828. var cameraWorldPosition = new THREE.Vector3();
  42829. var elWorldPosition = new THREE.Vector3();
  42830. var quaternion = new THREE.Quaternion();
  42831. var scale = new THREE.Vector3();
  42832. return function () {
  42833. var el = this.el;
  42834. var object3D = el.object3D;
  42835. var camera = el.sceneEl.camera;
  42836. var cameraPortalOrientation;
  42837. var distance;
  42838. var textEl = this.textEl;
  42839. if (!this.data.visualAspectEnabled) { return; }
  42840. // Update matrices
  42841. object3D.updateMatrixWorld();
  42842. camera.parent.updateMatrixWorld();
  42843. camera.updateMatrixWorld();
  42844. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  42845. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  42846. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  42847. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  42848. if (distance > 20) {
  42849. // Store original orientation to be restored when the portal stops facing the camera.
  42850. if (!this.previousQuaternion) {
  42851. this.quaternionClone.copy(quaternion);
  42852. this.previousQuaternion = this.quaternionClone;
  42853. }
  42854. // If the portal is far away from the user, face portal to camera.
  42855. object3D.lookAt(cameraWorldPosition);
  42856. } else {
  42857. // When portal is close to the user/camera.
  42858. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  42859. // If user gets very close to portal, replace with holed sphere they can peek in.
  42860. if (distance < 0.5) {
  42861. // Configure text size and sphere orientation depending side user approaches portal.
  42862. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  42863. textEl.setAttribute('text', 'width', 1.5);
  42864. if (cameraPortalOrientation <= 0.0) {
  42865. textEl.setAttribute('position', '0 0 0.75');
  42866. textEl.setAttribute('rotation', '0 180 0');
  42867. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  42868. } else {
  42869. textEl.setAttribute('position', '0 0 -0.75');
  42870. textEl.setAttribute('rotation', '0 0 0');
  42871. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  42872. }
  42873. el.getObject3D('mesh').visible = false;
  42874. this.semiSphereEl.setAttribute('visible', true);
  42875. this.peekCameraPortalOrientation = cameraPortalOrientation;
  42876. } else {
  42877. // Calculate wich side the camera is approaching the camera (back / front).
  42878. // Adjust text orientation based on camera position.
  42879. if (cameraPortalOrientation <= 0.0) {
  42880. textEl.setAttribute('rotation', '0 180 0');
  42881. } else {
  42882. textEl.setAttribute('rotation', '0 0 0');
  42883. }
  42884. textEl.setAttribute('text', 'width', 5);
  42885. textEl.setAttribute('position', '0 1.5 0');
  42886. el.getObject3D('mesh').visible = true;
  42887. this.semiSphereEl.setAttribute('visible', false);
  42888. this.peekCameraPortalOrientation = undefined;
  42889. }
  42890. if (this.previousQuaternion) {
  42891. object3D.quaternion.copy(this.previousQuaternion);
  42892. this.previousQuaternion = undefined;
  42893. }
  42894. }
  42895. };
  42896. })(),
  42897. hideAll: function () {
  42898. var el = this.el;
  42899. var hiddenEls = this.hiddenEls;
  42900. var self = this;
  42901. if (hiddenEls.length > 0) { return; }
  42902. el.sceneEl.object3D.traverse(function (object) {
  42903. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  42904. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  42905. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  42906. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  42907. object.el === self.semiSphereEl) {
  42908. return;
  42909. }
  42910. object.el.setAttribute('visible', false);
  42911. hiddenEls.push(object.el);
  42912. });
  42913. },
  42914. showAll: function () {
  42915. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  42916. this.hiddenEls = [];
  42917. },
  42918. /**
  42919. * Calculate whether the camera faces the front or back face of the portal.
  42920. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  42921. */
  42922. calculateCameraPortalOrientation: (function () {
  42923. var mat4 = new THREE.Matrix4();
  42924. var cameraPosition = new THREE.Vector3();
  42925. var portalNormal = new THREE.Vector3(0, 0, 1);
  42926. var portalPosition = new THREE.Vector3(0, 0, 0);
  42927. return function () {
  42928. var el = this.el;
  42929. var camera = el.sceneEl.camera;
  42930. // Reset tmp variables.
  42931. cameraPosition.set(0, 0, 0);
  42932. portalNormal.set(0, 0, 1);
  42933. portalPosition.set(0, 0, 0);
  42934. // Apply portal orientation to the normal.
  42935. el.object3D.matrixWorld.extractRotation(mat4);
  42936. portalNormal.applyMatrix4(mat4);
  42937. // Calculate portal world position.
  42938. el.object3D.updateMatrixWorld();
  42939. el.object3D.localToWorld(portalPosition);
  42940. // Calculate camera world position.
  42941. camera.parent.parent.updateMatrixWorld();
  42942. camera.parent.updateMatrixWorld();
  42943. camera.updateMatrixWorld();
  42944. camera.localToWorld(cameraPosition);
  42945. // Calculate vector from portal to camera.
  42946. // (portal) -------> (camera)
  42947. cameraPosition.sub(portalPosition).normalize();
  42948. portalNormal.normalize();
  42949. // Side where camera approaches portal is given by sign of dot product of portal normal
  42950. // and portal to camera vectors.
  42951. return Math.sign(portalNormal.dot(cameraPosition));
  42952. };
  42953. })(),
  42954. remove: function () {
  42955. this.removeEventListener();
  42956. }
  42957. });
  42958. /* eslint-disable */
  42959. registerShader('portal', {
  42960. schema: {
  42961. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  42962. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  42963. pano: {type: 'map', is: 'uniform'},
  42964. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  42965. },
  42966. vertexShader: [
  42967. 'vec3 portalPosition;',
  42968. 'varying vec3 vWorldPosition;',
  42969. 'varying float vDistanceToCenter;',
  42970. 'varying float vDistance;',
  42971. 'void main() {',
  42972. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  42973. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  42974. 'vDistance = length(portalPosition - cameraPosition);',
  42975. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  42976. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  42977. '}'
  42978. ].join('\n'),
  42979. fragmentShader: [
  42980. '#define RECIPROCAL_PI2 0.15915494',
  42981. 'uniform sampler2D pano;',
  42982. 'uniform vec3 strokeColor;',
  42983. 'uniform vec3 backgroundColor;',
  42984. 'uniform float borderEnabled;',
  42985. 'varying float vDistanceToCenter;',
  42986. 'varying float vDistance;',
  42987. 'varying vec3 vWorldPosition;',
  42988. 'void main() {',
  42989. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  42990. 'vec2 sampleUV;',
  42991. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  42992. 'sampleUV.y = saturate(direction.y * 0.5 + 0.5);',
  42993. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  42994. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  42995. 'gl_FragColor = vec4(strokeColor, 1.0);',
  42996. '} else {',
  42997. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  42998. '}',
  42999. '}'
  43000. ].join('\n')
  43001. });
  43002. /* eslint-enable */
  43003. },{"../core/component":103,"../core/shader":112,"../lib/three":151}],65:[function(_dereq_,module,exports){
  43004. var registerComponent = _dereq_('../core/component').registerComponent;
  43005. var THREE = _dereq_('../lib/three');
  43006. var utils = _dereq_('../utils/');
  43007. var bind = utils.bind;
  43008. var PolyfillControls = _dereq_('../utils').device.PolyfillControls;
  43009. // To avoid recalculation at every mouse movement tick
  43010. var GRABBING_CLASS = 'a-grabbing';
  43011. var PI_2 = Math.PI / 2;
  43012. var checkHasPositionalTracking = utils.device.checkHasPositionalTracking;
  43013. /**
  43014. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  43015. */
  43016. module.exports.Component = registerComponent('look-controls', {
  43017. dependencies: ['position', 'rotation'],
  43018. schema: {
  43019. enabled: {default: true},
  43020. hmdEnabled: {default: true},
  43021. pointerLockEnabled: {default: false},
  43022. reverseMouseDrag: {default: false},
  43023. touchEnabled: {default: true}
  43024. },
  43025. init: function () {
  43026. this.previousHMDPosition = new THREE.Vector3();
  43027. this.hmdQuaternion = new THREE.Quaternion();
  43028. this.hmdEuler = new THREE.Euler();
  43029. this.position = new THREE.Vector3();
  43030. // To save / restore camera pose
  43031. this.savedRotation = new THREE.Vector3();
  43032. this.savedPosition = new THREE.Vector3();
  43033. this.polyfillObject = new THREE.Object3D();
  43034. this.polyfillControls = new PolyfillControls(this.polyfillObject);
  43035. this.rotation = {};
  43036. this.deltaRotation = {};
  43037. this.savedPose = null;
  43038. this.pointerLocked = false;
  43039. this.setupMouseControls();
  43040. this.bindMethods();
  43041. this.savedPose = {
  43042. position: new THREE.Vector3(),
  43043. rotation: new THREE.Euler()
  43044. };
  43045. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  43046. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  43047. },
  43048. update: function (oldData) {
  43049. var data = this.data;
  43050. // Disable grab cursor classes if no longer enabled.
  43051. if (data.enabled !== oldData.enabled) {
  43052. this.updateGrabCursor(data.enabled);
  43053. }
  43054. // Reset pitch and yaw if disabling HMD.
  43055. if (oldData && !data.hmdEnabled && !oldData.hmdEnabled) {
  43056. this.pitchObject.rotation.set(0, 0, 0);
  43057. this.yawObject.rotation.set(0, 0, 0);
  43058. }
  43059. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  43060. this.removeEventListeners();
  43061. this.addEventListeners();
  43062. if (this.pointerLocked) { document.exitPointerLock(); }
  43063. }
  43064. },
  43065. tick: function (t) {
  43066. var data = this.data;
  43067. if (!data.enabled) { return; }
  43068. this.updateOrientation();
  43069. },
  43070. play: function () {
  43071. this.addEventListeners();
  43072. },
  43073. pause: function () {
  43074. this.removeEventListeners();
  43075. },
  43076. remove: function () {
  43077. this.removeEventListeners();
  43078. },
  43079. bindMethods: function () {
  43080. this.onMouseDown = bind(this.onMouseDown, this);
  43081. this.onMouseMove = bind(this.onMouseMove, this);
  43082. this.onMouseUp = bind(this.onMouseUp, this);
  43083. this.onTouchStart = bind(this.onTouchStart, this);
  43084. this.onTouchMove = bind(this.onTouchMove, this);
  43085. this.onTouchEnd = bind(this.onTouchEnd, this);
  43086. this.onEnterVR = bind(this.onEnterVR, this);
  43087. this.onExitVR = bind(this.onExitVR, this);
  43088. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  43089. this.onPointerLockError = bind(this.onPointerLockError, this);
  43090. },
  43091. /**
  43092. * Set up states and Object3Ds needed to store rotation data.
  43093. */
  43094. setupMouseControls: function () {
  43095. this.mouseDown = false;
  43096. this.pitchObject = new THREE.Object3D();
  43097. this.yawObject = new THREE.Object3D();
  43098. this.yawObject.position.y = 10;
  43099. this.yawObject.add(this.pitchObject);
  43100. },
  43101. /**
  43102. * Add mouse and touch event listeners to canvas.
  43103. */
  43104. addEventListeners: function () {
  43105. var sceneEl = this.el.sceneEl;
  43106. var canvasEl = sceneEl.canvas;
  43107. // Wait for canvas to load.
  43108. if (!canvasEl) {
  43109. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  43110. return;
  43111. }
  43112. // Mouse events.
  43113. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  43114. window.addEventListener('mousemove', this.onMouseMove, false);
  43115. window.addEventListener('mouseup', this.onMouseUp, false);
  43116. // Touch events.
  43117. canvasEl.addEventListener('touchstart', this.onTouchStart);
  43118. window.addEventListener('touchmove', this.onTouchMove);
  43119. window.addEventListener('touchend', this.onTouchEnd);
  43120. // sceneEl events.
  43121. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  43122. sceneEl.addEventListener('exit-vr', this.onExitVR);
  43123. // Pointer Lock events.
  43124. if (this.data.pointerLockEnabled) {
  43125. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  43126. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  43127. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  43128. }
  43129. },
  43130. /**
  43131. * Remove mouse and touch event listeners from canvas.
  43132. */
  43133. removeEventListeners: function () {
  43134. var sceneEl = this.el.sceneEl;
  43135. var canvasEl = sceneEl && sceneEl.canvas;
  43136. if (!canvasEl) { return; }
  43137. // Mouse events.
  43138. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  43139. window.removeEventListener('mousemove', this.onMouseMove);
  43140. window.removeEventListener('mouseup', this.onMouseUp);
  43141. // Touch events.
  43142. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  43143. window.removeEventListener('touchmove', this.onTouchMove);
  43144. window.removeEventListener('touchend', this.onTouchEnd);
  43145. // sceneEl events.
  43146. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  43147. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  43148. // Pointer Lock events.
  43149. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  43150. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  43151. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  43152. },
  43153. /**
  43154. * Update orientation for mobile, mouse drag, and headset.
  43155. * Mouse-drag only enabled if HMD is not active.
  43156. */
  43157. updateOrientation: function () {
  43158. var el = this.el;
  43159. var hmdEuler = this.hmdEuler;
  43160. var pitchObject = this.pitchObject;
  43161. var yawObject = this.yawObject;
  43162. var sceneEl = this.el.sceneEl;
  43163. // In VR mode, THREE is in charge of updating the camera rotation.
  43164. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) { return; }
  43165. // Calculate polyfilled HMD quaternion.
  43166. this.polyfillControls.update();
  43167. hmdEuler.setFromQuaternion(this.polyfillObject.quaternion, 'YXZ');
  43168. // On mobile, do camera rotation with touch events and sensors.
  43169. el.object3D.rotation.x = hmdEuler.x + pitchObject.rotation.x;
  43170. el.object3D.rotation.y = hmdEuler.y + yawObject.rotation.y;
  43171. el.object3D.rotation.z = 0;
  43172. },
  43173. /**
  43174. * Translate mouse drag into rotation.
  43175. *
  43176. * Dragging up and down rotates the camera around the X-axis (yaw).
  43177. * Dragging left and right rotates the camera around the Y-axis (pitch).
  43178. */
  43179. onMouseMove: function (event) {
  43180. var direction;
  43181. var movementX;
  43182. var movementY;
  43183. var pitchObject = this.pitchObject;
  43184. var previousMouseEvent = this.previousMouseEvent;
  43185. var yawObject = this.yawObject;
  43186. // Not dragging or not enabled.
  43187. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  43188. // Calculate delta.
  43189. if (this.pointerLocked) {
  43190. movementX = event.movementX || event.mozMovementX || 0;
  43191. movementY = event.movementY || event.mozMovementY || 0;
  43192. } else {
  43193. movementX = event.screenX - previousMouseEvent.screenX;
  43194. movementY = event.screenY - previousMouseEvent.screenY;
  43195. }
  43196. this.previousMouseEvent = event;
  43197. // Calculate rotation.
  43198. direction = this.data.reverseMouseDrag ? 1 : -1;
  43199. yawObject.rotation.y += movementX * 0.002 * direction;
  43200. pitchObject.rotation.x += movementY * 0.002 * direction;
  43201. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  43202. },
  43203. /**
  43204. * Register mouse down to detect mouse drag.
  43205. */
  43206. onMouseDown: function (evt) {
  43207. if (!this.data.enabled) { return; }
  43208. // Handle only primary button.
  43209. if (evt.button !== 0) { return; }
  43210. var sceneEl = this.el.sceneEl;
  43211. var canvasEl = sceneEl && sceneEl.canvas;
  43212. this.mouseDown = true;
  43213. this.previousMouseEvent = evt;
  43214. document.body.classList.add(GRABBING_CLASS);
  43215. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  43216. if (canvasEl.requestPointerLock) {
  43217. canvasEl.requestPointerLock();
  43218. } else if (canvasEl.mozRequestPointerLock) {
  43219. canvasEl.mozRequestPointerLock();
  43220. }
  43221. }
  43222. },
  43223. /**
  43224. * Register mouse up to detect release of mouse drag.
  43225. */
  43226. onMouseUp: function () {
  43227. this.mouseDown = false;
  43228. document.body.classList.remove(GRABBING_CLASS);
  43229. },
  43230. /**
  43231. * Register touch down to detect touch drag.
  43232. */
  43233. onTouchStart: function (evt) {
  43234. if (evt.touches.length !== 1 || !this.data.touchEnabled) { return; }
  43235. this.touchStart = {
  43236. x: evt.touches[0].pageX,
  43237. y: evt.touches[0].pageY
  43238. };
  43239. this.touchStarted = true;
  43240. },
  43241. /**
  43242. * Translate touch move to Y-axis rotation.
  43243. */
  43244. onTouchMove: function (evt) {
  43245. var canvas = this.el.sceneEl.canvas;
  43246. var deltaY;
  43247. var yawObject = this.yawObject;
  43248. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  43249. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  43250. // Limit touch orientaion to to yaw (y axis).
  43251. yawObject.rotation.y -= deltaY * 0.5;
  43252. this.touchStart = {
  43253. x: evt.touches[0].pageX,
  43254. y: evt.touches[0].pageY
  43255. };
  43256. },
  43257. /**
  43258. * Register touch end to detect release of touch drag.
  43259. */
  43260. onTouchEnd: function () {
  43261. this.touchStarted = false;
  43262. },
  43263. /**
  43264. * Save pose.
  43265. */
  43266. onEnterVR: function () {
  43267. this.saveCameraPose();
  43268. },
  43269. /**
  43270. * Restore the pose.
  43271. */
  43272. onExitVR: function () {
  43273. this.restoreCameraPose();
  43274. this.previousHMDPosition.set(0, 0, 0);
  43275. },
  43276. /**
  43277. * Update Pointer Lock state.
  43278. */
  43279. onPointerLockChange: function () {
  43280. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  43281. },
  43282. /**
  43283. * Recover from Pointer Lock error.
  43284. */
  43285. onPointerLockError: function () {
  43286. this.pointerLocked = false;
  43287. },
  43288. /**
  43289. * Toggle the feature of showing/hiding the grab cursor.
  43290. */
  43291. updateGrabCursor: function (enabled) {
  43292. var sceneEl = this.el.sceneEl;
  43293. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  43294. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  43295. if (!sceneEl.canvas) {
  43296. if (enabled) {
  43297. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  43298. } else {
  43299. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  43300. }
  43301. return;
  43302. }
  43303. if (enabled) {
  43304. enableGrabCursor();
  43305. return;
  43306. }
  43307. disableGrabCursor();
  43308. },
  43309. /**
  43310. * Save camera pose before entering VR to restore later if exiting.
  43311. */
  43312. saveCameraPose: function () {
  43313. var el = this.el;
  43314. var hasPositionalTracking = this.hasPositionalTracking !== undefined
  43315. ? this.hasPositionalTracking
  43316. : checkHasPositionalTracking();
  43317. if (this.hasSavedPose || !hasPositionalTracking) { return; }
  43318. this.savedPose.position.copy(el.object3D.position);
  43319. this.savedPose.rotation.copy(el.object3D.rotation);
  43320. this.hasSavedPose = true;
  43321. },
  43322. /**
  43323. * Reset camera pose to before entering VR.
  43324. */
  43325. restoreCameraPose: function () {
  43326. var el = this.el;
  43327. var savedPose = this.savedPose;
  43328. var hasPositionalTracking = this.hasPositionalTracking !== undefined
  43329. ? this.hasPositionalTracking
  43330. : checkHasPositionalTracking();
  43331. if (!this.hasSavedPose || !hasPositionalTracking) { return; }
  43332. // Reset camera orientation.
  43333. el.object3D.position.copy(savedPose.position);
  43334. el.object3D.rotation.copy(savedPose.rotation);
  43335. this.hasSavedPose = false;
  43336. }
  43337. });
  43338. },{"../core/component":103,"../lib/three":151,"../utils":173,"../utils/":173}],66:[function(_dereq_,module,exports){
  43339. /* global Promise */
  43340. var utils = _dereq_('../utils/');
  43341. var component = _dereq_('../core/component');
  43342. var THREE = _dereq_('../lib/three');
  43343. var shader = _dereq_('../core/shader');
  43344. var error = utils.debug('components:material:error');
  43345. var registerComponent = component.registerComponent;
  43346. var shaders = shader.shaders;
  43347. var shaderNames = shader.shaderNames;
  43348. /**
  43349. * Material component.
  43350. *
  43351. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  43352. * three.js's implementation of PBR. Another standard shading model is `flat` which
  43353. * uses MeshBasicMaterial.
  43354. */
  43355. module.exports.Component = registerComponent('material', {
  43356. schema: {
  43357. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  43358. depthTest: {default: true},
  43359. depthWrite: {default: true},
  43360. flatShading: {default: false},
  43361. npot: {default: false},
  43362. offset: {type: 'vec2', default: {x: 0, y: 0}},
  43363. opacity: {default: 1.0, min: 0.0, max: 1.0},
  43364. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  43365. shader: {default: 'standard', oneOf: shaderNames},
  43366. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  43367. transparent: {default: false},
  43368. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  43369. visible: {default: true},
  43370. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']}
  43371. },
  43372. init: function () {
  43373. this.material = null;
  43374. },
  43375. /**
  43376. * Update or create material.
  43377. *
  43378. * @param {object|null} oldData
  43379. */
  43380. update: function (oldData) {
  43381. var data = this.data;
  43382. if (!this.shader || data.shader !== oldData.shader) {
  43383. this.updateShader(data.shader);
  43384. }
  43385. this.shader.update(this.data);
  43386. this.updateMaterial(oldData);
  43387. },
  43388. updateSchema: function (data) {
  43389. var newShader = data.shader;
  43390. var currentShader = this.data && this.data.shader;
  43391. var shader = newShader || currentShader;
  43392. var schema = shaders[shader] && shaders[shader].schema;
  43393. if (!schema) { error('Unknown shader schema ' + shader); }
  43394. if (currentShader && newShader === currentShader) { return; }
  43395. this.extendSchema(schema);
  43396. this.updateBehavior();
  43397. },
  43398. updateBehavior: function () {
  43399. var schema = this.schema;
  43400. var self = this;
  43401. var sceneEl = this.el.sceneEl;
  43402. var tickProperties = {};
  43403. var tick = function (time, delta) {
  43404. Object.keys(tickProperties).forEach(function update (key) {
  43405. tickProperties[key] = time;
  43406. });
  43407. self.shader.update(tickProperties);
  43408. };
  43409. this.tick = undefined;
  43410. Object.keys(schema).forEach(function (key) {
  43411. if (schema[key].type === 'time') {
  43412. self.tick = tick;
  43413. tickProperties[key] = true;
  43414. }
  43415. });
  43416. if (!sceneEl) { return; }
  43417. if (!this.tick) {
  43418. sceneEl.removeBehavior(this);
  43419. } else {
  43420. sceneEl.addBehavior(this);
  43421. }
  43422. },
  43423. updateShader: function (shaderName) {
  43424. var data = this.data;
  43425. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  43426. var shaderInstance;
  43427. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  43428. // Get material from A-Frame shader.
  43429. shaderInstance = this.shader = new Shader();
  43430. shaderInstance.el = this.el;
  43431. shaderInstance.init(data);
  43432. this.setMaterial(shaderInstance.material);
  43433. this.updateSchema(data);
  43434. },
  43435. /**
  43436. * Set and update base material properties.
  43437. * Set `needsUpdate` when needed.
  43438. */
  43439. updateMaterial: function (oldData) {
  43440. var data = this.data;
  43441. var material = this.material;
  43442. // Base material properties.
  43443. material.alphaTest = data.alphaTest;
  43444. material.depthTest = data.depthTest !== false;
  43445. material.depthWrite = data.depthWrite !== false;
  43446. material.opacity = data.opacity;
  43447. material.flatShading = data.flatShading;
  43448. material.side = parseSide(data.side);
  43449. material.transparent = data.transparent !== false || data.opacity < 1.0;
  43450. material.vertexColors = parseVertexColors(data.vertexColors);
  43451. material.visible = data.visible;
  43452. material.blending = parseBlending(data.blending);
  43453. // Check if material needs update.
  43454. if (Object.keys(oldData).length &&
  43455. (oldData.alphaTest !== data.alphaTest ||
  43456. oldData.side !== data.side ||
  43457. oldData.vertexColors !== data.vertexColors)) {
  43458. material.needsUpdate = true;
  43459. }
  43460. },
  43461. /**
  43462. * Remove material on remove (callback).
  43463. * Dispose of it from memory and unsubscribe from scene updates.
  43464. */
  43465. remove: function () {
  43466. var defaultMaterial = new THREE.MeshBasicMaterial();
  43467. var material = this.material;
  43468. var object3D = this.el.getObject3D('mesh');
  43469. if (object3D) { object3D.material = defaultMaterial; }
  43470. disposeMaterial(material, this.system);
  43471. },
  43472. /**
  43473. * (Re)create new material. Has side-effects of setting `this.material` and updating
  43474. * material registration in scene.
  43475. *
  43476. * @param {object} data - Material component data.
  43477. * @param {object} type - Material type to create.
  43478. * @returns {object} Material.
  43479. */
  43480. setMaterial: function (material) {
  43481. var el = this.el;
  43482. var mesh;
  43483. var system = this.system;
  43484. if (this.material) { disposeMaterial(this.material, system); }
  43485. this.material = material;
  43486. system.registerMaterial(material);
  43487. // Set on mesh. If mesh does not exist, wait for it.
  43488. mesh = el.getObject3D('mesh');
  43489. if (mesh) {
  43490. mesh.material = material;
  43491. } else {
  43492. el.addEventListener('object3dset', function waitForMesh (evt) {
  43493. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  43494. el.getObject3D('mesh').material = material;
  43495. el.removeEventListener('object3dset', waitForMesh);
  43496. });
  43497. }
  43498. }
  43499. });
  43500. /**
  43501. * Return a three.js constant determining which material face sides to render
  43502. * based on the side parameter (passed as a component property).
  43503. *
  43504. * @param {string} [side=front] - `front`, `back`, or `double`.
  43505. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  43506. */
  43507. function parseSide (side) {
  43508. switch (side) {
  43509. case 'back': {
  43510. return THREE.BackSide;
  43511. }
  43512. case 'double': {
  43513. return THREE.DoubleSide;
  43514. }
  43515. default: {
  43516. // Including case `front`.
  43517. return THREE.FrontSide;
  43518. }
  43519. }
  43520. }
  43521. /**
  43522. * Return a three.js constant determining vertex coloring.
  43523. */
  43524. function parseVertexColors (coloring) {
  43525. switch (coloring) {
  43526. case 'face': {
  43527. return THREE.FaceColors;
  43528. }
  43529. case 'vertex': {
  43530. return THREE.VertexColors;
  43531. }
  43532. default: {
  43533. return THREE.NoColors;
  43534. }
  43535. }
  43536. }
  43537. /**
  43538. * Return a three.js constant determining blending
  43539. *
  43540. * @param {string} [blending=normal]
  43541. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  43542. * @returns {number}
  43543. */
  43544. function parseBlending (blending) {
  43545. switch (blending) {
  43546. case 'none': {
  43547. return THREE.NoBlending;
  43548. }
  43549. case 'additive': {
  43550. return THREE.AdditiveBlending;
  43551. }
  43552. case 'subtractive': {
  43553. return THREE.SubtractiveBlending;
  43554. }
  43555. case 'multiply': {
  43556. return THREE.MultiplyBlending;
  43557. }
  43558. default: {
  43559. return THREE.NormalBlending;
  43560. }
  43561. }
  43562. }
  43563. /**
  43564. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  43565. */
  43566. function disposeMaterial (material, system) {
  43567. material.dispose();
  43568. system.unregisterMaterial(material);
  43569. }
  43570. },{"../core/component":103,"../core/shader":112,"../lib/three":151,"../utils/":173}],67:[function(_dereq_,module,exports){
  43571. var debug = _dereq_('../utils/debug');
  43572. var registerComponent = _dereq_('../core/component').registerComponent;
  43573. var THREE = _dereq_('../lib/three');
  43574. var warn = debug('components:obj-model:warn');
  43575. module.exports.Component = registerComponent('obj-model', {
  43576. schema: {
  43577. mtl: {type: 'model'},
  43578. obj: {type: 'model'}
  43579. },
  43580. init: function () {
  43581. this.model = null;
  43582. this.objLoader = new THREE.OBJLoader();
  43583. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  43584. // Allow cross-origin images to be loaded.
  43585. this.mtlLoader.crossOrigin = '';
  43586. },
  43587. update: function () {
  43588. var data = this.data;
  43589. if (!data.obj) { return; }
  43590. this.remove();
  43591. this.loadObj(data.obj, data.mtl);
  43592. },
  43593. remove: function () {
  43594. if (!this.model) { return; }
  43595. this.el.removeObject3D('mesh');
  43596. },
  43597. loadObj: function (objUrl, mtlUrl) {
  43598. var self = this;
  43599. var el = this.el;
  43600. var mtlLoader = this.mtlLoader;
  43601. var objLoader = this.objLoader;
  43602. if (mtlUrl) {
  43603. // .OBJ with an .MTL.
  43604. if (el.hasAttribute('material')) {
  43605. warn('Material component properties are ignored when a .MTL is provided');
  43606. }
  43607. mtlLoader.setTexturePath(mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1));
  43608. mtlLoader.load(mtlUrl, function (materials) {
  43609. materials.preload();
  43610. objLoader.setMaterials(materials);
  43611. objLoader.load(objUrl, function (objModel) {
  43612. self.model = objModel;
  43613. el.setObject3D('mesh', objModel);
  43614. el.emit('model-loaded', {format: 'obj', model: objModel});
  43615. });
  43616. });
  43617. return;
  43618. }
  43619. // .OBJ only.
  43620. objLoader.load(objUrl, function loadObjOnly (objModel) {
  43621. // Apply material.
  43622. var material = el.components.material;
  43623. if (material) {
  43624. objModel.traverse(function (child) {
  43625. if (child instanceof THREE.Mesh) {
  43626. child.material = material.material;
  43627. }
  43628. });
  43629. }
  43630. self.model = objModel;
  43631. el.setObject3D('mesh', objModel);
  43632. el.emit('model-loaded', {format: 'obj', model: objModel});
  43633. });
  43634. }
  43635. });
  43636. },{"../core/component":103,"../lib/three":151,"../utils/debug":169}],68:[function(_dereq_,module,exports){
  43637. var registerComponent = _dereq_('../core/component').registerComponent;
  43638. var bind = _dereq_('../utils/bind');
  43639. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  43640. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  43641. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  43642. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  43643. var GAMEPAD_ID_PREFIX = 'Oculus Go';
  43644. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  43645. /**
  43646. * Oculus Go controls.
  43647. * Interface with Oculus Go controller and map Gamepad events to
  43648. * controller buttons: trackpad, trigger
  43649. * Load a controller model and highlight the pressed buttons.
  43650. */
  43651. module.exports.Component = registerComponent('oculus-go-controls', {
  43652. schema: {
  43653. hand: {default: ''}, // This informs the degenerate arm model.
  43654. buttonColor: {type: 'color', default: '#FFFFFF'},
  43655. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  43656. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  43657. model: {default: true},
  43658. rotationOffset: {default: 0},
  43659. armModel: {default: true}
  43660. },
  43661. /**
  43662. * Button IDs:
  43663. * 0 - trackpad
  43664. * 1 - trigger
  43665. */
  43666. mapping: {
  43667. axes: {trackpad: [0, 1]},
  43668. buttons: ['trackpad', 'trigger']
  43669. },
  43670. bindMethods: function () {
  43671. this.onModelLoaded = bind(this.onModelLoaded, this);
  43672. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43673. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43674. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  43675. this.onAxisMoved = bind(this.onAxisMoved, this);
  43676. },
  43677. init: function () {
  43678. var self = this;
  43679. this.animationActive = 'pointing';
  43680. this.onButtonChanged = bind(this.onButtonChanged, this);
  43681. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  43682. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  43683. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  43684. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  43685. this.onAxisMoved = bind(this.onAxisMoved, this);
  43686. this.controllerPresent = false;
  43687. this.lastControllerCheck = 0;
  43688. this.bindMethods();
  43689. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  43690. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  43691. },
  43692. addEventListeners: function () {
  43693. var el = this.el;
  43694. el.addEventListener('buttonchanged', this.onButtonChanged);
  43695. el.addEventListener('buttondown', this.onButtonDown);
  43696. el.addEventListener('buttonup', this.onButtonUp);
  43697. el.addEventListener('touchstart', this.onButtonTouchStart);
  43698. el.addEventListener('touchend', this.onButtonTouchEnd);
  43699. el.addEventListener('model-loaded', this.onModelLoaded);
  43700. el.addEventListener('axismove', this.onAxisMoved);
  43701. this.controllerEventsActive = true;
  43702. this.addControllersUpdateListener();
  43703. },
  43704. removeEventListeners: function () {
  43705. var el = this.el;
  43706. el.removeEventListener('buttonchanged', this.onButtonChanged);
  43707. el.removeEventListener('buttondown', this.onButtonDown);
  43708. el.removeEventListener('buttonup', this.onButtonUp);
  43709. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43710. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43711. el.removeEventListener('model-loaded', this.onModelLoaded);
  43712. el.removeEventListener('axismove', this.onAxisMoved);
  43713. this.controllerEventsActive = false;
  43714. this.removeControllersUpdateListener();
  43715. },
  43716. checkIfControllerPresent: function () {
  43717. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  43718. this.data.hand ? {hand: this.data.hand} : {});
  43719. },
  43720. play: function () {
  43721. this.checkIfControllerPresent();
  43722. this.addControllersUpdateListener();
  43723. },
  43724. pause: function () {
  43725. this.removeEventListeners();
  43726. this.removeControllersUpdateListener();
  43727. },
  43728. injectTrackedControls: function () {
  43729. var el = this.el;
  43730. var data = this.data;
  43731. el.setAttribute('tracked-controls', {
  43732. armModel: data.armModel,
  43733. idPrefix: GAMEPAD_ID_PREFIX,
  43734. rotationOffset: data.rotationOffset
  43735. });
  43736. if (!this.data.model) { return; }
  43737. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  43738. },
  43739. addControllersUpdateListener: function () {
  43740. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  43741. },
  43742. removeControllersUpdateListener: function () {
  43743. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  43744. },
  43745. onControllersUpdate: function () {
  43746. this.checkIfControllerPresent();
  43747. },
  43748. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  43749. onModelLoaded: function (evt) {
  43750. var controllerObject3D = evt.detail.model;
  43751. var buttonMeshes;
  43752. if (!this.data.model) { return; }
  43753. buttonMeshes = this.buttonMeshes = {};
  43754. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  43755. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  43756. },
  43757. onButtonChanged: function (evt) {
  43758. var button = this.mapping.buttons[evt.detail.id];
  43759. if (!button) return;
  43760. // Pass along changed event with button state, using button mapping for convenience.
  43761. this.el.emit(button + 'changed', evt.detail.state);
  43762. },
  43763. onAxisMoved: function (evt) {
  43764. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  43765. },
  43766. updateModel: function (buttonName, evtName) {
  43767. if (!this.data.model) { return; }
  43768. this.updateButtonModel(buttonName, evtName);
  43769. },
  43770. updateButtonModel: function (buttonName, state) {
  43771. var buttonMeshes = this.buttonMeshes;
  43772. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  43773. var color;
  43774. switch (state) {
  43775. case 'down':
  43776. color = this.data.buttonHighlightColor;
  43777. break;
  43778. case 'touchstart':
  43779. color = this.data.buttonTouchedColor;
  43780. break;
  43781. default:
  43782. color = this.data.buttonColor;
  43783. }
  43784. buttonMeshes[buttonName].material.color.set(color);
  43785. }
  43786. });
  43787. },{"../core/component":103,"../utils/bind":167,"../utils/tracked-controls":179}],69:[function(_dereq_,module,exports){
  43788. var bind = _dereq_('../utils/bind');
  43789. var registerComponent = _dereq_('../core/component').registerComponent;
  43790. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  43791. var THREE = _dereq_('../lib/three');
  43792. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  43793. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  43794. var TOUCH_CONTROLLER_MODEL_URL = {
  43795. left: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  43796. right: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf'
  43797. };
  43798. var GAMEPAD_ID_PREFIX = 'Oculus Touch';
  43799. var DEFAULT_MODEL_PIVOT_OFFSET = new THREE.Vector3(0, 0, -0.053);
  43800. var RAY_ORIGIN = {
  43801. left: {origin: {x: 0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  43802. right: {origin: {x: -0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}}
  43803. };
  43804. /**
  43805. * Oculus Touch controls.
  43806. * Interface with Oculus Touch controllers and map Gamepad events to
  43807. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  43808. * Load a controller model and highlight the pressed buttons.
  43809. */
  43810. module.exports.Component = registerComponent('oculus-touch-controls', {
  43811. schema: {
  43812. hand: {default: 'left'},
  43813. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  43814. buttonTouchColor: {type: 'color', default: '#8AB'},
  43815. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  43816. model: {default: true},
  43817. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  43818. },
  43819. /**
  43820. * Button IDs:
  43821. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  43822. * 1 - trigger (with analog value, which goes up to 1)
  43823. * 2 - grip (with analog value, which goes up to 1)
  43824. * 3 - X (left) or A (right)
  43825. * 4 - Y (left) or B (right)
  43826. * 5 - surface (touch only)
  43827. */
  43828. mapping: {
  43829. left: {
  43830. axes: {thumbstick: [0, 1]},
  43831. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  43832. },
  43833. right: {
  43834. axes: {thumbstick: [0, 1]},
  43835. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  43836. }
  43837. },
  43838. bindMethods: function () {
  43839. this.onModelLoaded = bind(this.onModelLoaded, this);
  43840. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43841. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43842. this.onAxisMoved = bind(this.onAxisMoved, this);
  43843. },
  43844. init: function () {
  43845. var self = this;
  43846. this.onButtonChanged = bind(this.onButtonChanged, this);
  43847. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  43848. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  43849. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  43850. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  43851. this.controllerPresent = false;
  43852. this.lastControllerCheck = 0;
  43853. this.previousButtonValues = {};
  43854. this.bindMethods();
  43855. // Allow mock.
  43856. this.emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  43857. this.checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  43858. },
  43859. addEventListeners: function () {
  43860. var el = this.el;
  43861. el.addEventListener('buttonchanged', this.onButtonChanged);
  43862. el.addEventListener('buttondown', this.onButtonDown);
  43863. el.addEventListener('buttonup', this.onButtonUp);
  43864. el.addEventListener('touchstart', this.onButtonTouchStart);
  43865. el.addEventListener('touchend', this.onButtonTouchEnd);
  43866. el.addEventListener('axismove', this.onAxisMoved);
  43867. el.addEventListener('model-loaded', this.onModelLoaded);
  43868. this.controllerEventsActive = true;
  43869. },
  43870. removeEventListeners: function () {
  43871. var el = this.el;
  43872. el.removeEventListener('buttonchanged', this.onButtonChanged);
  43873. el.removeEventListener('buttondown', this.onButtonDown);
  43874. el.removeEventListener('buttonup', this.onButtonUp);
  43875. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43876. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43877. el.removeEventListener('axismove', this.onAxisMoved);
  43878. el.removeEventListener('model-loaded', this.onModelLoaded);
  43879. this.controllerEventsActive = false;
  43880. },
  43881. checkIfControllerPresent: function () {
  43882. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  43883. hand: this.data.hand
  43884. });
  43885. },
  43886. play: function () {
  43887. this.checkIfControllerPresent();
  43888. this.addControllersUpdateListener();
  43889. },
  43890. pause: function () {
  43891. this.removeEventListeners();
  43892. this.removeControllersUpdateListener();
  43893. },
  43894. loadModel: function () {
  43895. var data = this.data;
  43896. if (!data.model) { return; }
  43897. this.el.setAttribute('gltf-model', 'url(' + TOUCH_CONTROLLER_MODEL_URL[data.hand] + ')');
  43898. },
  43899. injectTrackedControls: function () {
  43900. var data = this.data;
  43901. this.el.setAttribute('tracked-controls', {
  43902. id: data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)',
  43903. controller: 0,
  43904. orientationOffset: data.orientationOffset
  43905. });
  43906. this.loadModel();
  43907. },
  43908. addControllersUpdateListener: function () {
  43909. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  43910. },
  43911. removeControllersUpdateListener: function () {
  43912. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  43913. },
  43914. onControllersUpdate: function () {
  43915. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  43916. this.checkIfControllerPresent();
  43917. },
  43918. onButtonChanged: function (evt) {
  43919. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  43920. var buttonMeshes = this.buttonMeshes;
  43921. var analogValue;
  43922. if (!button) { return; }
  43923. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  43924. // Update trigger and/or grip meshes, if any.
  43925. if (buttonMeshes) {
  43926. if (button === 'trigger' && buttonMeshes.trigger) {
  43927. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 24);
  43928. }
  43929. if (button === 'grip' && buttonMeshes.grip) {
  43930. buttonMeshes.grip.rotation.y = (this.data.hand === 'left' ? -1 : 1) * analogValue * (Math.PI / 60);
  43931. }
  43932. }
  43933. // Pass along changed event with button state, using the buttom mapping for convenience.
  43934. this.el.emit(button + 'changed', evt.detail.state);
  43935. },
  43936. onModelLoaded: function (evt) {
  43937. var controllerObject3D = evt.detail.model;
  43938. var buttonMeshes;
  43939. if (!this.data.model) { return; }
  43940. var leftHand = this.data.hand === 'left';
  43941. buttonMeshes = this.buttonMeshes = {};
  43942. buttonMeshes.grip = controllerObject3D.getObjectByName(leftHand ? 'buttonHand_oculus-touch-controller-left.004' : 'buttonHand_oculus-touch-controller-right.005');
  43943. buttonMeshes.thumbstick = controllerObject3D.getObjectByName(leftHand ? 'stick_oculus-touch-controller-left.007' : 'stick_oculus-touch-controller-right.004');
  43944. buttonMeshes.trigger = controllerObject3D.getObjectByName(leftHand ? 'buttonTrigger_oculus-touch-controller-left.005' : 'buttonTrigger_oculus-touch-controller-right.006');
  43945. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX_oculus-touch-controller-left.002');
  43946. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA_oculus-touch-controller-right.002');
  43947. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY_oculus-touch-controller-left.001');
  43948. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB_oculus-touch-controller-right.003');
  43949. // Offset pivot point
  43950. controllerObject3D.position.copy(DEFAULT_MODEL_PIVOT_OFFSET);
  43951. this.el.emit('controllermodelready', {
  43952. name: 'oculus-touch-controls',
  43953. model: this.data.model,
  43954. rayOrigin: RAY_ORIGIN[this.data.hand]
  43955. });
  43956. },
  43957. onAxisMoved: function (evt) {
  43958. this.emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  43959. },
  43960. updateModel: function (buttonName, evtName) {
  43961. if (!this.data.model) { return; }
  43962. this.updateButtonModel(buttonName, evtName);
  43963. },
  43964. updateButtonModel: function (buttonName, state) {
  43965. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  43966. var buttonMeshes = this.buttonMeshes;
  43967. if (!this.data.model) { return; }
  43968. if (buttonMeshes && buttonMeshes[buttonName]) {
  43969. buttonMeshes[buttonName].material.color.set(color);
  43970. }
  43971. }
  43972. });
  43973. },{"../core/component":103,"../lib/three":151,"../utils/bind":167,"../utils/tracked-controls":179}],70:[function(_dereq_,module,exports){
  43974. var registerComponent = _dereq_('../core/component').registerComponent;
  43975. module.exports.Component = registerComponent('position', {
  43976. schema: {type: 'vec3'},
  43977. update: function () {
  43978. var object3D = this.el.object3D;
  43979. var data = this.data;
  43980. object3D.position.set(data.x, data.y, data.z);
  43981. },
  43982. remove: function () {
  43983. // Pretty much for mixins.
  43984. this.el.object3D.position.set(0, 0, 0);
  43985. }
  43986. });
  43987. },{"../core/component":103}],71:[function(_dereq_,module,exports){
  43988. /* global MutationObserver */
  43989. var registerComponent = _dereq_('../core/component').registerComponent;
  43990. var THREE = _dereq_('../lib/three');
  43991. var utils = _dereq_('../utils/');
  43992. var warn = utils.debug('components:raycaster:warn');
  43993. // Defines selectors that should be 'safe' for the MutationObserver used to
  43994. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  43995. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  43996. // reliably detected and are therefore disallowed.
  43997. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  43998. // Configuration for the MutationObserver used to refresh the whitelist.
  43999. // Listens for addition/removal of elements and attributes within the scene.
  44000. var OBSERVER_CONFIG = {
  44001. childList: true,
  44002. attributes: true,
  44003. subtree: true
  44004. };
  44005. /**
  44006. * Raycaster component.
  44007. *
  44008. * Pass options to three.js Raycaster including which objects to test.
  44009. * Poll for intersections.
  44010. * Emit event on origin entity and on target entity on intersect.
  44011. *
  44012. * @member {array} intersectedEls - List of currently intersected entities.
  44013. * @member {array} objects - Cached list of meshes to intersect.
  44014. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  44015. * @member {object} raycaster - three.js Raycaster.
  44016. */
  44017. module.exports.Component = registerComponent('raycaster', {
  44018. schema: {
  44019. autoRefresh: {default: true},
  44020. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  44021. enabled: {default: true},
  44022. far: {default: 1000},
  44023. interval: {default: 0},
  44024. near: {default: 0},
  44025. objects: {default: ''},
  44026. origin: {type: 'vec3'},
  44027. recursive: {default: true},
  44028. showLine: {default: false},
  44029. useWorldCoordinates: {default: false}
  44030. },
  44031. init: function () {
  44032. this.clearedIntersectedEls = [];
  44033. this.unitLineEndVec3 = new THREE.Vector3();
  44034. this.intersectedEls = [];
  44035. this.intersections = [];
  44036. this.newIntersectedEls = [];
  44037. this.newIntersections = [];
  44038. this.objects = [];
  44039. this.prevCheckTime = undefined;
  44040. this.prevIntersectedEls = [];
  44041. this.rawIntersections = [];
  44042. this.raycaster = new THREE.Raycaster();
  44043. this.updateOriginDirection();
  44044. this.setDirty = this.setDirty.bind(this);
  44045. this.observer = new MutationObserver(this.setDirty);
  44046. this.dirty = true;
  44047. this.lineEndVec3 = new THREE.Vector3();
  44048. this.otherLineEndVec3 = new THREE.Vector3();
  44049. this.lineData = {end: this.lineEndVec3};
  44050. this.intersectedClearedDetail = {el: this.el};
  44051. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  44052. this.intersectionDetail = {};
  44053. },
  44054. /**
  44055. * Create or update raycaster object.
  44056. */
  44057. update: function (oldData) {
  44058. var data = this.data;
  44059. var el = this.el;
  44060. var raycaster = this.raycaster;
  44061. // Set raycaster properties.
  44062. raycaster.far = data.far;
  44063. raycaster.near = data.near;
  44064. // Draw line.
  44065. if (data.showLine &&
  44066. (data.far !== oldData.far || data.origin !== oldData.origin ||
  44067. data.direction !== oldData.direction || !oldData.showLine)) {
  44068. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  44069. // adjust line length.
  44070. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  44071. this.drawLine();
  44072. }
  44073. if (!data.showLine && oldData.showLine) {
  44074. el.removeAttribute('line');
  44075. }
  44076. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  44077. warn('Selector "' + data.objects + '" may not update automatically with DOM changes.');
  44078. }
  44079. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  44080. data.autoRefresh
  44081. ? this.addEventListeners()
  44082. : this.removeEventListeners();
  44083. }
  44084. this.setDirty();
  44085. },
  44086. play: function () {
  44087. this.addEventListeners();
  44088. },
  44089. pause: function () {
  44090. this.removeEventListeners();
  44091. },
  44092. remove: function () {
  44093. if (this.data.showLine) {
  44094. this.el.removeAttribute('line');
  44095. }
  44096. },
  44097. addEventListeners: function () {
  44098. if (!this.data.autoRefresh) { return; }
  44099. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  44100. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  44101. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  44102. },
  44103. removeEventListeners: function () {
  44104. this.observer.disconnect();
  44105. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  44106. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  44107. },
  44108. /**
  44109. * Mark the object list as dirty, to be refreshed before next raycast.
  44110. */
  44111. setDirty: function () {
  44112. this.dirty = true;
  44113. },
  44114. /**
  44115. * Update list of objects to test for intersection.
  44116. */
  44117. refreshObjects: function () {
  44118. var data = this.data;
  44119. var els;
  44120. // If objects not defined, intersect with everything.
  44121. els = data.objects
  44122. ? this.el.sceneEl.querySelectorAll(data.objects)
  44123. : this.el.sceneEl.children;
  44124. this.objects = this.flattenChildrenShallow(els);
  44125. this.dirty = false;
  44126. },
  44127. /**
  44128. * Check for intersections and cleared intersections on an interval.
  44129. */
  44130. tick: function (time) {
  44131. var data = this.data;
  44132. var prevCheckTime = this.prevCheckTime;
  44133. // Only check for intersection if interval time has passed.
  44134. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  44135. // Update check time.
  44136. this.prevCheckTime = time;
  44137. this.checkIntersections();
  44138. },
  44139. /**
  44140. * Raycast for intersections and emit events for current and cleared inersections.
  44141. */
  44142. checkIntersections: function () {
  44143. var clearedIntersectedEls = this.clearedIntersectedEls;
  44144. var el = this.el;
  44145. var data = this.data;
  44146. var i;
  44147. var intersectedEls = this.intersectedEls;
  44148. var intersection;
  44149. var intersections = this.intersections;
  44150. var lineLength;
  44151. var newIntersectedEls = this.newIntersectedEls;
  44152. var newIntersections = this.newIntersections;
  44153. var prevIntersectedEls = this.prevIntersectedEls;
  44154. var rawIntersections = this.rawIntersections;
  44155. var self = this;
  44156. if (!this.data.enabled) { return; }
  44157. // Refresh the object whitelist if needed.
  44158. if (this.dirty) { this.refreshObjects(); }
  44159. // Store old previously intersected entities.
  44160. copyArray(this.prevIntersectedEls, this.intersectedEls);
  44161. // Raycast.
  44162. this.updateOriginDirection();
  44163. rawIntersections.length = 0;
  44164. this.raycaster.intersectObjects(this.objects, data.recursive, rawIntersections);
  44165. // Only keep intersections against objects that have a reference to an entity.
  44166. intersections.length = 0;
  44167. intersectedEls.length = 0;
  44168. for (i = 0; i < rawIntersections.length; i++) {
  44169. intersection = rawIntersections[i];
  44170. // Don't intersect with own line.
  44171. if (data.showLine && intersection.object === el.getObject3D('line')) {
  44172. continue;
  44173. }
  44174. if (intersection.object.el) {
  44175. intersections.push(intersection);
  44176. intersectedEls.push(intersection.object.el);
  44177. }
  44178. }
  44179. // Get newly intersected entities.
  44180. newIntersections.length = 0;
  44181. newIntersectedEls.length = 0;
  44182. for (i = 0; i < intersections.length; i++) {
  44183. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  44184. newIntersections.push(intersections[i]);
  44185. newIntersectedEls.push(intersections[i].object.el);
  44186. }
  44187. }
  44188. // Emit intersection cleared on both entities per formerly intersected entity.
  44189. clearedIntersectedEls.length = 0;
  44190. for (i = 0; i < prevIntersectedEls.length; i++) {
  44191. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  44192. prevIntersectedEls[i].emit('raycaster-intersected-cleared',
  44193. this.intersectedClearedDetail);
  44194. clearedIntersectedEls.push(prevIntersectedEls[i]);
  44195. }
  44196. if (clearedIntersectedEls.length) {
  44197. el.emit('raycaster-intersection-cleared', this.intersectionClearedDetail);
  44198. }
  44199. // Emit intersected on intersected entity per intersected entity.
  44200. for (i = 0; i < newIntersectedEls.length; i++) {
  44201. newIntersectedEls[i].emit('raycaster-intersected', {
  44202. el: el,
  44203. intersection: newIntersections[i]
  44204. });
  44205. }
  44206. // Emit all intersections at once on raycasting entity.
  44207. if (newIntersections.length) {
  44208. this.intersectionDetail.els = newIntersectedEls;
  44209. this.intersectionDetail.intersections = newIntersections;
  44210. el.emit('raycaster-intersection', this.intersectionDetail);
  44211. }
  44212. // Update line length.
  44213. setTimeout(function () {
  44214. if (self.data.showLine) {
  44215. if (intersections.length) {
  44216. if (intersections[0].object.el === el && intersections[1]) {
  44217. lineLength = intersections[1].distance;
  44218. } else {
  44219. lineLength = intersections[0].distance;
  44220. }
  44221. }
  44222. self.drawLine(lineLength);
  44223. }
  44224. });
  44225. },
  44226. /**
  44227. * Return the most recent intersection details for a given entity, if any.
  44228. * @param {AEntity} el
  44229. * @return {Object}
  44230. */
  44231. getIntersection: function (el) {
  44232. var i;
  44233. var intersection;
  44234. for (i = 0; i < this.intersections.length; i++) {
  44235. intersection = this.intersections[i];
  44236. if (intersection.object.el === el) { return intersection; }
  44237. }
  44238. return null;
  44239. },
  44240. /**
  44241. * Update origin and direction of raycaster using entity transforms and supplied origin or
  44242. * direction offsets.
  44243. */
  44244. updateOriginDirection: (function () {
  44245. var direction = new THREE.Vector3();
  44246. var originVec3 = new THREE.Vector3();
  44247. // Closure to make quaternion/vector3 objects private.
  44248. return function updateOriginDirection () {
  44249. var el = this.el;
  44250. var data = this.data;
  44251. if (data.useWorldCoordinates) {
  44252. this.raycaster.set(data.origin, data.direction);
  44253. return;
  44254. }
  44255. // Grab the position and rotation.
  44256. el.object3D.updateMatrixWorld();
  44257. el.object3D.getWorldPosition(originVec3);
  44258. // If non-zero origin, translate the origin into world space.
  44259. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  44260. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  44261. }
  44262. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  44263. // provide. Apply the offset to the direction, then rotation from the object,
  44264. // and normalize.
  44265. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  44266. // Apply offset and direction, in world coordinates.
  44267. this.raycaster.set(originVec3, direction);
  44268. };
  44269. })(),
  44270. /**
  44271. * Create or update line to give raycaster visual representation.
  44272. * Customize the line through through line component.
  44273. * We draw the line in the raycaster component to customize the line to the
  44274. * raycaster's origin, direction, and far.
  44275. *
  44276. * Unlike the raycaster, we create the line as a child of the object. The line will
  44277. * be affected by the transforms of the objects, so we don't have to calculate transforms
  44278. * like we do with the raycaster.
  44279. *
  44280. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  44281. * point. If not provided, length will default to the max length, `raycaster.far`.
  44282. */
  44283. drawLine: function (length) {
  44284. var data = this.data;
  44285. var el = this.el;
  44286. var endVec3;
  44287. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  44288. endVec3 = this.lineData.end === this.lineEndVec3
  44289. ? this.otherLineEndVec3
  44290. : this.lineEndVec3;
  44291. // Treat Infinity as 1000m for the line.
  44292. if (length === undefined) {
  44293. length = data.far === Infinity ? 1000 : data.far;
  44294. }
  44295. // Update the length of the line if given. `unitLineEndVec3` is the direction
  44296. // given by data.direction, then we apply a scalar to give it a length.
  44297. this.lineData.start = data.origin;
  44298. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  44299. el.setAttribute('line', this.lineData);
  44300. },
  44301. /**
  44302. * Return children of each element's object3D group. Children are flattened
  44303. * by one level, removing the THREE.Group wrapper, so that non-recursive
  44304. * raycasting remains useful.
  44305. *
  44306. * @param {Array<Element>} els
  44307. * @return {Array<THREE.Object3D>}
  44308. */
  44309. flattenChildrenShallow: (function () {
  44310. var groups = [];
  44311. return function (els) {
  44312. var children;
  44313. var i;
  44314. var objects = this.objects;
  44315. // Push meshes onto list of objects to intersect.
  44316. groups.length = 0;
  44317. for (i = 0; i < els.length; i++) {
  44318. if (els[i].object3D) {
  44319. groups.push(els[i].object3D);
  44320. }
  44321. }
  44322. // Each entity's root is a THREE.Group. Return the group's chilrden.
  44323. objects.length = 0;
  44324. for (i = 0; i < groups.length; i++) {
  44325. children = groups[i].children;
  44326. if (children && children.length) {
  44327. objects.push.apply(objects, children);
  44328. }
  44329. }
  44330. return objects;
  44331. };
  44332. })()
  44333. });
  44334. /**
  44335. * Copy contents of one array to another without allocating new array.
  44336. */
  44337. function copyArray (a, b) {
  44338. var i;
  44339. a.length = b.length;
  44340. for (i = 0; i < b.length; i++) {
  44341. a[i] = b[i];
  44342. }
  44343. }
  44344. },{"../core/component":103,"../lib/three":151,"../utils/":173}],72:[function(_dereq_,module,exports){
  44345. var degToRad = _dereq_('../lib/three').Math.degToRad;
  44346. var registerComponent = _dereq_('../core/component').registerComponent;
  44347. module.exports.Component = registerComponent('rotation', {
  44348. schema: {type: 'vec3'},
  44349. /**
  44350. * Updates object3D rotation.
  44351. */
  44352. update: function () {
  44353. var data = this.data;
  44354. var object3D = this.el.object3D;
  44355. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  44356. object3D.rotation.order = 'YXZ';
  44357. },
  44358. remove: function () {
  44359. // Pretty much for mixins.
  44360. this.el.object3D.rotation.set(0, 0, 0);
  44361. }
  44362. });
  44363. },{"../core/component":103,"../lib/three":151}],73:[function(_dereq_,module,exports){
  44364. var registerComponent = _dereq_('../core/component').registerComponent;
  44365. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  44366. var zeroScale = 0.00001;
  44367. module.exports.Component = registerComponent('scale', {
  44368. schema: {
  44369. type: 'vec3',
  44370. default: {x: 1, y: 1, z: 1}
  44371. },
  44372. update: function () {
  44373. var data = this.data;
  44374. var object3D = this.el.object3D;
  44375. var x = data.x === 0 ? zeroScale : data.x;
  44376. var y = data.y === 0 ? zeroScale : data.y;
  44377. var z = data.z === 0 ? zeroScale : data.z;
  44378. object3D.scale.set(x, y, z);
  44379. },
  44380. remove: function () {
  44381. // Pretty much for mixins.
  44382. this.el.object3D.scale.set(1, 1, 1);
  44383. }
  44384. });
  44385. },{"../core/component":103}],74:[function(_dereq_,module,exports){
  44386. /* global THREE */
  44387. var register = _dereq_('../../core/component').registerComponent;
  44388. module.exports.Component = register('background', {
  44389. schema: {
  44390. color: {type: 'color', default: 'black'},
  44391. transparent: {default: false}
  44392. },
  44393. update: function () {
  44394. var data = this.data;
  44395. var object3D = this.el.object3D;
  44396. if (data.transparent) {
  44397. object3D.background = null;
  44398. return;
  44399. }
  44400. object3D.background = new THREE.Color(data.color);
  44401. }
  44402. });
  44403. },{"../../core/component":103}],75:[function(_dereq_,module,exports){
  44404. var register = _dereq_('../../core/component').registerComponent;
  44405. module.exports.Component = register('debug', {
  44406. schema: {default: true}
  44407. });
  44408. },{"../../core/component":103}],76:[function(_dereq_,module,exports){
  44409. var registerComponent = _dereq_('../../core/component').registerComponent;
  44410. /**
  44411. * Component to embed an a-frame scene within the layout of a 2D page.
  44412. */
  44413. module.exports.Component = registerComponent('embedded', {
  44414. dependencies: ['vr-mode-ui'],
  44415. schema: {default: true},
  44416. update: function () {
  44417. var sceneEl = this.el;
  44418. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  44419. if (this.data === true) {
  44420. if (enterVREl) { enterVREl.classList.add('embedded'); }
  44421. sceneEl.removeFullScreenStyles();
  44422. } else {
  44423. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  44424. sceneEl.addFullScreenStyles();
  44425. }
  44426. }
  44427. });
  44428. },{"../../core/component":103}],77:[function(_dereq_,module,exports){
  44429. var register = _dereq_('../../core/component').registerComponent;
  44430. var THREE = _dereq_('../../lib/three');
  44431. var debug = _dereq_('../../utils/debug');
  44432. var warn = debug('components:fog:warn');
  44433. /**
  44434. * Fog component.
  44435. * Applies only to the scene entity.
  44436. */
  44437. module.exports.Component = register('fog', {
  44438. schema: {
  44439. color: {type: 'color', default: '#000'},
  44440. density: {default: 0.00025},
  44441. far: {default: 1000, min: 0},
  44442. near: {default: 1, min: 0},
  44443. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  44444. },
  44445. update: function () {
  44446. var data = this.data;
  44447. var el = this.el;
  44448. var fog = this.el.object3D.fog;
  44449. if (!el.isScene) {
  44450. warn('Fog component can only be applied to <a-scene>');
  44451. return;
  44452. }
  44453. // (Re)create fog if fog doesn't exist or fog type changed.
  44454. if (!fog || data.type !== fog.name) {
  44455. el.object3D.fog = getFog(data);
  44456. el.systems.material.updateMaterials();
  44457. return;
  44458. }
  44459. // Fog data changed. Update fog.
  44460. Object.keys(this.schema).forEach(function (key) {
  44461. var value = data[key];
  44462. if (key === 'color') { value = new THREE.Color(value); }
  44463. fog[key] = value;
  44464. });
  44465. },
  44466. /**
  44467. * Remove fog on remove (callback).
  44468. */
  44469. remove: function () {
  44470. var fog = this.el.object3D.fog;
  44471. if (!fog) { return; }
  44472. fog.far = 0;
  44473. fog.near = 0.1;
  44474. }
  44475. });
  44476. /**
  44477. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  44478. *
  44479. * @param {object} data - Fog data.
  44480. * @returns {object} fog
  44481. */
  44482. function getFog (data) {
  44483. var fog;
  44484. if (data.type === 'exponential') {
  44485. fog = new THREE.FogExp2(data.color, data.density);
  44486. } else {
  44487. fog = new THREE.Fog(data.color, data.near, data.far);
  44488. }
  44489. fog.name = data.type;
  44490. return fog;
  44491. }
  44492. },{"../../core/component":103,"../../lib/three":151,"../../utils/debug":169}],78:[function(_dereq_,module,exports){
  44493. (function (process){
  44494. /* global AFRAME */
  44495. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  44496. var bind = _dereq_('../../utils/bind');
  44497. var pkg = _dereq_('../../../package');
  44498. var registerComponent = _dereq_('../../core/component').registerComponent;
  44499. /**
  44500. * 0.4.2 to 0.4.x
  44501. * Will need to update this when A-Frame goes to 1.x.x.
  44502. */
  44503. function getFuzzyPatchVersion (version) {
  44504. var split = version.split('.');
  44505. split[2] = 'x';
  44506. return split.join('.');
  44507. }
  44508. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  44509. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  44510. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  44511. var LOADING_MESSAGE = 'Loading Inspector';
  44512. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  44513. module.exports.Component = registerComponent('inspector', {
  44514. schema: {
  44515. url: {default: INSPECTOR_URL}
  44516. },
  44517. init: function () {
  44518. this.onKeydown = bind(this.onKeydown, this);
  44519. this.onMessage = bind(this.onMessage, this);
  44520. this.initOverlay();
  44521. window.addEventListener('keydown', this.onKeydown);
  44522. window.addEventListener('message', this.onMessage);
  44523. },
  44524. initOverlay: function () {
  44525. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  44526. this.loadingMessageEl = document.createElement('div');
  44527. this.loadingMessageEl.classList.add('a-inspector-loader');
  44528. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  44529. },
  44530. remove: function () {
  44531. this.removeEventListeners();
  44532. },
  44533. /**
  44534. * <ctrl> + <alt> + i keyboard shortcut.
  44535. */
  44536. onKeydown: function (evt) {
  44537. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  44538. if (!this.data || !shortcutPressed) { return; }
  44539. this.injectInspector();
  44540. },
  44541. showLoader: function () {
  44542. document.body.appendChild(this.loadingMessageEl);
  44543. },
  44544. hideLoader: function () {
  44545. document.body.removeChild(this.loadingMessageEl);
  44546. },
  44547. /**
  44548. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  44549. */
  44550. onMessage: function (evt) {
  44551. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.injectInspector(); }
  44552. },
  44553. injectInspector: function () {
  44554. var self = this;
  44555. var script;
  44556. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) { return; }
  44557. this.showLoader();
  44558. // Inject.
  44559. script = document.createElement('script');
  44560. script.src = this.data.url;
  44561. script.setAttribute('data-name', 'aframe-inspector');
  44562. script.setAttribute(AFRAME_INJECTED, '');
  44563. script.onload = function () {
  44564. AFRAME.INSPECTOR.open();
  44565. self.hideLoader();
  44566. self.removeEventListeners();
  44567. };
  44568. script.onerror = function () {
  44569. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  44570. };
  44571. document.head.appendChild(script);
  44572. AFRAME.inspectorInjected = true;
  44573. },
  44574. removeEventListeners: function () {
  44575. window.removeEventListener('keydown', this.onKeydown);
  44576. window.removeEventListener('message', this.onMessage);
  44577. }
  44578. });
  44579. }).call(this,_dereq_('_process'))
  44580. },{"../../../package":51,"../../constants":94,"../../core/component":103,"../../utils/bind":167,"_process":32}],79:[function(_dereq_,module,exports){
  44581. var registerComponent = _dereq_('../../core/component').registerComponent;
  44582. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  44583. module.exports.Component = registerComponent('keyboard-shortcuts', {
  44584. schema: {
  44585. enterVR: {default: true},
  44586. exitVR: {default: true}
  44587. },
  44588. init: function () {
  44589. this.onKeyup = this.onKeyup.bind(this);
  44590. },
  44591. update: function (oldData) {
  44592. var data = this.data;
  44593. this.enterVREnabled = data.enterVR;
  44594. },
  44595. play: function () {
  44596. window.addEventListener('keyup', this.onKeyup, false);
  44597. },
  44598. pause: function () {
  44599. window.removeEventListener('keyup', this.onKeyup);
  44600. },
  44601. onKeyup: function (evt) {
  44602. var scene = this.el;
  44603. if (!shouldCaptureKeyEvent(evt)) { return; }
  44604. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  44605. scene.enterVR();
  44606. }
  44607. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  44608. scene.exitVR();
  44609. }
  44610. }
  44611. });
  44612. },{"../../core/component":103,"../../utils/":173}],80:[function(_dereq_,module,exports){
  44613. var debug = _dereq_('../../utils/debug');
  44614. var registerComponent = _dereq_('../../core/component').registerComponent;
  44615. var warn = debug('components:pool:warn');
  44616. /**
  44617. * Pool component to reuse entities.
  44618. * Avoids creating and destroying the same kind of entities.
  44619. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  44620. *
  44621. * @member {array} availableEls - Available entities in the pool.
  44622. * @member {array} usedEls - Entities of the pool in use.
  44623. */
  44624. module.exports.Component = registerComponent('pool', {
  44625. schema: {
  44626. container: {default: ''},
  44627. mixin: {default: ''},
  44628. size: {default: 0},
  44629. dynamic: {default: false}
  44630. },
  44631. multiple: true,
  44632. initPool: function () {
  44633. var i;
  44634. this.availableEls = [];
  44635. this.usedEls = [];
  44636. if (!this.data.mixin) {
  44637. warn('No mixin provided for pool component.');
  44638. }
  44639. if (this.data.container) {
  44640. this.container = document.querySelector(this.data.container);
  44641. if (!this.container) {
  44642. warn('Container ' + this.data.container + ' not found.');
  44643. }
  44644. }
  44645. this.container = this.container || this.el;
  44646. for (i = 0; i < this.data.size; ++i) {
  44647. this.createEntity();
  44648. }
  44649. },
  44650. update: function (oldData) {
  44651. var data = this.data;
  44652. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  44653. this.initPool();
  44654. }
  44655. },
  44656. /**
  44657. * Add a new entity to the list of available entities.
  44658. */
  44659. createEntity: function () {
  44660. var el;
  44661. el = document.createElement('a-entity');
  44662. el.play = this.wrapPlay(el.play);
  44663. el.setAttribute('mixin', this.data.mixin);
  44664. el.object3D.visible = false;
  44665. el.pause();
  44666. this.container.appendChild(el);
  44667. this.availableEls.push(el);
  44668. },
  44669. /**
  44670. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  44671. * entities that are not in use.
  44672. */
  44673. wrapPlay: function (playMethod) {
  44674. var usedEls = this.usedEls;
  44675. return function () {
  44676. if (usedEls.indexOf(this) === -1) { return; }
  44677. playMethod.call(this);
  44678. };
  44679. },
  44680. /**
  44681. * Used to request one of the available entities of the pool.
  44682. */
  44683. requestEntity: function () {
  44684. var el;
  44685. if (this.availableEls.length === 0) {
  44686. if (this.data.dynamic === false) {
  44687. warn('Requested entity from empty pool: ' + this.name);
  44688. return;
  44689. } else {
  44690. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  44691. 'automatically. You might want to increase its initial size: ' + this.name);
  44692. }
  44693. this.createEntity();
  44694. }
  44695. el = this.availableEls.shift();
  44696. this.usedEls.push(el);
  44697. el.object3D.visible = true;
  44698. return el;
  44699. },
  44700. /**
  44701. * Used to return a used entity to the pool.
  44702. */
  44703. returnEntity: function (el) {
  44704. var index = this.usedEls.indexOf(el);
  44705. if (index === -1) {
  44706. warn('The returned entity was not previously pooled from ' + this.name);
  44707. return;
  44708. }
  44709. this.usedEls.splice(index, 1);
  44710. this.availableEls.push(el);
  44711. el.object3D.visible = false;
  44712. el.pause();
  44713. return el;
  44714. }
  44715. });
  44716. },{"../../core/component":103,"../../utils/debug":169}],81:[function(_dereq_,module,exports){
  44717. var register = _dereq_('../../core/component').registerComponent;
  44718. var debug = _dereq_('../../utils/debug');
  44719. var warn = debug('components:renderer:warn');
  44720. /**
  44721. * Determines state of various renderer properties.
  44722. *
  44723. * NOTE: Because the `renderer` component is not added to the scene
  44724. * automatically, changing default values here has no effect unless
  44725. * the same changes are included in `a-scene.js`.
  44726. */
  44727. module.exports.Component = register('renderer', {
  44728. schema: {
  44729. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  44730. gammaOutput: {default: false},
  44731. physicallyCorrectLights: {default: false},
  44732. sortObjects: {default: false}
  44733. },
  44734. init: function () {
  44735. var el = this.el;
  44736. if (!el.isScene) {
  44737. warn('Renderer component can only be applied to <a-scene>');
  44738. }
  44739. // TODO: Uncomment these lines and deprecate 'antialias' for v0.9.0.
  44740. // if (el.hasAttribute('antialias')) {
  44741. // warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  44742. // }
  44743. },
  44744. update: function (prevData) {
  44745. var data = this.data;
  44746. var sceneEl = this.el;
  44747. var renderer = sceneEl.renderer;
  44748. var needsShaderUpdate = false;
  44749. if (sceneEl.time > 0 && data.antialias !== prevData.antialias) {
  44750. warn('Property "antialias" cannot be changed after scene initialization');
  44751. }
  44752. if (data.sortObjects !== prevData.sortObjects) {
  44753. renderer.sortObjects = data.sortObjects;
  44754. }
  44755. if (data.gammaOutput !== prevData.gammaOutput) {
  44756. renderer.gammaOutput = data.gammaOutput;
  44757. needsShaderUpdate = true;
  44758. }
  44759. if (data.physicallyCorrectLights !== prevData.physicallyCorrectLights) {
  44760. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  44761. needsShaderUpdate = true;
  44762. }
  44763. if (!needsShaderUpdate || sceneEl.time === 0) { return; }
  44764. warn('Modifying renderer properties at runtime requires shader update and may drop frames.');
  44765. sceneEl.object3D.traverse(function (node) {
  44766. if (!node.isMesh) { return; }
  44767. if (Array.isArray(node.material)) {
  44768. node.material.forEach(function (material) {
  44769. material.needsUpdate = true;
  44770. });
  44771. } else {
  44772. node.material.needsUpdate = true;
  44773. }
  44774. });
  44775. }
  44776. });
  44777. },{"../../core/component":103,"../../utils/debug":169}],82:[function(_dereq_,module,exports){
  44778. /* global ImageData, URL */
  44779. var registerComponent = _dereq_('../../core/component').registerComponent;
  44780. var THREE = _dereq_('../../lib/three');
  44781. var VERTEX_SHADER = [
  44782. 'attribute vec3 position;',
  44783. 'attribute vec2 uv;',
  44784. 'uniform mat4 projectionMatrix;',
  44785. 'uniform mat4 modelViewMatrix;',
  44786. 'varying vec2 vUv;',
  44787. 'void main() {',
  44788. ' vUv = vec2( 1.- uv.x, uv.y );',
  44789. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  44790. '}'
  44791. ].join('\n');
  44792. var FRAGMENT_SHADER = [
  44793. 'precision mediump float;',
  44794. 'uniform samplerCube map;',
  44795. 'varying vec2 vUv;',
  44796. '#define M_PI 3.141592653589793238462643383279',
  44797. 'void main() {',
  44798. ' vec2 uv = vUv;',
  44799. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  44800. ' float latitude = uv.y * M_PI;',
  44801. ' vec3 dir = vec3(',
  44802. ' - sin( longitude ) * sin( latitude ),',
  44803. ' cos( latitude ),',
  44804. ' - cos( longitude ) * sin( latitude )',
  44805. ' );',
  44806. ' normalize( dir );',
  44807. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  44808. '}'
  44809. ].join('\n');
  44810. /**
  44811. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  44812. * It can be configured to either take 360&deg; captures (`equirectangular`)
  44813. * or regular screenshots (`projection`)
  44814. *
  44815. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  44816. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  44817. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  44818. * WebGLRenderTarget with an ortographic camera.
  44819. */
  44820. module.exports.Component = registerComponent('screenshot', {
  44821. schema: {
  44822. width: {default: 4096},
  44823. height: {default: 2048},
  44824. camera: {type: 'selector'}
  44825. },
  44826. init: function () {
  44827. var el = this.el;
  44828. var self = this;
  44829. if (el.renderer) {
  44830. setup();
  44831. } else {
  44832. el.addEventListener('render-target-loaded', setup);
  44833. }
  44834. function setup () {
  44835. var gl = el.renderer.getContext();
  44836. if (!gl) { return; }
  44837. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  44838. self.material = new THREE.RawShaderMaterial({
  44839. uniforms: {map: {type: 't', value: null}},
  44840. vertexShader: VERTEX_SHADER,
  44841. fragmentShader: FRAGMENT_SHADER,
  44842. side: THREE.DoubleSide
  44843. });
  44844. self.quad = new THREE.Mesh(
  44845. new THREE.PlaneBufferGeometry(1, 1),
  44846. self.material
  44847. );
  44848. self.quad.visible = false;
  44849. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  44850. self.canvas = document.createElement('canvas');
  44851. self.ctx = self.canvas.getContext('2d');
  44852. if (el.camera) { el.camera.add(self.quad); }
  44853. self.onKeyDown = self.onKeyDown.bind(self);
  44854. self.onCameraActive = self.onCameraActive.bind(self);
  44855. el.addEventListener('camera-set-active', self.onCameraActive);
  44856. }
  44857. },
  44858. getRenderTarget: function (width, height) {
  44859. return new THREE.WebGLRenderTarget(width, height, {
  44860. minFilter: THREE.LinearFilter,
  44861. magFilter: THREE.LinearFilter,
  44862. wrapS: THREE.ClampToEdgeWrapping,
  44863. wrapT: THREE.ClampToEdgeWrapping,
  44864. format: THREE.RGBAFormat,
  44865. type: THREE.UnsignedByteType
  44866. });
  44867. },
  44868. resize: function (width, height) {
  44869. // Resize quad.
  44870. this.quad.scale.set(width, height, 1);
  44871. // Resize camera.
  44872. this.camera.left = -1 * width / 2;
  44873. this.camera.right = width / 2;
  44874. this.camera.top = height / 2;
  44875. this.camera.bottom = -1 * height / 2;
  44876. this.camera.updateProjectionMatrix();
  44877. // Resize canvas.
  44878. this.canvas.width = width;
  44879. this.canvas.height = height;
  44880. },
  44881. play: function () {
  44882. window.addEventListener('keydown', this.onKeyDown);
  44883. },
  44884. onCameraActive: function (evt) {
  44885. var cameraParent = this.quad.parent;
  44886. if (cameraParent) { cameraParent.remove(this.quad); }
  44887. evt.detail.cameraEl.getObject3D('camera').add(this.quad);
  44888. },
  44889. /**
  44890. * <ctrl> + <alt> + s = Regular screenshot.
  44891. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  44892. */
  44893. onKeyDown: function (evt) {
  44894. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  44895. if (!this.data || !shortcutPressed) { return; }
  44896. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  44897. this.capture(projection);
  44898. },
  44899. /**
  44900. * Capture a screenshot of the scene.
  44901. *
  44902. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  44903. */
  44904. setCapture: function (projection) {
  44905. var el = this.el;
  44906. var size;
  44907. var camera;
  44908. var cubeCamera;
  44909. // Configure camera.
  44910. if (projection === 'perspective') {
  44911. // Quad is only used in equirectangular mode. Hide it in this case.
  44912. this.quad.visible = false;
  44913. // Use scene camera.
  44914. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  44915. size = {width: this.data.width, height: this.data.height};
  44916. } else {
  44917. // Use ortho camera.
  44918. camera = this.camera;
  44919. // Copy position and rotation of scene camera into the ortho one.
  44920. camera.position.copy(el.camera.getWorldPosition());
  44921. camera.rotation.copy(el.camera.getWorldRotation());
  44922. // Create cube camera and copy position from scene camera.
  44923. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  44924. Math.min(this.cubeMapSize, 2048));
  44925. cubeCamera.position.copy(el.camera.getWorldPosition());
  44926. cubeCamera.rotation.copy(el.camera.getWorldRotation());
  44927. // Render scene with cube camera.
  44928. cubeCamera.updateCubeMap(el.renderer, el.object3D);
  44929. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  44930. size = {width: this.data.width, height: this.data.height};
  44931. // Use quad to project image taken by the cube camera.
  44932. this.quad.visible = true;
  44933. }
  44934. return {
  44935. camera: camera,
  44936. size: size,
  44937. projection: projection
  44938. };
  44939. },
  44940. /**
  44941. * Maintained for backwards compatibility.
  44942. */
  44943. capture: function (projection) {
  44944. var params = this.setCapture(projection);
  44945. this.renderCapture(params.camera, params.size, params.projection);
  44946. // Trigger file download.
  44947. this.saveCapture();
  44948. },
  44949. /**
  44950. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  44951. */
  44952. getCanvas: function (projection) {
  44953. var params = this.setCapture(projection);
  44954. this.renderCapture(params.camera, params.size, params.projection);
  44955. return this.canvas;
  44956. },
  44957. renderCapture: function (camera, size, projection) {
  44958. var autoClear = this.el.renderer.autoClear;
  44959. var el = this.el;
  44960. var imageData;
  44961. var output;
  44962. var pixels;
  44963. var renderer = this.el.renderer;
  44964. // Create rendering target and buffer to store the read pixels.
  44965. output = this.getRenderTarget(size.width, size.height);
  44966. pixels = new Uint8Array(4 * size.width * size.height);
  44967. // Resize quad, camera, and canvas.
  44968. this.resize(size.width, size.height);
  44969. // Render scene to render target.
  44970. renderer.autoClear = true;
  44971. renderer.render(el.object3D, camera, output, true);
  44972. renderer.autoClear = autoClear;
  44973. // Read image pizels back.
  44974. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  44975. if (projection === 'perspective') {
  44976. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  44977. }
  44978. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  44979. // Hide quad after projecting the image.
  44980. this.quad.visible = false;
  44981. // Copy pixels into canvas.
  44982. this.ctx.putImageData(imageData, 0, 0);
  44983. },
  44984. flipPixelsVertically: function (pixels, width, height) {
  44985. var flippedPixels = pixels.slice(0);
  44986. for (var x = 0; x < width; ++x) {
  44987. for (var y = 0; y < height; ++y) {
  44988. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  44989. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  44990. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  44991. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  44992. }
  44993. }
  44994. return flippedPixels;
  44995. },
  44996. /**
  44997. * Download capture to file.
  44998. */
  44999. saveCapture: function () {
  45000. this.canvas.toBlob(function (blob) {
  45001. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  45002. var linkEl = document.createElement('a');
  45003. var url = URL.createObjectURL(blob);
  45004. linkEl.href = url;
  45005. linkEl.setAttribute('download', fileName);
  45006. linkEl.innerHTML = 'downloading...';
  45007. linkEl.style.display = 'none';
  45008. document.body.appendChild(linkEl);
  45009. setTimeout(function () {
  45010. linkEl.click();
  45011. document.body.removeChild(linkEl);
  45012. }, 1);
  45013. }, 'image/png');
  45014. }
  45015. });
  45016. },{"../../core/component":103,"../../lib/three":151}],83:[function(_dereq_,module,exports){
  45017. var registerComponent = _dereq_('../../core/component').registerComponent;
  45018. var RStats = _dereq_('../../../vendor/rStats');
  45019. var utils = _dereq_('../../utils');
  45020. _dereq_('../../../vendor/rStats.extras');
  45021. _dereq_('../../lib/rStatsAframe');
  45022. var AFrameStats = window.aframeStats;
  45023. var bind = utils.bind;
  45024. var HIDDEN_CLASS = 'a-hidden';
  45025. var ThreeStats = window.threeStats;
  45026. /**
  45027. * Stats appended to document.body by RStats.
  45028. */
  45029. module.exports.Component = registerComponent('stats', {
  45030. schema: {default: true},
  45031. init: function () {
  45032. var scene = this.el;
  45033. if (utils.getUrlParameter('stats') === 'false') { return; }
  45034. this.stats = createStats(scene);
  45035. this.statsEl = document.querySelector('.rs-base');
  45036. this.hideBound = bind(this.hide, this);
  45037. this.showBound = bind(this.show, this);
  45038. scene.addEventListener('enter-vr', this.hideBound);
  45039. scene.addEventListener('exit-vr', this.showBound);
  45040. },
  45041. update: function () {
  45042. if (!this.stats) { return; }
  45043. return (!this.data) ? this.hide() : this.show();
  45044. },
  45045. remove: function () {
  45046. this.el.removeEventListener('enter-vr', this.hideBound);
  45047. this.el.removeEventListener('exit-vr', this.showBound);
  45048. if (!this.statsEl) { return; } // Scene detached.
  45049. this.statsEl.parentNode.removeChild(this.statsEl);
  45050. },
  45051. tick: function () {
  45052. var stats = this.stats;
  45053. if (!stats) { return; }
  45054. stats('rAF').tick();
  45055. stats('FPS').frame();
  45056. stats().update();
  45057. },
  45058. hide: function () {
  45059. this.statsEl.classList.add(HIDDEN_CLASS);
  45060. },
  45061. show: function () {
  45062. this.statsEl.classList.remove(HIDDEN_CLASS);
  45063. }
  45064. });
  45065. function createStats (scene) {
  45066. var threeStats = new ThreeStats(scene.renderer);
  45067. var aframeStats = new AFrameStats(scene);
  45068. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  45069. return new RStats({
  45070. css: [], // Our stylesheet is injected from `src/index.js`.
  45071. values: {
  45072. fps: {caption: 'fps', below: 30}
  45073. },
  45074. groups: [
  45075. {caption: 'Framerate', values: ['fps', 'raf']}
  45076. ],
  45077. plugins: plugins
  45078. });
  45079. }
  45080. },{"../../../vendor/rStats":181,"../../../vendor/rStats.extras":180,"../../core/component":103,"../../lib/rStatsAframe":150,"../../utils":173}],84:[function(_dereq_,module,exports){
  45081. var registerComponent = _dereq_('../../core/component').registerComponent;
  45082. var constants = _dereq_('../../constants/');
  45083. var utils = _dereq_('../../utils/');
  45084. var bind = utils.bind;
  45085. var ENTER_VR_CLASS = 'a-enter-vr';
  45086. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  45087. var HIDDEN_CLASS = 'a-hidden';
  45088. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  45089. /**
  45090. * UI for entering VR mode.
  45091. */
  45092. module.exports.Component = registerComponent('vr-mode-ui', {
  45093. dependencies: ['canvas'],
  45094. schema: {
  45095. enabled: {default: true}
  45096. },
  45097. init: function () {
  45098. var self = this;
  45099. var sceneEl = this.el;
  45100. if (utils.getUrlParameter('ui') === 'false') { return; }
  45101. this.insideLoader = false;
  45102. this.enterVREl = null;
  45103. this.orientationModalEl = null;
  45104. this.bindMethods();
  45105. // Hide/show VR UI when entering/exiting VR mode.
  45106. sceneEl.addEventListener('enter-vr', this.updateEnterVRInterface);
  45107. sceneEl.addEventListener('exit-vr', this.updateEnterVRInterface);
  45108. window.addEventListener('message', function (event) {
  45109. if (event.data.type === 'loaderReady') {
  45110. self.insideLoader = true;
  45111. self.remove();
  45112. }
  45113. });
  45114. // Modal that tells the user to change orientation if in portrait.
  45115. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  45116. },
  45117. bindMethods: function () {
  45118. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  45119. this.onModalClick = bind(this.onModalClick, this);
  45120. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  45121. this.updateEnterVRInterface = bind(this.updateEnterVRInterface, this);
  45122. },
  45123. /**
  45124. * Exit VR when modal clicked.
  45125. */
  45126. onModalClick: function () {
  45127. this.el.exitVR();
  45128. },
  45129. /**
  45130. * Enter VR when modal clicked.
  45131. */
  45132. onEnterVRButtonClick: function () {
  45133. this.el.enterVR();
  45134. },
  45135. update: function () {
  45136. var sceneEl = this.el;
  45137. if (!this.data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  45138. return this.remove();
  45139. }
  45140. if (this.enterVREl || this.orientationModalEl) { return; }
  45141. // Add UI if enabled and not already present.
  45142. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  45143. sceneEl.appendChild(this.enterVREl);
  45144. this.orientationModalEl = createOrientationModal(this.onModalClick);
  45145. sceneEl.appendChild(this.orientationModalEl);
  45146. this.updateEnterVRInterface();
  45147. },
  45148. remove: function () {
  45149. [this.enterVREl, this.orientationModalEl].forEach(function (uiElement) {
  45150. if (uiElement && uiElement.parentNode) {
  45151. uiElement.parentNode.removeChild(uiElement);
  45152. }
  45153. });
  45154. },
  45155. updateEnterVRInterface: function () {
  45156. this.toggleEnterVRButtonIfNeeded();
  45157. this.toggleOrientationModalIfNeeded();
  45158. },
  45159. toggleEnterVRButtonIfNeeded: function () {
  45160. var sceneEl = this.el;
  45161. if (!this.enterVREl) { return; }
  45162. if (sceneEl.is('vr-mode')) {
  45163. this.enterVREl.classList.add(HIDDEN_CLASS);
  45164. } else {
  45165. this.enterVREl.classList.remove(HIDDEN_CLASS);
  45166. }
  45167. },
  45168. toggleOrientationModalIfNeeded: function () {
  45169. var sceneEl = this.el;
  45170. var orientationModalEl = this.orientationModalEl;
  45171. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  45172. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  45173. // Show if in VR mode on portrait.
  45174. orientationModalEl.classList.remove(HIDDEN_CLASS);
  45175. } else {
  45176. orientationModalEl.classList.add(HIDDEN_CLASS);
  45177. }
  45178. }
  45179. });
  45180. /**
  45181. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  45182. *
  45183. * Structure: <div><button></div>
  45184. *
  45185. * @param {function} onClick - click event handler
  45186. * @returns {Element} Wrapper <div>.
  45187. */
  45188. function createEnterVRButton (onClick) {
  45189. var vrButton;
  45190. var wrapper;
  45191. // Create elements.
  45192. wrapper = document.createElement('div');
  45193. wrapper.classList.add(ENTER_VR_CLASS);
  45194. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  45195. vrButton = document.createElement('button');
  45196. vrButton.className = ENTER_VR_BTN_CLASS;
  45197. vrButton.setAttribute('title', 'Enter VR mode with a headset or fullscreen mode on a desktop. Visit https://webvr.rocks or https://webvr.info for more information.');
  45198. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  45199. // Insert elements.
  45200. wrapper.appendChild(vrButton);
  45201. vrButton.addEventListener('click', function (evt) {
  45202. onClick();
  45203. evt.stopPropagation();
  45204. });
  45205. return wrapper;
  45206. }
  45207. /**
  45208. * Creates a modal dialog to request the user to switch to landscape orientation.
  45209. *
  45210. * @param {function} onClick - click event handler
  45211. * @returns {Element} Wrapper <div>.
  45212. */
  45213. function createOrientationModal (onClick) {
  45214. var modal = document.createElement('div');
  45215. modal.className = ORIENTATION_MODAL_CLASS;
  45216. modal.classList.add(HIDDEN_CLASS);
  45217. modal.setAttribute(constants.AFRAME_INJECTED, '');
  45218. var exit = document.createElement('button');
  45219. exit.setAttribute(constants.AFRAME_INJECTED, '');
  45220. exit.innerHTML = 'Exit VR';
  45221. // Exit VR on close.
  45222. exit.addEventListener('click', onClick);
  45223. modal.appendChild(exit);
  45224. return modal;
  45225. }
  45226. },{"../../constants/":94,"../../core/component":103,"../../utils/":173}],85:[function(_dereq_,module,exports){
  45227. var component = _dereq_('../core/component');
  45228. var THREE = _dereq_('../lib/three');
  45229. var bind = _dereq_('../utils/bind');
  45230. var registerComponent = component.registerComponent;
  45231. /**
  45232. * Shadow component.
  45233. *
  45234. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  45235. * shadows as specified by the `cast` and `receive` properties.
  45236. */
  45237. module.exports.Component = registerComponent('shadow', {
  45238. schema: {
  45239. cast: {default: true},
  45240. receive: {default: true}
  45241. },
  45242. init: function () {
  45243. this.onMeshChanged = bind(this.update, this);
  45244. this.el.addEventListener('object3dset', this.onMeshChanged);
  45245. this.system.setShadowMapEnabled(true);
  45246. },
  45247. update: function () {
  45248. var data = this.data;
  45249. this.updateDescendants(data.cast, data.receive);
  45250. },
  45251. remove: function () {
  45252. var el = this.el;
  45253. el.removeEventListener('object3dset', this.onMeshChanged);
  45254. this.updateDescendants(false, false);
  45255. },
  45256. updateDescendants: function (cast, receive) {
  45257. var sceneEl = this.el.sceneEl;
  45258. this.el.object3D.traverse(function (node) {
  45259. if (!(node instanceof THREE.Mesh)) { return; }
  45260. node.castShadow = cast;
  45261. node.receiveShadow = receive;
  45262. // If scene has already rendered, materials must be updated.
  45263. if (sceneEl.hasLoaded && node.material) {
  45264. var materials = Array.isArray(node.material) ? node.material : [node.material];
  45265. for (var i = 0; i < materials.length; i++) {
  45266. materials[i].needsUpdate = true;
  45267. }
  45268. }
  45269. });
  45270. }
  45271. });
  45272. },{"../core/component":103,"../lib/three":151,"../utils/bind":167}],86:[function(_dereq_,module,exports){
  45273. var registerComponent = _dereq_('../core/component').registerComponent;
  45274. var debug = _dereq_('../utils/debug');
  45275. var bind = _dereq_('../utils/bind');
  45276. var THREE = _dereq_('../lib/three');
  45277. var warn = debug('components:sound:warn');
  45278. /**
  45279. * Sound component.
  45280. */
  45281. module.exports.Component = registerComponent('sound', {
  45282. schema: {
  45283. autoplay: {default: false},
  45284. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  45285. loop: {default: false},
  45286. maxDistance: {default: 10000},
  45287. on: {default: ''},
  45288. poolSize: {default: 1},
  45289. positional: {default: true},
  45290. refDistance: {default: 1},
  45291. rolloffFactor: {default: 1},
  45292. src: {type: 'audio'},
  45293. volume: {default: 1}
  45294. },
  45295. multiple: true,
  45296. init: function () {
  45297. this.listener = null;
  45298. this.audioLoader = new THREE.AudioLoader();
  45299. this.pool = new THREE.Group();
  45300. this.loaded = false;
  45301. this.mustPlay = false;
  45302. this.playSound = bind(this.playSound, this);
  45303. },
  45304. update: function (oldData) {
  45305. var data = this.data;
  45306. var srcChanged = data.src !== oldData.src;
  45307. // Create new sound if not yet created or changing `src`.
  45308. if (srcChanged) {
  45309. if (!data.src) {
  45310. warn('Audio source was not specified with `src`');
  45311. return;
  45312. }
  45313. this.setupSound();
  45314. }
  45315. this.pool.children.forEach(function (sound) {
  45316. if (data.positional) {
  45317. sound.setDistanceModel(data.distanceModel);
  45318. sound.setMaxDistance(data.maxDistance);
  45319. sound.setRefDistance(data.refDistance);
  45320. sound.setRolloffFactor(data.rolloffFactor);
  45321. }
  45322. sound.setLoop(data.loop);
  45323. sound.setVolume(data.volume);
  45324. sound.isPaused = false;
  45325. });
  45326. if (data.on !== oldData.on) {
  45327. this.updateEventListener(oldData.on);
  45328. }
  45329. // All sound values set. Load in `src`.
  45330. if (srcChanged) {
  45331. var self = this;
  45332. this.loaded = false;
  45333. this.audioLoader.load(data.src, function (buffer) {
  45334. self.pool.children.forEach(function (sound) {
  45335. sound.setBuffer(buffer);
  45336. });
  45337. self.loaded = true;
  45338. // Remove this key from cache, otherwise we can't play it again
  45339. THREE.Cache.remove(data.src);
  45340. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  45341. self.el.emit('sound-loaded', self.evtDetail);
  45342. });
  45343. }
  45344. },
  45345. pause: function () {
  45346. this.stopSound();
  45347. this.removeEventListener();
  45348. },
  45349. play: function () {
  45350. if (this.data.autoplay) { this.playSound(); }
  45351. this.updateEventListener();
  45352. },
  45353. remove: function () {
  45354. this.removeEventListener();
  45355. this.el.removeObject3D(this.attrName);
  45356. try {
  45357. this.pool.children.forEach(function (sound) {
  45358. sound.disconnect();
  45359. });
  45360. } catch (e) {
  45361. // disconnect() will throw if it was never connected initially.
  45362. warn('Audio source not properly disconnected');
  45363. }
  45364. },
  45365. /**
  45366. * Update listener attached to the user defined on event.
  45367. */
  45368. updateEventListener: function (oldEvt) {
  45369. var el = this.el;
  45370. if (oldEvt) { el.removeEventListener(oldEvt, this.playSound); }
  45371. el.addEventListener(this.data.on, this.playSound);
  45372. },
  45373. removeEventListener: function () {
  45374. this.el.removeEventListener(this.data.on, this.playSound);
  45375. },
  45376. /**
  45377. * Removes current sound object, creates new sound object, adds to entity.
  45378. *
  45379. * @returns {object} sound
  45380. */
  45381. setupSound: function () {
  45382. var self = this;
  45383. var el = this.el;
  45384. var sceneEl = el.sceneEl;
  45385. if (this.pool.children.length > 0) {
  45386. this.stopSound();
  45387. el.removeObject3D('sound');
  45388. }
  45389. // Only want one AudioListener. Cache it on the scene.
  45390. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  45391. sceneEl.audioListener = listener;
  45392. if (sceneEl.camera) {
  45393. sceneEl.camera.add(listener);
  45394. }
  45395. // Wait for camera if necessary.
  45396. sceneEl.addEventListener('camera-set-active', function (evt) {
  45397. evt.detail.cameraEl.getObject3D('camera').add(listener);
  45398. });
  45399. // Create [poolSize] audio instances and attach them to pool
  45400. this.pool = new THREE.Group();
  45401. for (var i = 0; i < this.data.poolSize; i++) {
  45402. var sound = this.data.positional ? new THREE.PositionalAudio(listener) : new THREE.Audio(listener);
  45403. this.pool.add(sound);
  45404. }
  45405. el.setObject3D(this.attrName, this.pool);
  45406. this.pool.children.forEach(function (sound) {
  45407. sound.onEnded = function () {
  45408. sound.isPlaying = false;
  45409. el.emit('sound-ended', self.evtDetail);
  45410. };
  45411. });
  45412. },
  45413. /**
  45414. * Pause all the sounds in the pool.
  45415. */
  45416. pauseSound: function () {
  45417. this.isPlaying = false;
  45418. this.pool.children.forEach(function (sound) {
  45419. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) { return; }
  45420. sound.isPaused = true;
  45421. sound.pause();
  45422. });
  45423. },
  45424. /**
  45425. * Look for an unused sound in the pool and play it if found.
  45426. */
  45427. playSound: function () {
  45428. if (!this.loaded) {
  45429. warn('Sound not loaded yet. It will be played once it finished loading');
  45430. this.mustPlay = true;
  45431. return;
  45432. }
  45433. var found = false;
  45434. this.isPlaying = true;
  45435. this.pool.children.forEach(function (sound) {
  45436. if (!sound.isPlaying && sound.buffer && !found) {
  45437. sound.play();
  45438. sound.isPaused = false;
  45439. found = true;
  45440. return;
  45441. }
  45442. });
  45443. if (!found) {
  45444. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  45445. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  45446. return;
  45447. }
  45448. this.mustPlay = false;
  45449. },
  45450. /**
  45451. * Stop all the sounds in the pool.
  45452. */
  45453. stopSound: function () {
  45454. this.isPlaying = false;
  45455. this.pool.children.forEach(function (sound) {
  45456. if (!sound.source || !sound.source.buffer) { return; }
  45457. sound.stop();
  45458. });
  45459. }
  45460. });
  45461. },{"../core/component":103,"../lib/three":151,"../utils/bind":167,"../utils/debug":169}],87:[function(_dereq_,module,exports){
  45462. var createTextGeometry = _dereq_('three-bmfont-text');
  45463. var loadBMFont = _dereq_('load-bmfont');
  45464. var registerComponent = _dereq_('../core/component').registerComponent;
  45465. var coreShader = _dereq_('../core/shader');
  45466. var THREE = _dereq_('../lib/three');
  45467. var utils = _dereq_('../utils/');
  45468. var error = utils.debug('components:text:error');
  45469. var shaders = coreShader.shaders;
  45470. var warn = utils.debug('components:text:warn');
  45471. // 1 to match other A-Frame default widths.
  45472. var DEFAULT_WIDTH = 1;
  45473. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  45474. var MAX_ANISOTROPY = 16;
  45475. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  45476. var FONTS = {
  45477. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  45478. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  45479. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  45480. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  45481. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  45482. monoid: FONT_BASE_URL + 'Monoid.fnt',
  45483. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  45484. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  45485. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  45486. };
  45487. var MSDF_FONTS = ['roboto'];
  45488. var DEFAULT_FONT = 'roboto';
  45489. module.exports.FONTS = FONTS;
  45490. var cache = new PromiseCache();
  45491. var fontWidthFactors = {};
  45492. var textures = {};
  45493. /**
  45494. * SDF-based text component.
  45495. * Based on https://github.com/Jam3/three-bmfont-text.
  45496. *
  45497. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  45498. * original `sdf` shader.
  45499. */
  45500. module.exports.Component = registerComponent('text', {
  45501. multiple: true,
  45502. schema: {
  45503. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  45504. alphaTest: {default: 0.5},
  45505. // `anchor` defaults to center to match geometries.
  45506. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  45507. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  45508. color: {type: 'color', default: '#FFF'},
  45509. font: {type: 'string', default: DEFAULT_FONT},
  45510. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  45511. fontImage: {type: 'string'},
  45512. // `height` has no default, will be populated at layout.
  45513. height: {type: 'number'},
  45514. letterSpacing: {type: 'number', default: 0},
  45515. // `lineHeight` defaults to font's `lineHeight` value.
  45516. lineHeight: {type: 'number'},
  45517. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  45518. negate: {type: 'boolean', default: true},
  45519. opacity: {type: 'number', default: 1.0},
  45520. shader: {default: 'sdf', oneOf: shaders},
  45521. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  45522. tabSize: {default: 4},
  45523. transparent: {default: true},
  45524. value: {type: 'string'},
  45525. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  45526. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  45527. width: {type: 'number'},
  45528. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  45529. wrapCount: {type: 'number', default: 40},
  45530. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  45531. wrapPixels: {type: 'number'},
  45532. // `xOffset` to add padding.
  45533. xOffset: {type: 'number', default: 0},
  45534. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  45535. yOffset: {type: 'number', default: 0},
  45536. // `zOffset` will provide a small z offset to avoid z-fighting.
  45537. zOffset: {type: 'number', default: 0.001}
  45538. },
  45539. init: function () {
  45540. this.shaderData = {};
  45541. this.geometry = createTextGeometry();
  45542. this.createOrUpdateMaterial();
  45543. this.mesh = new THREE.Mesh(this.geometry, this.material);
  45544. this.el.setObject3D(this.attrName, this.mesh);
  45545. },
  45546. update: function (oldData) {
  45547. var data = coerceData(this.data);
  45548. var font = this.currentFont;
  45549. var fontImage = this.getFontImageSrc();
  45550. if (textures[fontImage]) {
  45551. this.texture = textures[fontImage];
  45552. } else {
  45553. // Create texture per font.
  45554. this.texture = textures[fontImage] = new THREE.Texture();
  45555. this.texture.anisotropy = MAX_ANISOTROPY;
  45556. }
  45557. // Update material.
  45558. this.createOrUpdateMaterial();
  45559. // New font. `updateFont` will later change data and layout.
  45560. if (oldData.font !== data.font) {
  45561. this.updateFont();
  45562. return;
  45563. }
  45564. // Update geometry and layout.
  45565. if (font) {
  45566. this.updateGeometry(this.geometry, data, font);
  45567. this.updateLayout(data);
  45568. }
  45569. },
  45570. /**
  45571. * Clean up geometry, material, texture, mesh, objects.
  45572. */
  45573. remove: function () {
  45574. this.geometry.dispose();
  45575. this.geometry = null;
  45576. this.el.removeObject3D(this.attrName);
  45577. this.material.dispose();
  45578. this.material = null;
  45579. this.texture.dispose();
  45580. this.texture = null;
  45581. if (this.shaderObject) {
  45582. delete this.shaderObject;
  45583. }
  45584. },
  45585. /**
  45586. * Update the shader of the material.
  45587. */
  45588. createOrUpdateMaterial: function () {
  45589. var data = this.data;
  45590. var hasChangedShader;
  45591. var material = this.material;
  45592. var NewShader;
  45593. var shaderData = this.shaderData;
  45594. var shaderName;
  45595. // Infer shader if using a stock font (or from `-msdf` filename convention).
  45596. shaderName = data.shader;
  45597. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  45598. shaderName = 'msdf';
  45599. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  45600. shaderName = 'sdf';
  45601. }
  45602. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  45603. shaderData.alphaTest = data.alphaTest;
  45604. shaderData.color = data.color;
  45605. shaderData.map = this.texture;
  45606. shaderData.opacity = data.opacity;
  45607. shaderData.side = parseSide(data.side);
  45608. shaderData.transparent = data.transparent;
  45609. shaderData.negate = data.negate;
  45610. // Shader has not changed, do an update.
  45611. if (!hasChangedShader) {
  45612. // Update shader material.
  45613. this.shaderObject.update(shaderData);
  45614. // Apparently, was not set on `init` nor `update`.
  45615. material.transparent = shaderData.transparent;
  45616. material.side = shaderData.side;
  45617. return;
  45618. }
  45619. // Shader has changed. Create a shader material.
  45620. NewShader = createShader(this.el, shaderName, shaderData);
  45621. this.material = NewShader.material;
  45622. this.shaderObject = NewShader.shader;
  45623. // Set new shader material.
  45624. this.material.side = shaderData.side;
  45625. if (this.mesh) { this.mesh.material = this.material; }
  45626. },
  45627. /**
  45628. * Load font for geometry, load font image for material, and apply.
  45629. */
  45630. updateFont: function () {
  45631. var data = this.data;
  45632. var el = this.el;
  45633. var fontSrc;
  45634. var geometry = this.geometry;
  45635. var self = this;
  45636. if (!data.font) { warn('No font specified. Using the default font.'); }
  45637. // Make invisible during font swap.
  45638. this.mesh.visible = false;
  45639. // Look up font URL to use, and perform cached load.
  45640. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  45641. cache.get(fontSrc, function doLoadFont () {
  45642. return loadFont(fontSrc, data.yOffset);
  45643. }).then(function setFont (font) {
  45644. var coercedData;
  45645. var fontImgSrc;
  45646. if (font.pages.length !== 1) {
  45647. throw new Error('Currently only single-page bitmap fonts are supported.');
  45648. }
  45649. if (!fontWidthFactors[fontSrc]) {
  45650. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  45651. }
  45652. // Update geometry given font metrics.
  45653. coercedData = coerceData(data);
  45654. self.updateGeometry(geometry, self.data, font);
  45655. // Set font and update layout.
  45656. self.currentFont = font;
  45657. self.updateLayout(coercedData);
  45658. // Look up font image URL to use, and perform cached load.
  45659. fontImgSrc = self.getFontImageSrc();
  45660. cache.get(fontImgSrc, function () {
  45661. return loadTexture(fontImgSrc);
  45662. }).then(function (image) {
  45663. // Make mesh visible and apply font image as texture.
  45664. var texture = self.texture;
  45665. texture.image = image;
  45666. texture.needsUpdate = true;
  45667. textures[fontImgSrc] = texture;
  45668. self.texture = texture;
  45669. self.mesh.visible = true;
  45670. el.emit('textfontset', {font: data.font, fontObj: font});
  45671. }).catch(function (err) {
  45672. error(err);
  45673. throw err;
  45674. });
  45675. }).catch(function (err) {
  45676. error(err);
  45677. throw err;
  45678. });
  45679. },
  45680. getFontImageSrc: function () {
  45681. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  45682. return this.data.fontImage || fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  45683. },
  45684. /**
  45685. * Update layout with anchor, alignment, baseline, and considering any meshes.
  45686. */
  45687. updateLayout: function (data) {
  45688. var anchor;
  45689. var baseline;
  45690. var el = this.el;
  45691. var geometry = this.geometry;
  45692. var geometryComponent = el.getAttribute('geometry');
  45693. var height;
  45694. var layout = geometry.layout;
  45695. var mesh = this.mesh;
  45696. var textRenderWidth;
  45697. var textScale;
  45698. var width;
  45699. var x;
  45700. var y;
  45701. // Determine width to use (defined width, geometry's width, or default width).
  45702. geometryComponent = el.getAttribute('geometry');
  45703. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  45704. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  45705. // Note that experimental factor will never be correct for variable width fonts.
  45706. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  45707. this.currentFont.widthFactor);
  45708. textScale = width / textRenderWidth;
  45709. // Determine height to use.
  45710. height = textScale * (layout.height + layout.descender);
  45711. // Update geometry dimensions to match text layout if width and height are set to 0.
  45712. // For example, scales a plane to fit text.
  45713. if (geometryComponent) {
  45714. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  45715. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  45716. }
  45717. // Calculate X position to anchor text left, center, or right.
  45718. anchor = data.anchor === 'align' ? data.align : data.anchor;
  45719. if (anchor === 'left') {
  45720. x = 0;
  45721. } else if (anchor === 'right') {
  45722. x = -1 * layout.width;
  45723. } else if (anchor === 'center') {
  45724. x = -1 * layout.width / 2;
  45725. } else {
  45726. throw new TypeError('Invalid text.anchor property value', anchor);
  45727. }
  45728. // Calculate Y position to anchor text top, center, or bottom.
  45729. baseline = data.baseline;
  45730. if (baseline === 'bottom') {
  45731. y = 0;
  45732. } else if (baseline === 'top') {
  45733. y = -1 * layout.height + layout.ascender;
  45734. } else if (baseline === 'center') {
  45735. y = -1 * layout.height / 2;
  45736. } else {
  45737. throw new TypeError('Invalid text.baseline property value', baseline);
  45738. }
  45739. // Position and scale mesh to apply layout.
  45740. mesh.position.x = x * textScale + data.xOffset;
  45741. mesh.position.y = y * textScale;
  45742. // Place text slightly in front to avoid Z-fighting.
  45743. mesh.position.z = data.zOffset;
  45744. mesh.scale.set(textScale, -1 * textScale, textScale);
  45745. this.geometry.computeBoundingSphere();
  45746. },
  45747. /**
  45748. * Grab font from the constant.
  45749. * Set as a method for test stubbing purposes.
  45750. */
  45751. lookupFont: function (key) {
  45752. return FONTS[key];
  45753. },
  45754. /**
  45755. * Update the text geometry using `three-bmfont-text.update`.
  45756. */
  45757. updateGeometry: function (geometry, data, font) {
  45758. geometry.update(utils.extend({}, data, {
  45759. font: font,
  45760. width: computeWidth(data.wrapPixels, data.wrapCount, font.widthFactor),
  45761. text: data.value.toString().replace(/\\n/g, '\n').replace(/\\t/g, '\t'),
  45762. lineHeight: data.lineHeight || font.common.lineHeight
  45763. }));
  45764. }
  45765. });
  45766. /**
  45767. * Due to using negative scale, we return the opposite side specified.
  45768. * https://github.com/mrdoob/three.js/pull/12787/
  45769. */
  45770. function parseSide (side) {
  45771. switch (side) {
  45772. case 'back': {
  45773. return THREE.FrontSide;
  45774. }
  45775. case 'double': {
  45776. return THREE.DoubleSide;
  45777. }
  45778. default: {
  45779. return THREE.BackSide;
  45780. }
  45781. }
  45782. }
  45783. /**
  45784. * Coerce some data to numbers.
  45785. * as they will be passed directly into text creation and update
  45786. */
  45787. function coerceData (data) {
  45788. data = utils.clone(data);
  45789. if (data.lineHeight !== undefined) {
  45790. data.lineHeight = parseFloat(data.lineHeight);
  45791. if (!isFinite(data.lineHeight)) { data.lineHeight = undefined; }
  45792. }
  45793. if (data.width !== undefined) {
  45794. data.width = parseFloat(data.width);
  45795. if (!isFinite(data.width)) { data.width = undefined; }
  45796. }
  45797. return data;
  45798. }
  45799. /**
  45800. * @returns {Promise}
  45801. */
  45802. function loadFont (src, yOffset) {
  45803. return new Promise(function (resolve, reject) {
  45804. loadBMFont(src, function (err, font) {
  45805. if (err) {
  45806. error('Error loading font', src);
  45807. reject(err);
  45808. return;
  45809. }
  45810. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  45811. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  45812. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  45813. resolve(font);
  45814. });
  45815. });
  45816. }
  45817. /**
  45818. * @returns {Promise}
  45819. */
  45820. function loadTexture (src) {
  45821. return new Promise(function (resolve, reject) {
  45822. new THREE.ImageLoader().load(src, function (image) {
  45823. resolve(image);
  45824. }, undefined, function () {
  45825. error('Error loading font image', src);
  45826. reject(null);
  45827. });
  45828. });
  45829. }
  45830. function createShader (el, shaderName, data) {
  45831. var shader;
  45832. var shaderObject;
  45833. // Set up Shader.
  45834. shaderObject = new shaders[shaderName].Shader();
  45835. shaderObject.el = el;
  45836. shaderObject.init(data);
  45837. shaderObject.update(data);
  45838. // Get material.
  45839. shader = shaderObject.material;
  45840. // Apparently, was not set on `init` nor `update`.
  45841. shader.transparent = data.transparent;
  45842. return {
  45843. material: shader,
  45844. shader: shaderObject
  45845. };
  45846. }
  45847. /**
  45848. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  45849. * Note that experimental factor will never be correct for variable width fonts.
  45850. */
  45851. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  45852. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  45853. }
  45854. /**
  45855. * Compute default font width factor to use.
  45856. */
  45857. function computeFontWidthFactor (font) {
  45858. var sum = 0;
  45859. var digitsum = 0;
  45860. var digits = 0;
  45861. font.chars.map(function (ch) {
  45862. sum += ch.xadvance;
  45863. if (ch.id >= 48 && ch.id <= 57) {
  45864. digits++;
  45865. digitsum += ch.xadvance;
  45866. }
  45867. });
  45868. return digits ? digitsum / digits : sum / font.chars.length;
  45869. }
  45870. /**
  45871. * Get or create a promise given a key and promise generator.
  45872. * @todo Move to a utility and use in other parts of A-Frame.
  45873. */
  45874. function PromiseCache () {
  45875. var cache = this.cache = {};
  45876. this.get = function (key, promiseGenerator) {
  45877. if (key in cache) {
  45878. return cache[key];
  45879. }
  45880. cache[key] = promiseGenerator();
  45881. return cache[key];
  45882. };
  45883. }
  45884. },{"../core/component":103,"../core/shader":112,"../lib/three":151,"../utils/":173,"load-bmfont":23,"three-bmfont-text":36}],88:[function(_dereq_,module,exports){
  45885. var registerComponent = _dereq_('../core/component').registerComponent;
  45886. var controllerUtils = _dereq_('../utils/tracked-controls');
  45887. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  45888. var THREE = _dereq_('../lib/three');
  45889. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  45890. // Vector from eyes to elbow (divided by user height).
  45891. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  45892. // Vector from eyes to elbow (divided by user height).
  45893. var FOREARM = {x: 0, y: 0, z: -0.175};
  45894. /**
  45895. * Tracked controls component.
  45896. * Wrap the gamepad API for pose and button states.
  45897. * Select the appropriate controller and apply pose to the entity.
  45898. * Observe button states and emit appropriate events.
  45899. *
  45900. * @property {number} controller - Index of controller in array returned by Gamepad API. Only used if hand property is not set.
  45901. * @property {string} id - Selected controller among those returned by Gamepad API.
  45902. * @property {number} hand - If multiple controllers found with id, choose the one with the given value for hand. If set, we ignore 'controller' property
  45903. */
  45904. module.exports.Component = registerComponent('tracked-controls', {
  45905. schema: {
  45906. controller: {default: 0},
  45907. id: {type: 'string', default: ''},
  45908. hand: {type: 'string', default: ''},
  45909. idPrefix: {type: 'string', default: ''},
  45910. orientationOffset: {type: 'vec3'},
  45911. // Arm model parameters when not 6DoF.
  45912. armModel: {default: true},
  45913. headElement: {type: 'selector'}
  45914. },
  45915. init: function () {
  45916. this.axis = [0, 0, 0];
  45917. this.buttonStates = {};
  45918. this.changedAxes = [];
  45919. this.targetControllerNumber = this.data.controller;
  45920. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  45921. this.deltaControllerPosition = new THREE.Vector3();
  45922. this.controllerQuaternion = new THREE.Quaternion();
  45923. this.controllerEuler = new THREE.Euler();
  45924. this.updateGamepad();
  45925. },
  45926. tick: function (time, delta) {
  45927. var mesh = this.el.getObject3D('mesh');
  45928. // Update mesh animations.
  45929. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  45930. this.updateGamepad();
  45931. this.updatePose();
  45932. this.updateButtons();
  45933. },
  45934. /**
  45935. * Return default user height to use for non-6DOF arm model.
  45936. */
  45937. defaultUserHeight: function () {
  45938. return DEFAULT_CAMERA_HEIGHT;
  45939. },
  45940. /**
  45941. * Return head element to use for non-6DOF arm model.
  45942. */
  45943. getHeadElement: function () {
  45944. return this.data.headElement || this.el.sceneEl.camera.el;
  45945. },
  45946. /**
  45947. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  45948. */
  45949. updateGamepad: function () {
  45950. var data = this.data;
  45951. var controller = controllerUtils.findMatchingController(
  45952. this.system.controllers,
  45953. data.id,
  45954. data.idPrefix,
  45955. data.hand,
  45956. data.controller
  45957. );
  45958. this.controller = controller;
  45959. },
  45960. /**
  45961. * Applies an artificial arm model to simulate elbow to wrist positioning
  45962. * based on the orientation of the controller.
  45963. *
  45964. * @param {object} controllerPosition - Existing vector to update with controller position.
  45965. */
  45966. applyArmModel: function (controllerPosition) {
  45967. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  45968. var controller = this.controller;
  45969. var controllerEuler = this.controllerEuler;
  45970. var controllerQuaternion = this.controllerQuaternion;
  45971. var deltaControllerPosition = this.deltaControllerPosition;
  45972. var hand;
  45973. var headEl;
  45974. var headObject3D;
  45975. var pose;
  45976. var userHeight;
  45977. headEl = this.getHeadElement();
  45978. headObject3D = headEl.object3D;
  45979. userHeight = this.defaultUserHeight();
  45980. pose = controller.pose;
  45981. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  45982. // Use camera position as head position.
  45983. controllerPosition.copy(headObject3D.position);
  45984. // Set offset for degenerate "arm model" to elbow.
  45985. deltaControllerPosition.set(
  45986. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  45987. EYES_TO_ELBOW.y, // Lower than our eyes.
  45988. EYES_TO_ELBOW.z); // Slightly out in front.
  45989. // Scale offset by user height.
  45990. deltaControllerPosition.multiplyScalar(userHeight);
  45991. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  45992. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  45993. // Apply rotated offset to position.
  45994. controllerPosition.add(deltaControllerPosition);
  45995. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  45996. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  45997. // Scale offset by user height.
  45998. deltaControllerPosition.multiplyScalar(userHeight);
  45999. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  46000. if (pose.orientation) {
  46001. controllerQuaternion.fromArray(pose.orientation);
  46002. } else {
  46003. controllerQuaternion.copy(headObject3D.quaternion);
  46004. }
  46005. controllerEuler.setFromQuaternion(controllerQuaternion);
  46006. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  46007. deltaControllerPosition.applyEuler(controllerEuler);
  46008. // Apply rotated offset to position.
  46009. controllerPosition.add(deltaControllerPosition);
  46010. },
  46011. /**
  46012. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  46013. */
  46014. updatePose: function () {
  46015. var controller = this.controller;
  46016. var data = this.data;
  46017. var object3D = this.el.object3D;
  46018. var pose;
  46019. var vrDisplay = this.system.vrDisplay;
  46020. var standingMatrix;
  46021. if (!controller) { return; }
  46022. // Compose pose from Gamepad.
  46023. pose = controller.pose;
  46024. if (pose.position) {
  46025. object3D.position.fromArray(pose.position);
  46026. } else {
  46027. // Controller not 6DOF, apply arm model.
  46028. if (data.armModel) { this.applyArmModel(object3D.position); }
  46029. }
  46030. if (pose.orientation) {
  46031. object3D.quaternion.fromArray(pose.orientation);
  46032. }
  46033. // Apply transforms, if 6DOF and in VR.
  46034. if (vrDisplay && pose.position) {
  46035. standingMatrix = this.el.sceneEl.renderer.vr.getStandingMatrix();
  46036. object3D.matrixAutoUpdate = false;
  46037. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  46038. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  46039. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  46040. }
  46041. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  46042. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  46043. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  46044. object3D.updateMatrix();
  46045. object3D.matrixWorldNeedsUpdate = true;
  46046. },
  46047. /**
  46048. * Handle button changes including axes, presses, touches, values.
  46049. */
  46050. updateButtons: function () {
  46051. var buttonState;
  46052. var controller = this.controller;
  46053. var id;
  46054. if (!controller) { return; }
  46055. // Check every button.
  46056. for (id = 0; id < controller.buttons.length; ++id) {
  46057. // Initialize button state.
  46058. if (!this.buttonStates[id]) {
  46059. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  46060. }
  46061. buttonState = controller.buttons[id];
  46062. this.handleButton(id, buttonState);
  46063. }
  46064. // Check axes.
  46065. this.handleAxes();
  46066. },
  46067. /**
  46068. * Handle presses and touches for a single button.
  46069. *
  46070. * @param {number} id - Index of button in Gamepad button array.
  46071. * @param {number} buttonState - Value of button state from 0 to 1.
  46072. * @returns {boolean} Whether button has changed in any way.
  46073. */
  46074. handleButton: function (id, buttonState) {
  46075. var changed = this.handlePress(id, buttonState) |
  46076. this.handleTouch(id, buttonState) |
  46077. this.handleValue(id, buttonState);
  46078. if (!changed) { return false; }
  46079. this.el.emit('buttonchanged', {id: id, state: buttonState});
  46080. return true;
  46081. },
  46082. /**
  46083. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  46084. * Compare each component of the axis to the previous value to determine change.
  46085. *
  46086. * @returns {boolean} Whether axes changed.
  46087. */
  46088. handleAxes: function () {
  46089. var changed = false;
  46090. var controllerAxes = this.controller.axes;
  46091. var i;
  46092. var previousAxis = this.axis;
  46093. var changedAxes = this.changedAxes;
  46094. // Check if axis changed.
  46095. this.changedAxes.length = 0;
  46096. for (i = 0; i < controllerAxes.length; ++i) {
  46097. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  46098. if (changedAxes[i]) { changed = true; }
  46099. }
  46100. if (!changed) { return false; }
  46101. this.axis.length = 0;
  46102. for (i = 0; i < controllerAxes.length; i++) {
  46103. this.axis.push(controllerAxes[i]);
  46104. }
  46105. this.el.emit('axismove', this.axisMoveEventDetail);
  46106. return true;
  46107. },
  46108. /**
  46109. * Determine whether a button press has occured and emit events as appropriate.
  46110. *
  46111. * @param {string} id - ID of the button to check.
  46112. * @param {object} buttonState - State of the button to check.
  46113. * @returns {boolean} Whether button press state changed.
  46114. */
  46115. handlePress: function (id, buttonState) {
  46116. var evtName;
  46117. var previousButtonState = this.buttonStates[id];
  46118. // Not changed.
  46119. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  46120. evtName = buttonState.pressed ? 'down' : 'up';
  46121. this.el.emit('button' + evtName, {id: id, state: buttonState});
  46122. previousButtonState.pressed = buttonState.pressed;
  46123. return true;
  46124. },
  46125. /**
  46126. * Determine whether a button touch has occured and emit events as appropriate.
  46127. *
  46128. * @param {string} id - ID of the button to check.
  46129. * @param {object} buttonState - State of the button to check.
  46130. * @returns {boolean} Whether button touch state changed.
  46131. */
  46132. handleTouch: function (id, buttonState) {
  46133. var evtName;
  46134. var previousButtonState = this.buttonStates[id];
  46135. // Not changed.
  46136. if (buttonState.touched === previousButtonState.touched) { return false; }
  46137. evtName = buttonState.touched ? 'start' : 'end';
  46138. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  46139. this.el.emit('touch' + evtName, {id: id, state: buttonState}, true, {touches: []});
  46140. previousButtonState.touched = buttonState.touched;
  46141. return true;
  46142. },
  46143. /**
  46144. * Determine whether a button value has changed.
  46145. *
  46146. * @param {string} id - Id of the button to check.
  46147. * @param {object} buttonState - State of the button to check.
  46148. * @returns {boolean} Whether button value changed.
  46149. */
  46150. handleValue: function (id, buttonState) {
  46151. var previousButtonState = this.buttonStates[id];
  46152. // Not changed.
  46153. if (buttonState.value === previousButtonState.value) { return false; }
  46154. previousButtonState.value = buttonState.value;
  46155. return true;
  46156. }
  46157. });
  46158. },{"../constants":94,"../core/component":103,"../lib/three":151,"../utils/tracked-controls":179}],89:[function(_dereq_,module,exports){
  46159. var registerComponent = _dereq_('../core/component').registerComponent;
  46160. /**
  46161. * Visibility component.
  46162. */
  46163. module.exports.Component = registerComponent('visible', {
  46164. schema: {default: true},
  46165. update: function () {
  46166. this.el.object3D.visible = this.data;
  46167. }
  46168. });
  46169. },{"../core/component":103}],90:[function(_dereq_,module,exports){
  46170. var registerComponent = _dereq_('../core/component').registerComponent;
  46171. var utils = _dereq_('../utils/');
  46172. var bind = utils.bind;
  46173. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46174. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46175. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46176. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46177. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  46178. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  46179. var GAMEPAD_ID_PREFIX = 'OpenVR ';
  46180. /**
  46181. * Vive controls.
  46182. * Interface with Vive controllers and map Gamepad events to controller buttons:
  46183. * trackpad, trigger, grip, menu, system
  46184. * Load a controller model and highlight the pressed buttons.
  46185. */
  46186. module.exports.Component = registerComponent('vive-controls', {
  46187. schema: {
  46188. hand: {default: 'left'},
  46189. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  46190. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  46191. model: {default: true},
  46192. orientationOffset: {type: 'vec3'}
  46193. },
  46194. /**
  46195. * Button IDs:
  46196. * 0 - trackpad
  46197. * 1 - trigger (intensity value from 0.5 to 1)
  46198. * 2 - grip
  46199. * 3 - menu (dispatch but better for menu options)
  46200. * 4 - system (never dispatched on this layer)
  46201. */
  46202. mapping: {
  46203. axes: {trackpad: [0, 1]},
  46204. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  46205. },
  46206. init: function () {
  46207. var self = this;
  46208. this.animationActive = 'pointing';
  46209. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  46210. this.controllerPresent = false;
  46211. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  46212. this.lastControllerCheck = 0;
  46213. this.onButtonChanged = bind(this.onButtonChanged, this);
  46214. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46215. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46216. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46217. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46218. this.onAxisMoved = bind(this.onAxisMoved, this);
  46219. this.previousButtonValues = {};
  46220. this.bindMethods();
  46221. },
  46222. play: function () {
  46223. this.checkIfControllerPresent();
  46224. this.addControllersUpdateListener();
  46225. },
  46226. pause: function () {
  46227. this.removeEventListeners();
  46228. this.removeControllersUpdateListener();
  46229. },
  46230. bindMethods: function () {
  46231. this.onModelLoaded = bind(this.onModelLoaded, this);
  46232. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46233. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46234. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46235. this.onAxisMoved = bind(this.onAxisMoved, this);
  46236. },
  46237. addEventListeners: function () {
  46238. var el = this.el;
  46239. el.addEventListener('buttonchanged', this.onButtonChanged);
  46240. el.addEventListener('buttondown', this.onButtonDown);
  46241. el.addEventListener('buttonup', this.onButtonUp);
  46242. el.addEventListener('touchend', this.onButtonTouchEnd);
  46243. el.addEventListener('touchstart', this.onButtonTouchStart);
  46244. el.addEventListener('model-loaded', this.onModelLoaded);
  46245. el.addEventListener('axismove', this.onAxisMoved);
  46246. this.controllerEventsActive = true;
  46247. },
  46248. removeEventListeners: function () {
  46249. var el = this.el;
  46250. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46251. el.removeEventListener('buttondown', this.onButtonDown);
  46252. el.removeEventListener('buttonup', this.onButtonUp);
  46253. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46254. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46255. el.removeEventListener('model-loaded', this.onModelLoaded);
  46256. el.removeEventListener('axismove', this.onAxisMoved);
  46257. this.controllerEventsActive = false;
  46258. },
  46259. /**
  46260. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  46261. * var isPresent = this.checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  46262. { hand: data.hand });
  46263. * Until then, use hardcoded index.
  46264. */
  46265. checkIfControllerPresent: function () {
  46266. var data = this.data;
  46267. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  46268. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex});
  46269. },
  46270. injectTrackedControls: function () {
  46271. var el = this.el;
  46272. var data = this.data;
  46273. // If we have an OpenVR Gamepad, use the fixed mapping.
  46274. el.setAttribute('tracked-controls', {
  46275. idPrefix: GAMEPAD_ID_PREFIX,
  46276. // Hand IDs: 0 = right, 1 = left, 2 = anything else.
  46277. controller: data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2,
  46278. orientationOffset: data.orientationOffset
  46279. });
  46280. // Load model.
  46281. if (!this.data.model) { return; }
  46282. this.el.setAttribute('obj-model', {
  46283. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  46284. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  46285. });
  46286. },
  46287. addControllersUpdateListener: function () {
  46288. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46289. },
  46290. removeControllersUpdateListener: function () {
  46291. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46292. },
  46293. onControllersUpdate: function () {
  46294. this.checkIfControllerPresent();
  46295. },
  46296. /**
  46297. * Rotate the trigger button based on how hard the trigger is pressed.
  46298. */
  46299. onButtonChanged: function (evt) {
  46300. var button = this.mapping.buttons[evt.detail.id];
  46301. var buttonMeshes = this.buttonMeshes;
  46302. var analogValue;
  46303. if (!button) { return; }
  46304. if (button === 'trigger') {
  46305. analogValue = evt.detail.state.value;
  46306. // Update trigger rotation depending on button value.
  46307. if (buttonMeshes && buttonMeshes.trigger) {
  46308. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  46309. }
  46310. }
  46311. // Pass along changed event with button state, using button mapping for convenience.
  46312. this.el.emit(button + 'changed', evt.detail.state);
  46313. },
  46314. onModelLoaded: function (evt) {
  46315. var buttonMeshes;
  46316. var controllerObject3D = evt.detail.model;
  46317. var self = this;
  46318. if (!this.data.model) { return; }
  46319. // Store button meshes object to be able to change their colors.
  46320. buttonMeshes = this.buttonMeshes = {};
  46321. buttonMeshes.grip = {
  46322. left: controllerObject3D.getObjectByName('leftgrip'),
  46323. right: controllerObject3D.getObjectByName('rightgrip')
  46324. };
  46325. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  46326. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  46327. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  46328. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  46329. // Set default colors.
  46330. Object.keys(buttonMeshes).forEach(function (buttonName) {
  46331. self.setButtonColor(buttonName, self.data.buttonColor);
  46332. });
  46333. // Offset pivot point.
  46334. controllerObject3D.position.set(0, -0.015, 0.04);
  46335. },
  46336. onAxisMoved: function (evt) {
  46337. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  46338. },
  46339. updateModel: function (buttonName, evtName) {
  46340. var color;
  46341. var isTouch;
  46342. if (!this.data.model) { return; }
  46343. isTouch = evtName.indexOf('touch') !== -1;
  46344. // Don't change color for trackpad touch.
  46345. if (isTouch) { return; }
  46346. // Update colors.
  46347. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  46348. this.setButtonColor(buttonName, color);
  46349. },
  46350. setButtonColor: function (buttonName, color) {
  46351. var buttonMeshes = this.buttonMeshes;
  46352. if (!buttonMeshes) { return; }
  46353. // Need to do both left and right sides for grip.
  46354. if (buttonName === 'grip') {
  46355. buttonMeshes.grip.left.material.color.set(color);
  46356. buttonMeshes.grip.right.material.color.set(color);
  46357. return;
  46358. }
  46359. buttonMeshes[buttonName].material.color.set(color);
  46360. }
  46361. });
  46362. },{"../core/component":103,"../utils/":173,"../utils/tracked-controls":179}],91:[function(_dereq_,module,exports){
  46363. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  46364. var registerComponent = _dereq_('../core/component').registerComponent;
  46365. var THREE = _dereq_('../lib/three');
  46366. var utils = _dereq_('../utils/');
  46367. var bind = utils.bind;
  46368. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  46369. var CLAMP_VELOCITY = 0.00001;
  46370. var MAX_DELTA = 0.2;
  46371. var KEYS = [
  46372. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  46373. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  46374. ];
  46375. /**
  46376. * WASD component to control entities using WASD keys.
  46377. */
  46378. module.exports.Component = registerComponent('wasd-controls', {
  46379. schema: {
  46380. acceleration: {default: 65},
  46381. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  46382. adEnabled: {default: true},
  46383. adInverted: {default: false},
  46384. easing: {default: 20},
  46385. enabled: {default: true},
  46386. fly: {default: false},
  46387. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  46388. wsEnabled: {default: true},
  46389. wsInverted: {default: false}
  46390. },
  46391. init: function () {
  46392. // To keep track of the pressed keys.
  46393. this.keys = {};
  46394. this.position = {};
  46395. this.velocity = new THREE.Vector3();
  46396. // Bind methods and add event listeners.
  46397. this.onBlur = bind(this.onBlur, this);
  46398. this.onFocus = bind(this.onFocus, this);
  46399. this.onKeyDown = bind(this.onKeyDown, this);
  46400. this.onKeyUp = bind(this.onKeyUp, this);
  46401. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  46402. this.attachVisibilityEventListeners();
  46403. },
  46404. tick: function (time, delta) {
  46405. var currentPosition;
  46406. var data = this.data;
  46407. var el = this.el;
  46408. var movementVector;
  46409. var position = this.position;
  46410. var velocity = this.velocity;
  46411. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  46412. isEmptyObject(this.keys)) { return; }
  46413. // Update velocity.
  46414. delta = delta / 1000;
  46415. this.updateVelocity(delta);
  46416. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  46417. // Get movement vector and translate position.
  46418. currentPosition = el.getAttribute('position');
  46419. movementVector = this.getMovementVector(delta);
  46420. position.x = currentPosition.x + movementVector.x;
  46421. position.y = currentPosition.y + movementVector.y;
  46422. position.z = currentPosition.z + movementVector.z;
  46423. el.setAttribute('position', position);
  46424. },
  46425. remove: function () {
  46426. this.removeKeyEventListeners();
  46427. this.removeVisibilityEventListeners();
  46428. },
  46429. play: function () {
  46430. this.attachKeyEventListeners();
  46431. },
  46432. pause: function () {
  46433. this.keys = {};
  46434. this.removeKeyEventListeners();
  46435. },
  46436. updateVelocity: function (delta) {
  46437. var acceleration;
  46438. var adAxis;
  46439. var adSign;
  46440. var data = this.data;
  46441. var keys = this.keys;
  46442. var velocity = this.velocity;
  46443. var wsAxis;
  46444. var wsSign;
  46445. adAxis = data.adAxis;
  46446. wsAxis = data.wsAxis;
  46447. // If FPS too low, reset velocity.
  46448. if (delta > MAX_DELTA) {
  46449. velocity[adAxis] = 0;
  46450. velocity[wsAxis] = 0;
  46451. return;
  46452. }
  46453. // Decay velocity.
  46454. if (velocity[adAxis] !== 0) {
  46455. velocity[adAxis] -= velocity[adAxis] * data.easing * delta;
  46456. }
  46457. if (velocity[wsAxis] !== 0) {
  46458. velocity[wsAxis] -= velocity[wsAxis] * data.easing * delta;
  46459. }
  46460. // Clamp velocity easing.
  46461. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  46462. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  46463. if (!data.enabled) { return; }
  46464. // Update velocity using keys pressed.
  46465. acceleration = data.acceleration;
  46466. if (data.adEnabled) {
  46467. adSign = data.adInverted ? -1 : 1;
  46468. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  46469. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  46470. }
  46471. if (data.wsEnabled) {
  46472. wsSign = data.wsInverted ? -1 : 1;
  46473. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  46474. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  46475. }
  46476. },
  46477. getMovementVector: (function () {
  46478. var directionVector = new THREE.Vector3(0, 0, 0);
  46479. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  46480. return function (delta) {
  46481. var rotation = this.el.getAttribute('rotation');
  46482. var velocity = this.velocity;
  46483. var xRotation;
  46484. directionVector.copy(velocity);
  46485. directionVector.multiplyScalar(delta);
  46486. // Absolute.
  46487. if (!rotation) { return directionVector; }
  46488. xRotation = this.data.fly ? rotation.x : 0;
  46489. // Transform direction relative to heading.
  46490. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  46491. directionVector.applyEuler(rotationEuler);
  46492. return directionVector;
  46493. };
  46494. })(),
  46495. attachVisibilityEventListeners: function () {
  46496. window.addEventListener('blur', this.onBlur);
  46497. window.addEventListener('focus', this.onFocus);
  46498. document.addEventListener('visibilitychange', this.onVisibilityChange);
  46499. },
  46500. removeVisibilityEventListeners: function () {
  46501. window.removeEventListener('blur', this.onBlur);
  46502. window.removeEventListener('focus', this.onFocus);
  46503. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  46504. },
  46505. attachKeyEventListeners: function () {
  46506. window.addEventListener('keydown', this.onKeyDown);
  46507. window.addEventListener('keyup', this.onKeyUp);
  46508. },
  46509. removeKeyEventListeners: function () {
  46510. window.removeEventListener('keydown', this.onKeyDown);
  46511. window.removeEventListener('keyup', this.onKeyUp);
  46512. },
  46513. onBlur: function () {
  46514. this.pause();
  46515. },
  46516. onFocus: function () {
  46517. this.play();
  46518. },
  46519. onVisibilityChange: function () {
  46520. if (document.hidden) {
  46521. this.onBlur();
  46522. } else {
  46523. this.onFocus();
  46524. }
  46525. },
  46526. onKeyDown: function (event) {
  46527. var code;
  46528. if (!shouldCaptureKeyEvent(event)) { return; }
  46529. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  46530. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  46531. },
  46532. onKeyUp: function (event) {
  46533. var code;
  46534. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  46535. delete this.keys[code];
  46536. }
  46537. });
  46538. function isEmptyObject (keys) {
  46539. var key;
  46540. for (key in keys) { return false; }
  46541. return true;
  46542. }
  46543. },{"../constants":94,"../core/component":103,"../lib/three":151,"../utils/":173}],92:[function(_dereq_,module,exports){
  46544. /* global THREE */
  46545. var bind = _dereq_('../utils/bind');
  46546. var registerComponent = _dereq_('../core/component').registerComponent;
  46547. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46548. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46549. var utils = _dereq_('../utils/');
  46550. var debug = utils.debug('components:windows-motion-controls:debug');
  46551. var warn = utils.debug('components:windows-motion-controls:warn');
  46552. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  46553. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  46554. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  46555. var GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  46556. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  46557. /**
  46558. * Windows Motion Controller controls.
  46559. * Interface with Windows Motion Controller controllers and map Gamepad events to
  46560. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  46561. * Load a controller model and transform the pressed buttons.
  46562. */
  46563. module.exports.Component = registerComponent('windows-motion-controls', {
  46564. schema: {
  46565. hand: {default: DEFAULT_HANDEDNESS},
  46566. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  46567. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  46568. pair: {default: 0},
  46569. // If true, loads the controller glTF asset.
  46570. model: {default: true},
  46571. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  46572. hideDisconnected: {default: true}
  46573. },
  46574. mapping: {
  46575. // A-Frame specific semantic axis names
  46576. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  46577. // A-Frame specific semantic button names
  46578. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  46579. // A mapping of the semantic name to node name in the glTF model file,
  46580. // that should be transformed by axis value.
  46581. // This array mirrors the browser Gamepad.axes array, such that
  46582. // the mesh corresponding to axis 0 is in this array index 0.
  46583. axisMeshNames: [
  46584. 'THUMBSTICK_X',
  46585. 'THUMBSTICK_Y',
  46586. 'TOUCHPAD_TOUCH_X',
  46587. 'TOUCHPAD_TOUCH_Y'
  46588. ],
  46589. // A mapping of the semantic name to button node name in the glTF model file,
  46590. // that should be transformed by button value.
  46591. buttonMeshNames: {
  46592. 'trigger': 'SELECT',
  46593. 'menu': 'MENU',
  46594. 'grip': 'GRASP',
  46595. 'thumbstick': 'THUMBSTICK_PRESS',
  46596. 'trackpad': 'TOUCHPAD_PRESS'
  46597. },
  46598. pointingPoseMeshName: 'POINTING_POSE'
  46599. },
  46600. bindMethods: function () {
  46601. this.onModelError = bind(this.onModelError, this);
  46602. this.onModelLoaded = bind(this.onModelLoaded, this);
  46603. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46604. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46605. this.onAxisMoved = bind(this.onAxisMoved, this);
  46606. },
  46607. init: function () {
  46608. var self = this;
  46609. var el = this.el;
  46610. this.onButtonChanged = bind(this.onButtonChanged, this);
  46611. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46612. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46613. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46614. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46615. this.onControllerConnected = function () { self.setModelVisibility(true); };
  46616. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  46617. this.controllerPresent = false;
  46618. this.lastControllerCheck = 0;
  46619. this.previousButtonValues = {};
  46620. this.bindMethods();
  46621. // Cache for submeshes that we have looked up by name.
  46622. this.loadedMeshInfo = {
  46623. buttonMeshes: null,
  46624. axisMeshes: null
  46625. };
  46626. // Pointing poses
  46627. this.rayOrigin = {
  46628. origin: new THREE.Vector3(),
  46629. direction: new THREE.Vector3(0, 0, -1),
  46630. createdFromMesh: false
  46631. };
  46632. // Stored on object to allow for mocking in tests
  46633. this.emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46634. this.checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46635. el.addEventListener('controllerconnected', this.onControllerConnected);
  46636. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  46637. },
  46638. addEventListeners: function () {
  46639. var el = this.el;
  46640. el.addEventListener('buttonchanged', this.onButtonChanged);
  46641. el.addEventListener('buttondown', this.onButtonDown);
  46642. el.addEventListener('buttonup', this.onButtonUp);
  46643. el.addEventListener('touchstart', this.onButtonTouchStart);
  46644. el.addEventListener('touchend', this.onButtonTouchEnd);
  46645. el.addEventListener('axismove', this.onAxisMoved);
  46646. el.addEventListener('model-error', this.onModelError);
  46647. el.addEventListener('model-loaded', this.onModelLoaded);
  46648. this.controllerEventsActive = true;
  46649. },
  46650. removeEventListeners: function () {
  46651. var el = this.el;
  46652. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46653. el.removeEventListener('buttondown', this.onButtonDown);
  46654. el.removeEventListener('buttonup', this.onButtonUp);
  46655. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46656. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46657. el.removeEventListener('axismove', this.onAxisMoved);
  46658. el.removeEventListener('model-error', this.onModelError);
  46659. el.removeEventListener('model-loaded', this.onModelLoaded);
  46660. this.controllerEventsActive = false;
  46661. },
  46662. checkIfControllerPresent: function () {
  46663. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  46664. hand: this.data.hand,
  46665. index: this.data.pair
  46666. });
  46667. },
  46668. play: function () {
  46669. this.checkIfControllerPresent();
  46670. this.addControllersUpdateListener();
  46671. },
  46672. pause: function () {
  46673. this.removeEventListeners();
  46674. this.removeControllersUpdateListener();
  46675. },
  46676. updateControllerModel: function () {
  46677. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  46678. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  46679. this.modelReady();
  46680. return;
  46681. }
  46682. var sourceUrl = this.createControllerModelUrl();
  46683. this.loadModel(sourceUrl);
  46684. },
  46685. /**
  46686. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  46687. * art assets.
  46688. */
  46689. createControllerModelUrl: function (forceDefault) {
  46690. // Determine the device specific folder based on the ID suffix
  46691. var trackedControlsComponent = this.el.components['tracked-controls'];
  46692. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  46693. var device = 'default';
  46694. var hand = this.data.hand;
  46695. var filename;
  46696. if (controller) {
  46697. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  46698. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  46699. // In this case, we want to load the universal model, so need to get the '' from the controller.
  46700. hand = controller.hand;
  46701. if (!forceDefault) {
  46702. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  46703. device = ((match && match[0]) || device);
  46704. }
  46705. }
  46706. // Hand
  46707. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  46708. // Final url
  46709. return MODEL_BASE_URL + device + '/' + filename;
  46710. },
  46711. injectTrackedControls: function () {
  46712. var data = this.data;
  46713. this.el.setAttribute('tracked-controls', {
  46714. idPrefix: GAMEPAD_ID_PREFIX,
  46715. controller: data.pair,
  46716. hand: data.hand,
  46717. armModel: false
  46718. });
  46719. this.updateControllerModel();
  46720. },
  46721. addControllersUpdateListener: function () {
  46722. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46723. },
  46724. removeControllersUpdateListener: function () {
  46725. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46726. },
  46727. onControllersUpdate: function () {
  46728. this.checkIfControllerPresent();
  46729. },
  46730. onModelError: function (evt) {
  46731. var defaultUrl = this.createControllerModelUrl(true);
  46732. if (evt.detail.src !== defaultUrl) {
  46733. warn('Failed to load controller model for device, attempting to load default.');
  46734. this.loadModel(defaultUrl);
  46735. } else {
  46736. warn('Failed to load default controller model.');
  46737. }
  46738. },
  46739. loadModel: function (url) {
  46740. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  46741. // removed and re-loaded if the given url changes.
  46742. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  46743. },
  46744. onModelLoaded: function (evt) {
  46745. var rootNode = this.controllerModel = evt.detail.model;
  46746. var loadedMeshInfo = this.loadedMeshInfo;
  46747. var i;
  46748. var meshName;
  46749. var mesh;
  46750. var meshInfo;
  46751. debug('Processing model');
  46752. // Reset the caches
  46753. loadedMeshInfo.buttonMeshes = {};
  46754. loadedMeshInfo.axisMeshes = {};
  46755. // Cache our meshes so we aren't traversing the hierarchy per frame
  46756. if (rootNode) {
  46757. // Button Meshes
  46758. for (i = 0; i < this.mapping.buttons.length; i++) {
  46759. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  46760. if (!meshName) {
  46761. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  46762. continue;
  46763. }
  46764. mesh = rootNode.getObjectByName(meshName);
  46765. if (!mesh) {
  46766. warn('Missing button mesh with name: ' + meshName);
  46767. continue;
  46768. }
  46769. meshInfo = {
  46770. index: i,
  46771. value: getImmediateChildByName(mesh, 'VALUE'),
  46772. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  46773. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  46774. };
  46775. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  46776. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  46777. } else {
  46778. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  46779. warn('Missing button submesh under mesh with name: ' + meshName +
  46780. '(VALUE: ' + !!meshInfo.value +
  46781. ', PRESSED: ' + !!meshInfo.pressed +
  46782. ', UNPRESSED:' + !!meshInfo.unpressed +
  46783. ')');
  46784. }
  46785. }
  46786. // Axis Meshes
  46787. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  46788. meshName = this.mapping.axisMeshNames[i];
  46789. if (!meshName) {
  46790. debug('Skipping unknown axis at index: ' + i);
  46791. continue;
  46792. }
  46793. mesh = rootNode.getObjectByName(meshName);
  46794. if (!mesh) {
  46795. warn('Missing axis mesh with name: ' + meshName);
  46796. continue;
  46797. }
  46798. meshInfo = {
  46799. index: i,
  46800. value: getImmediateChildByName(mesh, 'VALUE'),
  46801. min: getImmediateChildByName(mesh, 'MIN'),
  46802. max: getImmediateChildByName(mesh, 'MAX')
  46803. };
  46804. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  46805. loadedMeshInfo.axisMeshes[i] = meshInfo;
  46806. } else {
  46807. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  46808. warn('Missing axis submesh under mesh with name: ' + meshName +
  46809. '(VALUE: ' + !!meshInfo.value +
  46810. ', MIN: ' + !!meshInfo.min +
  46811. ', MAX:' + !!meshInfo.max +
  46812. ')');
  46813. }
  46814. }
  46815. this.calculateRayOriginFromMesh(rootNode);
  46816. // Determine if the model has to be visible or not.
  46817. this.setModelVisibility();
  46818. }
  46819. debug('Model load complete.');
  46820. // Look through only immediate children. This will return null if no mesh exists with the given name.
  46821. function getImmediateChildByName (object3d, value) {
  46822. for (var i = 0, l = object3d.children.length; i < l; i++) {
  46823. var obj = object3d.children[i];
  46824. if (obj && obj['name'] === value) {
  46825. return obj;
  46826. }
  46827. }
  46828. return undefined;
  46829. }
  46830. },
  46831. calculateRayOriginFromMesh: (function () {
  46832. var quaternion = new THREE.Quaternion();
  46833. return function (rootNode) {
  46834. var mesh;
  46835. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  46836. // in the glTF (assumes that root node is at world origin)
  46837. this.rayOrigin.origin.set(0, 0, 0);
  46838. this.rayOrigin.direction.set(0, 0, -1);
  46839. this.rayOrigin.createdFromMesh = true;
  46840. // Try to read Pointing pose from the source model
  46841. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  46842. if (mesh) {
  46843. var parent = rootNode.parent;
  46844. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  46845. if (parent) {
  46846. rootNode.parent = null;
  46847. rootNode.updateMatrixWorld(true);
  46848. rootNode.parent = parent;
  46849. }
  46850. mesh.getWorldPosition(this.rayOrigin.origin);
  46851. mesh.getWorldQuaternion(quaternion);
  46852. this.rayOrigin.direction.applyQuaternion(quaternion);
  46853. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  46854. if (parent) {
  46855. rootNode.updateMatrixWorld(true);
  46856. }
  46857. } else {
  46858. debug('Mesh does not contain pointing origin data, defaulting to none.');
  46859. }
  46860. // Emit event stating that our pointing ray is now accurate.
  46861. this.modelReady();
  46862. };
  46863. })(),
  46864. lerpAxisTransform: (function () {
  46865. var quaternion = new THREE.Quaternion();
  46866. return function (axis, axisValue) {
  46867. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  46868. if (!axisMeshInfo) return;
  46869. var min = axisMeshInfo.min;
  46870. var max = axisMeshInfo.max;
  46871. var target = axisMeshInfo.value;
  46872. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  46873. var lerpValue = axisValue * 0.5 + 0.5;
  46874. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  46875. target.position.lerpVectors(min.position, max.position, lerpValue);
  46876. };
  46877. })(),
  46878. lerpButtonTransform: (function () {
  46879. var quaternion = new THREE.Quaternion();
  46880. return function (buttonName, buttonValue) {
  46881. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  46882. if (!buttonMeshInfo) return;
  46883. var min = buttonMeshInfo.unpressed;
  46884. var max = buttonMeshInfo.pressed;
  46885. var target = buttonMeshInfo.value;
  46886. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  46887. target.position.lerpVectors(min.position, max.position, buttonValue);
  46888. };
  46889. })(),
  46890. modelReady: function () {
  46891. this.el.emit('controllermodelready', {
  46892. name: 'windows-motion-controls',
  46893. model: this.data.model,
  46894. rayOrigin: this.rayOrigin
  46895. });
  46896. },
  46897. onButtonChanged: function (evt) {
  46898. var buttonName = this.mapping.buttons[evt.detail.id];
  46899. if (buttonName) {
  46900. // Update the button mesh transform
  46901. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  46902. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  46903. }
  46904. // Only emit events for buttons that we know how to map from index to name
  46905. this.el.emit(buttonName + 'changed', evt.detail.state);
  46906. }
  46907. },
  46908. onAxisMoved: function (evt) {
  46909. var numAxes = this.mapping.axisMeshNames.length;
  46910. // Only attempt to update meshes if we have valid data.
  46911. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  46912. for (var axis = 0; axis < numAxes; axis++) {
  46913. // Update the button mesh transform
  46914. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  46915. }
  46916. }
  46917. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  46918. },
  46919. setModelVisibility: function (visible) {
  46920. var model = this.el.getObject3D('mesh');
  46921. visible = visible !== undefined ? visible : this.modelVisible;
  46922. this.modelVisible = visible;
  46923. if (!model) { return; }
  46924. model.visible = visible;
  46925. }
  46926. });
  46927. },{"../constants":94,"../core/component":103,"../utils/":173,"../utils/bind":167,"../utils/tracked-controls":179}],93:[function(_dereq_,module,exports){
  46928. /**
  46929. * Animation configuration options for TWEEN.js animations.
  46930. * Used by `<a-animation>`.
  46931. */
  46932. var TWEEN = _dereq_('@tweenjs/tween.js');
  46933. var DIRECTIONS = {
  46934. alternate: 'alternate',
  46935. alternateReverse: 'alternate-reverse',
  46936. normal: 'normal',
  46937. reverse: 'reverse'
  46938. };
  46939. var EASING_FUNCTIONS = {
  46940. 'linear': TWEEN.Easing.Linear.None,
  46941. 'ease': TWEEN.Easing.Cubic.InOut,
  46942. 'ease-in': TWEEN.Easing.Cubic.In,
  46943. 'ease-out': TWEEN.Easing.Cubic.Out,
  46944. 'ease-in-out': TWEEN.Easing.Cubic.InOut,
  46945. 'ease-cubic': TWEEN.Easing.Cubic.In,
  46946. 'ease-in-cubic': TWEEN.Easing.Cubic.In,
  46947. 'ease-out-cubic': TWEEN.Easing.Cubic.Out,
  46948. 'ease-in-out-cubic': TWEEN.Easing.Cubic.InOut,
  46949. 'ease-quad': TWEEN.Easing.Quadratic.InOut,
  46950. 'ease-in-quad': TWEEN.Easing.Quadratic.In,
  46951. 'ease-out-quad': TWEEN.Easing.Quadratic.Out,
  46952. 'ease-in-out-quad': TWEEN.Easing.Quadratic.InOut,
  46953. 'ease-quart': TWEEN.Easing.Quartic.InOut,
  46954. 'ease-in-quart': TWEEN.Easing.Quartic.In,
  46955. 'ease-out-quart': TWEEN.Easing.Quartic.Out,
  46956. 'ease-in-out-quart': TWEEN.Easing.Quartic.InOut,
  46957. 'ease-quint': TWEEN.Easing.Quintic.InOut,
  46958. 'ease-in-quint': TWEEN.Easing.Quintic.In,
  46959. 'ease-out-quint': TWEEN.Easing.Quintic.Out,
  46960. 'ease-in-out-quint': TWEEN.Easing.Quintic.InOut,
  46961. 'ease-sine': TWEEN.Easing.Sinusoidal.InOut,
  46962. 'ease-in-sine': TWEEN.Easing.Sinusoidal.In,
  46963. 'ease-out-sine': TWEEN.Easing.Sinusoidal.Out,
  46964. 'ease-in-out-sine': TWEEN.Easing.Sinusoidal.InOut,
  46965. 'ease-expo': TWEEN.Easing.Exponential.InOut,
  46966. 'ease-in-expo': TWEEN.Easing.Exponential.In,
  46967. 'ease-out-expo': TWEEN.Easing.Exponential.Out,
  46968. 'ease-in-out-expo': TWEEN.Easing.Exponential.InOut,
  46969. 'ease-circ': TWEEN.Easing.Circular.InOut,
  46970. 'ease-in-circ': TWEEN.Easing.Circular.In,
  46971. 'ease-out-circ': TWEEN.Easing.Circular.Out,
  46972. 'ease-in-out-circ': TWEEN.Easing.Circular.InOut,
  46973. 'ease-elastic': TWEEN.Easing.Elastic.InOut,
  46974. 'ease-in-elastic': TWEEN.Easing.Elastic.In,
  46975. 'ease-out-elastic': TWEEN.Easing.Elastic.Out,
  46976. 'ease-in-out-elastic': TWEEN.Easing.Elastic.InOut,
  46977. 'ease-back': TWEEN.Easing.Back.InOut,
  46978. 'ease-in-back': TWEEN.Easing.Back.In,
  46979. 'ease-out-back': TWEEN.Easing.Back.Out,
  46980. 'ease-in-out-back': TWEEN.Easing.Back.InOut,
  46981. 'ease-bounce': TWEEN.Easing.Bounce.InOut,
  46982. 'ease-in-bounce': TWEEN.Easing.Bounce.In,
  46983. 'ease-out-bounce': TWEEN.Easing.Bounce.Out,
  46984. 'ease-in-out-bounce': TWEEN.Easing.Bounce.InOut
  46985. };
  46986. var FILLS = {
  46987. backwards: 'backwards',
  46988. both: 'both',
  46989. forwards: 'forwards',
  46990. none: 'none'
  46991. };
  46992. var REPEATS = {
  46993. indefinite: 'indefinite'
  46994. };
  46995. var DEFAULTS = {
  46996. attribute: 'rotation',
  46997. begin: '',
  46998. end: '',
  46999. delay: 0,
  47000. dur: 1000,
  47001. easing: 'ease',
  47002. direction: DIRECTIONS.normal,
  47003. fill: FILLS.forwards,
  47004. from: undefined,
  47005. repeat: 0,
  47006. to: undefined
  47007. };
  47008. module.exports.defaults = DEFAULTS;
  47009. module.exports.directions = DIRECTIONS;
  47010. module.exports.easingFunctions = EASING_FUNCTIONS;
  47011. module.exports.fills = FILLS;
  47012. module.exports.repeats = REPEATS;
  47013. },{"@tweenjs/tween.js":1}],94:[function(_dereq_,module,exports){
  47014. module.exports = {
  47015. AFRAME_INJECTED: 'aframe-injected',
  47016. DEFAULT_CAMERA_HEIGHT: 1.6,
  47017. DEFAULT_HANDEDNESS: 'right',
  47018. animation: _dereq_('./animation'),
  47019. keyboardevent: _dereq_('./keyboardevent')
  47020. };
  47021. },{"./animation":93,"./keyboardevent":95}],95:[function(_dereq_,module,exports){
  47022. module.exports = {
  47023. // Tiny KeyboardEvent.code polyfill.
  47024. KEYCODE_TO_CODE: {
  47025. '38': 'ArrowUp',
  47026. '37': 'ArrowLeft',
  47027. '40': 'ArrowDown',
  47028. '39': 'ArrowRight',
  47029. '87': 'KeyW',
  47030. '65': 'KeyA',
  47031. '83': 'KeyS',
  47032. '68': 'KeyD'
  47033. }
  47034. };
  47035. },{}],96:[function(_dereq_,module,exports){
  47036. var ANode = _dereq_('./a-node');
  47037. var animationConstants = _dereq_('../constants/animation');
  47038. var coordinates = _dereq_('../utils/').coordinates;
  47039. var parseProperty = _dereq_('./schema').parseProperty;
  47040. var registerElement = _dereq_('./a-register-element').registerElement;
  47041. var TWEEN = _dereq_('@tweenjs/tween.js');
  47042. var THREE = _dereq_('../lib/three');
  47043. var utils = _dereq_('../utils/');
  47044. var bind = utils.bind;
  47045. var getComponentProperty = utils.entity.getComponentProperty;
  47046. var DEFAULTS = animationConstants.defaults;
  47047. var DIRECTIONS = animationConstants.directions;
  47048. var EASING_FUNCTIONS = animationConstants.easingFunctions;
  47049. var FILLS = animationConstants.fills;
  47050. var REPEATS = animationConstants.repeats;
  47051. var isCoordinates = coordinates.isCoordinates;
  47052. var warn = utils.debug('core:a-animation:warn');
  47053. var hasLoggedDeprecation = false;
  47054. /**
  47055. * Animation element that applies Tween animation to parent element (entity).
  47056. * Takes after the Web Animations spec.
  47057. *
  47058. * @member {number} count - Decrementing counter for how many cycles of animations left to
  47059. * run.
  47060. * @member {Element} el - Entity which the animation is modifying.
  47061. * @member initialValue - Value before animation started. Used to restore state.
  47062. * @member {bool} isRunning - Whether animation is currently running.
  47063. * @member {function} partialSetAttribute -
  47064. * setAttribute function that is agnostic to whether we are setting an attribute value
  47065. * or a component property value. The el and the attribute names are bundled with
  47066. * the function.
  47067. * @member {object} tween - tween.js object.
  47068. */
  47069. module.exports.AAnimation = registerElement('a-animation', {
  47070. prototype: Object.create(ANode.prototype, {
  47071. createdCallback: {
  47072. value: function () {
  47073. this.bindMethods();
  47074. this.isRunning = false;
  47075. this.partialSetAttribute = function () { /* no-op */ };
  47076. this.tween = null;
  47077. if (!hasLoggedDeprecation) {
  47078. warn('<a-animation> has been deprecated and will be replaced by the animation ' +
  47079. 'component: https://www.npmjs.com/package/aframe-animation-component');
  47080. hasLoggedDeprecation = true;
  47081. }
  47082. }
  47083. },
  47084. attachedCallback: {
  47085. value: function () {
  47086. this.el = this.parentNode;
  47087. this.handleMixinUpdate();
  47088. this.update();
  47089. this.load();
  47090. }
  47091. },
  47092. attributeChangedCallback: {
  47093. value: function (attr, oldVal, newVal) {
  47094. if (!this.hasLoaded || !this.isRunning) { return; }
  47095. this.stop();
  47096. this.handleMixinUpdate();
  47097. this.update();
  47098. }
  47099. },
  47100. detachedCallback: {
  47101. value: function () {
  47102. if (!this.isRunning) { return; }
  47103. this.stop();
  47104. }
  47105. },
  47106. /**
  47107. * Builds a Tween object to handle animations.
  47108. * Uses tween.js's from, to, delay, easing, repeat, onUpdate, and onComplete.
  47109. * Note: tween.js takes objects for its `from` and `to` values.
  47110. *
  47111. * @returns {object}
  47112. */
  47113. getTween: {
  47114. value: function () {
  47115. var self = this;
  47116. var data = self.data;
  47117. var el = self.el;
  47118. var animationValues;
  47119. var attribute = data.attribute;
  47120. var delay = parseInt(data.delay, 10);
  47121. var currentValue = getComponentProperty(el, attribute);
  47122. var direction = self.getDirection(data.direction);
  47123. var easing = EASING_FUNCTIONS[data.easing];
  47124. var fill = data.fill;
  47125. var from;
  47126. var repeat = data.repeat === REPEATS.indefinite ? Infinity : 0;
  47127. var to;
  47128. var toTemp;
  47129. var yoyo = false;
  47130. animationValues = getAnimationValues(el, attribute, data.from || self.initialValue, data.to, currentValue);
  47131. from = animationValues.from;
  47132. to = animationValues.to;
  47133. self.partialSetAttribute = animationValues.partialSetAttribute;
  47134. if (self.count === undefined) {
  47135. self.count = repeat === Infinity ? 0 : parseInt(data.repeat, 10);
  47136. }
  47137. if (isNaN(delay)) { delay = 0; }
  47138. // Store initial state.
  47139. self.initialValue = self.initialValue || cloneValue(currentValue);
  47140. // Handle indefinite + forwards + alternate yoyo edge-case (#405).
  47141. if (repeat === Infinity && fill === FILLS.forwards &&
  47142. [DIRECTIONS.alternate,
  47143. DIRECTIONS.alternateReverse].indexOf(data.direction) !== -1) {
  47144. yoyo = true;
  47145. }
  47146. // If reversing, swap from and to.
  47147. if (direction === DIRECTIONS.reverse) {
  47148. toTemp = to;
  47149. to = cloneValue(from);
  47150. from = cloneValue(toTemp);
  47151. }
  47152. // If fill is backwards or both, start animation at the specified from.
  47153. if ([FILLS.backwards, FILLS.both].indexOf(fill) !== -1) {
  47154. self.partialSetAttribute(from);
  47155. }
  47156. // Create Tween.
  47157. return new TWEEN.Tween(cloneValue(from))
  47158. .to(to, data.dur)
  47159. .delay(delay)
  47160. .easing(easing)
  47161. .repeat(repeat)
  47162. .yoyo(yoyo)
  47163. .onUpdate(function () {
  47164. self.partialSetAttribute(this);
  47165. })
  47166. .onComplete(bind(self.onCompleted, self));
  47167. }
  47168. },
  47169. /**
  47170. * Animation parameters changed. Stop current animation, get a new one, and start it.
  47171. */
  47172. update: {
  47173. value: function () {
  47174. var data = this.data;
  47175. // Terminology warning if infinite used instead of indefinite
  47176. if (data.repeat === 'infinite') {
  47177. console.warn("Using 'infinite' as 'repeat' value is invalid. Use 'indefinite' instead.");
  47178. }
  47179. // Deprecation warning for begin when used as a delay.
  47180. if (data.begin !== '' && !isNaN(data.begin)) {
  47181. console.warn("Using 'begin' to specify a delay is deprecated. Use 'delay' instead.");
  47182. data.delay = data.begin;
  47183. data.begin = '';
  47184. }
  47185. var begin = data.begin;
  47186. var end = data.end;
  47187. // Cancel previous event listeners
  47188. if (this.evt) { this.removeEventListeners(this.evt); }
  47189. // Store new event name.
  47190. this.evt = {begin: begin, end: end};
  47191. // Add new event listeners
  47192. this.addEventListeners(this.evt);
  47193. // If `begin` is not defined, start the animation right away.
  47194. if (begin === '') {
  47195. this.stop();
  47196. this.start();
  47197. }
  47198. },
  47199. writable: window.debug
  47200. },
  47201. /**
  47202. * Callback for when a cycle of an animation is complete. Handles when to completely
  47203. * finish the animation.
  47204. *
  47205. * If `repeat` is set to a value, this method is called after each repeat. Repeats are
  47206. * handled by ending the current animation and creating a new one with `count` updated.
  47207. * Note that this method is *not* called if repeat is set to `indefinite`.
  47208. */
  47209. onCompleted: {
  47210. value: function () {
  47211. var data = this.data;
  47212. this.isRunning = false;
  47213. if ([FILLS.backwards, FILLS.none].indexOf(data.fill) !== -1) {
  47214. this.partialSetAttribute(this.initialValue);
  47215. }
  47216. if (this.count === 0) {
  47217. this.count = undefined;
  47218. this.emit('animationend');
  47219. return;
  47220. }
  47221. this.isRunning = false;
  47222. this.count--;
  47223. this.start();
  47224. }
  47225. },
  47226. start: {
  47227. value: function () {
  47228. var self = this;
  47229. // Postpone animation start until the entity has loaded
  47230. if (!this.el.hasLoaded) {
  47231. this.el.addEventListener('loaded', function () { self.start(); });
  47232. return;
  47233. }
  47234. if (this.isRunning || !this.el.isPlaying) { return; }
  47235. this.tween = this.getTween();
  47236. this.isRunning = true;
  47237. this.tween.start();
  47238. this.emit('animationstart');
  47239. },
  47240. writable: true
  47241. },
  47242. stop: {
  47243. value: function () {
  47244. var tween = this.tween;
  47245. if (!tween) { return; }
  47246. tween.stop();
  47247. this.isRunning = false;
  47248. if ([FILLS.backwards, FILLS.none].indexOf(this.data.fill) !== -1) {
  47249. this.partialSetAttribute(this.initialValue);
  47250. }
  47251. this.emit('animationstop');
  47252. },
  47253. writable: true
  47254. },
  47255. /**
  47256. * Handle alternating directions. Given the current direction, calculate the next one,
  47257. * and store the current one.
  47258. *
  47259. * @param {string} direction
  47260. * @returns {string} Direction that the next individual cycle of the animation will go
  47261. * towards.
  47262. */
  47263. getDirection: {
  47264. value: function (direction) {
  47265. if (direction === DIRECTIONS.alternate) {
  47266. this.prevDirection =
  47267. this.prevDirection === DIRECTIONS.normal ? DIRECTIONS.reverse : DIRECTIONS.normal;
  47268. return this.prevDirection;
  47269. }
  47270. if (direction === DIRECTIONS.alternateReverse) {
  47271. this.prevDirection =
  47272. this.prevDirection === DIRECTIONS.reverse ? DIRECTIONS.normal : DIRECTIONS.reverse;
  47273. return this.prevDirection;
  47274. }
  47275. return direction;
  47276. }
  47277. },
  47278. /**
  47279. * Preemptive binding to attach/detach event listeners (see `update`).
  47280. */
  47281. bindMethods: {
  47282. value: function () {
  47283. this.start = bind(this.start, this);
  47284. this.stop = bind(this.stop, this);
  47285. this.onStateAdded = bind(this.onStateAdded, this);
  47286. this.onStateRemoved = bind(this.onStateRemoved, this);
  47287. }
  47288. },
  47289. addEventListeners: {
  47290. value: function (evts) {
  47291. var el = this.el;
  47292. var self = this;
  47293. utils.splitString(evts.begin).forEach(function (evt) {
  47294. el.addEventListener(evt, self.start);
  47295. });
  47296. utils.splitString(evts.end).forEach(function (evt) {
  47297. el.addEventListener(evt, self.stop);
  47298. });
  47299. // If "begin" is an event name, wait. If it is not defined, start.
  47300. if (evts.begin === '') { el.addEventListener('play', this.start); }
  47301. el.addEventListener('pause', this.stop);
  47302. el.addEventListener('stateadded', this.onStateAdded);
  47303. el.addEventListener('stateremoved', this.onStateRemoved);
  47304. }
  47305. },
  47306. removeEventListeners: {
  47307. value: function (evts) {
  47308. var el = this.el;
  47309. var start = this.start;
  47310. var stop = this.stop;
  47311. utils.splitString(evts.begin).forEach(function (evt) {
  47312. el.removeEventListener(evt, start);
  47313. });
  47314. utils.splitString(evts.end).forEach(function (evt) {
  47315. el.removeEventListener(evt, stop);
  47316. });
  47317. el.removeEventListener('stateadded', this.onStateAdded);
  47318. el.removeEventListener('stateremoved', this.onStateRemoved);
  47319. }
  47320. },
  47321. onStateAdded: {
  47322. value: function (evt) {
  47323. if (evt.detail === this.data.begin) { this.start(); }
  47324. },
  47325. writable: true
  47326. },
  47327. onStateRemoved: {
  47328. value: function (evt) {
  47329. if (evt.detail === this.data.begin) { this.stop(); }
  47330. },
  47331. writable: true
  47332. },
  47333. /**
  47334. * Applies animation data from a mixin element.
  47335. * Works the same as component mixins but reimplemented because animations
  47336. * aren't components.
  47337. */
  47338. handleMixinUpdate: {
  47339. value: function () {
  47340. var data = {};
  47341. var elData;
  47342. var mixinData;
  47343. var mixinEl;
  47344. // Get mixin data.
  47345. mixinEl = document.querySelector('#' + this.getAttribute('mixin'));
  47346. mixinData = mixinEl ? utils.getElData(mixinEl, DEFAULTS) : {};
  47347. elData = utils.getElData(this, DEFAULTS);
  47348. utils.extend(data, DEFAULTS, mixinData, elData);
  47349. this.data = data;
  47350. }
  47351. }
  47352. })
  47353. });
  47354. function cloneValue (val) {
  47355. return utils.extend({}, val);
  47356. }
  47357. /**
  47358. * Deduces different animation values based on whether we are:
  47359. * - animating an inner attribute of a component.
  47360. * - animating a coordinate component.
  47361. * - animating a boolean.
  47362. * - animating a number.
  47363. *
  47364. * @param {Element} el
  47365. * @param {string} attribute - Tells what to animate based on whether it is dot-separated.
  47366. * @param {string} dataFrom - Data `from` value.
  47367. * @param {string} dataTo - Data `to` value.
  47368. * @param currentValue
  47369. * @returns {object}
  47370. * Object with keys [from, to, partialSetAttribute].
  47371. * `from` and `to`
  47372. * Objects where key is attribute being animated and value is value.
  47373. * `partialSetAttribute`
  47374. * Closured-function that tells tween how to update the component.
  47375. */
  47376. function getAnimationValues (el, attribute, dataFrom, dataTo, currentValue) {
  47377. var attributeSplit = attribute.split('.');
  47378. var schema;
  47379. var component;
  47380. var componentPropName;
  47381. var componentName;
  47382. var from = {};
  47383. var partialSetAttribute;
  47384. var to = {};
  47385. if (attributeSplit.length === 2) {
  47386. if (isColor()) {
  47387. getForColorComponent();
  47388. } else {
  47389. getForComponentAttribute();
  47390. }
  47391. } else if (dataTo && isCoordinates(dataTo)) {
  47392. getForCoordinateComponent();
  47393. } else if (['true', 'false'].indexOf(dataTo) !== -1) {
  47394. getForBoolean();
  47395. } else if (isNaN(dataTo)) {
  47396. getForColorComponent();
  47397. } else {
  47398. getForNumber();
  47399. }
  47400. return {
  47401. from: from,
  47402. partialSetAttribute: partialSetAttribute,
  47403. to: to
  47404. };
  47405. /**
  47406. * Match the schema type to color
  47407. * @return {bool} if the schema is of type color
  47408. */
  47409. function isColor () {
  47410. var componentName = attributeSplit[0];
  47411. var propertyName = attributeSplit[1];
  47412. var component = el.components[componentName];
  47413. var schema = component && component.schema;
  47414. return schema && schema[propertyName] && schema[propertyName].type === 'color';
  47415. }
  47416. /**
  47417. * Animating a component that has multiple attributes (e.g., geometry.width).
  47418. */
  47419. function getForComponentAttribute () {
  47420. componentName = attributeSplit[0];
  47421. componentPropName = attributeSplit[1];
  47422. component = el.components[componentName];
  47423. if (!component) {
  47424. el.setAttribute(componentName, '');
  47425. component = el.components[componentName];
  47426. }
  47427. schema = component.schema;
  47428. if (dataFrom === undefined) { // dataFrom can be 0.
  47429. from[attribute] = getComponentProperty(el, attribute);
  47430. } else {
  47431. from[attribute] = dataFrom;
  47432. }
  47433. from[attribute] = parseProperty(from[attribute], schema[componentPropName]);
  47434. to[attribute] = parseProperty(dataTo, schema[componentPropName]);
  47435. partialSetAttribute = function (value) {
  47436. if (!(attribute in value)) { return; }
  47437. el.setAttribute(componentName, componentPropName, value[attribute]);
  47438. };
  47439. }
  47440. /**
  47441. * Animating a component that is an XYZ coordinate (e.g., position).
  47442. * Will be tweening {x, y, z} all at once.
  47443. */
  47444. function getForCoordinateComponent () {
  47445. from = dataFrom ? coordinates.parse(dataFrom) : currentValue;
  47446. to = coordinates.parse(dataTo);
  47447. partialSetAttribute = function (value) {
  47448. el.setAttribute(attribute, value);
  47449. };
  47450. }
  47451. /**
  47452. * Animation a boolean (e.g., visible).
  47453. * Have to convert from boolean to an integer (0 is false, > 0 is true) for tween.
  47454. */
  47455. function getForBoolean () {
  47456. if (dataFrom === undefined) {
  47457. from[attribute] = false;
  47458. } else {
  47459. from[attribute] = strToBool(dataFrom);
  47460. }
  47461. from[attribute] = boolToNum(from[attribute]);
  47462. to[attribute] = boolToNum(strToBool(dataTo));
  47463. partialSetAttribute = function (value) {
  47464. el.setAttribute(attribute, !!value[attribute]);
  47465. };
  47466. }
  47467. /**
  47468. * Animating a color component
  47469. * Will convert a hex value to a THREE.Color
  47470. * Then converts to hex for the setAttribute
  47471. */
  47472. function getForColorComponent () {
  47473. from = new THREE.Color(dataFrom || el.getAttribute(attribute));
  47474. to = new THREE.Color(dataTo);
  47475. partialSetAttribute = function (value) {
  47476. if (attributeSplit.length > 1) {
  47477. el.setAttribute(attributeSplit[0], attributeSplit[1], rgbVectorToHex(value));
  47478. }
  47479. el.setAttribute(attribute, rgbVectorToHex(value));
  47480. };
  47481. }
  47482. /**
  47483. * Animating a numbered attribute (e.g., opacity).
  47484. */
  47485. function getForNumber () {
  47486. if (dataFrom === undefined) { // dataFrom can be 0.
  47487. from[attribute] = parseFloat(el.getAttribute(attribute));
  47488. } else {
  47489. from[attribute] = parseFloat(dataFrom);
  47490. }
  47491. to[attribute] = parseFloat(dataTo);
  47492. partialSetAttribute = function (value) {
  47493. el.setAttribute(attribute, value[attribute]);
  47494. };
  47495. }
  47496. }
  47497. module.exports.getAnimationValues = getAnimationValues;
  47498. /**
  47499. * Converts string to bool.
  47500. *
  47501. * @param {string} str - `true` or `false`.
  47502. * @returns {bool}
  47503. */
  47504. function strToBool (str) {
  47505. if (str === 'true') { return true; }
  47506. return false;
  47507. }
  47508. /**
  47509. * Converts boolean to number.
  47510. *
  47511. * @param {bool}
  47512. * @returns {number}
  47513. */
  47514. function boolToNum (bool) {
  47515. return bool ? 1 : 0;
  47516. }
  47517. /**
  47518. * Converts a number 0-255 to hex
  47519. * @param {number} color number 0 - 255
  47520. * @returns {string} hex value of number bassed
  47521. */
  47522. function componentToHex (color) {
  47523. var hex = color.toString(16);
  47524. return hex.length === 1 ? '0' + hex : hex;
  47525. }
  47526. /**
  47527. * Clamps a number to 0-1
  47528. * Then converts that number to 0-255
  47529. * @param {number} color number 0 - 1
  47530. * @returns {number} color number 0 - 255
  47531. */
  47532. function convertToIntegerColor (color) {
  47533. return Math.floor(Math.min(Math.abs(color), 1) * 255);
  47534. }
  47535. /**
  47536. * Converts a rgb object into a hex string
  47537. * @param {object} color { r: 1, g: 1, b: 1 }
  47538. * @returns {string} hex value #ffffff
  47539. */
  47540. function rgbVectorToHex (color) {
  47541. return '#' + ['r', 'g', 'b'].map(function (prop) {
  47542. return componentToHex(convertToIntegerColor(color[prop]));
  47543. }).join('');
  47544. }
  47545. },{"../constants/animation":93,"../lib/three":151,"../utils/":173,"./a-node":101,"./a-register-element":102,"./schema":111,"@tweenjs/tween.js":1}],97:[function(_dereq_,module,exports){
  47546. var ANode = _dereq_('./a-node');
  47547. var bind = _dereq_('../utils/bind');
  47548. var debug = _dereq_('../utils/debug');
  47549. var registerElement = _dereq_('./a-register-element').registerElement;
  47550. var THREE = _dereq_('../lib/three');
  47551. var fileLoader = new THREE.FileLoader();
  47552. var warn = debug('core:a-assets:warn');
  47553. /**
  47554. * Asset management system. Handles blocking on asset loading.
  47555. */
  47556. module.exports = registerElement('a-assets', {
  47557. prototype: Object.create(ANode.prototype, {
  47558. createdCallback: {
  47559. value: function () {
  47560. this.isAssets = true;
  47561. this.fileLoader = fileLoader;
  47562. this.timeout = null;
  47563. }
  47564. },
  47565. attachedCallback: {
  47566. value: function () {
  47567. var self = this;
  47568. var i;
  47569. var loaded = [];
  47570. var mediaEl;
  47571. var mediaEls;
  47572. var imgEl;
  47573. var imgEls;
  47574. var timeout;
  47575. if (!this.parentNode.isScene) {
  47576. throw new Error('<a-assets> must be a child of a <a-scene>.');
  47577. }
  47578. // Wait for <img>s.
  47579. imgEls = this.querySelectorAll('img');
  47580. for (i = 0; i < imgEls.length; i++) {
  47581. imgEl = fixUpMediaElement(imgEls[i]);
  47582. loaded.push(new Promise(function (resolve, reject) {
  47583. // Set in cache because we won't be needing to call three.js loader if we have.
  47584. // a loaded media element.
  47585. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  47586. imgEl.onload = resolve;
  47587. imgEl.onerror = reject;
  47588. }));
  47589. }
  47590. // Wait for <audio>s and <video>s.
  47591. mediaEls = this.querySelectorAll('audio, video');
  47592. for (i = 0; i < mediaEls.length; i++) {
  47593. mediaEl = fixUpMediaElement(mediaEls[i]);
  47594. if (!mediaEl.src && !mediaEl.srcObject) {
  47595. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  47596. }
  47597. loaded.push(mediaElementLoaded(mediaEl));
  47598. }
  47599. // Trigger loaded for scene to start rendering.
  47600. Promise.all(loaded).then(bind(this.load, this));
  47601. // Timeout to start loading anyways.
  47602. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  47603. this.timeout = setTimeout(function () {
  47604. if (self.hasLoaded) { return; }
  47605. warn('Asset loading timed out in ', timeout, 'ms');
  47606. self.emit('timeout');
  47607. self.load();
  47608. }, timeout);
  47609. }
  47610. },
  47611. detachedCallback: {
  47612. value: function () {
  47613. if (this.timeout) { clearTimeout(this.timeout); }
  47614. }
  47615. },
  47616. load: {
  47617. value: function () {
  47618. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  47619. return el.isAssetItem && el.hasAttribute('src');
  47620. });
  47621. }
  47622. }
  47623. })
  47624. });
  47625. /**
  47626. * Preload using XHRLoader for any type of asset.
  47627. */
  47628. registerElement('a-asset-item', {
  47629. prototype: Object.create(ANode.prototype, {
  47630. createdCallback: {
  47631. value: function () {
  47632. this.data = null;
  47633. this.isAssetItem = true;
  47634. }
  47635. },
  47636. attachedCallback: {
  47637. value: function () {
  47638. var self = this;
  47639. var src = this.getAttribute('src');
  47640. fileLoader.setResponseType(
  47641. this.getAttribute('response-type') || inferResponseType(src));
  47642. fileLoader.load(src, function handleOnLoad (response) {
  47643. self.data = response;
  47644. /*
  47645. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  47646. previous one closes, the second request never finishes.
  47647. setTimeout finishes the first request and lets the logic triggered by load open
  47648. subsequent requests.
  47649. setTimeout can be removed once the fix for the bug below ships:
  47650. 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
  47651. */
  47652. setTimeout(function load () { ANode.prototype.load.call(self); });
  47653. }, function handleOnProgress (xhr) {
  47654. self.emit('progress', {
  47655. loadedBytes: xhr.loaded,
  47656. totalBytes: xhr.total,
  47657. xhr: xhr
  47658. });
  47659. }, function handleOnError (xhr) {
  47660. self.emit('error', {xhr: xhr});
  47661. });
  47662. }
  47663. }
  47664. })
  47665. });
  47666. /**
  47667. * Create a Promise that resolves once the media element has finished buffering.
  47668. *
  47669. * @param {Element} el - HTMLMediaElement.
  47670. * @returns {Promise}
  47671. */
  47672. function mediaElementLoaded (el) {
  47673. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  47674. return;
  47675. }
  47676. // If media specifies autoplay or preload, wait until media is completely buffered.
  47677. return new Promise(function (resolve, reject) {
  47678. if (el.readyState === 4) { return resolve(); } // Already loaded.
  47679. if (el.error) { return reject(); } // Error.
  47680. el.addEventListener('loadeddata', checkProgress, false);
  47681. el.addEventListener('progress', checkProgress, false);
  47682. el.addEventListener('error', reject, false);
  47683. function checkProgress () {
  47684. // Add up the seconds buffered.
  47685. var secondsBuffered = 0;
  47686. for (var i = 0; i < el.buffered.length; i++) {
  47687. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  47688. }
  47689. // Compare seconds buffered to media duration.
  47690. if (secondsBuffered >= el.duration) {
  47691. // Set in cache because we won't be needing to call three.js loader if we have.
  47692. // a loaded media element.
  47693. THREE.Cache.files[el.getAttribute('src')] = el;
  47694. resolve();
  47695. }
  47696. }
  47697. });
  47698. }
  47699. /**
  47700. * Automatically add attributes to media elements where convenient.
  47701. * crossorigin, playsinline.
  47702. */
  47703. function fixUpMediaElement (mediaEl) {
  47704. // Cross-origin.
  47705. var newMediaEl = setCrossOrigin(mediaEl);
  47706. // Plays inline for mobile.
  47707. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  47708. newMediaEl.setAttribute('playsinline', '');
  47709. newMediaEl.setAttribute('webkit-playsinline', '');
  47710. }
  47711. if (newMediaEl !== mediaEl) {
  47712. mediaEl.parentNode.appendChild(newMediaEl);
  47713. mediaEl.parentNode.removeChild(mediaEl);
  47714. }
  47715. return newMediaEl;
  47716. }
  47717. /**
  47718. * Automatically set `crossorigin` if not defined on the media element.
  47719. * If it is not defined, we must create and re-append a new media element <img> and
  47720. * have the browser re-request it with `crossorigin` set.
  47721. *
  47722. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  47723. * @returns {Element} Media element to be used to listen to for loaded events.
  47724. */
  47725. function setCrossOrigin (mediaEl) {
  47726. var newMediaEl;
  47727. var src;
  47728. // Already has crossorigin set.
  47729. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  47730. src = mediaEl.getAttribute('src');
  47731. if (src !== null) {
  47732. // Does not have protocol.
  47733. if (src.indexOf('://') === -1) { return mediaEl; }
  47734. // Determine if cross origin is actually needed.
  47735. if (extractDomain(src) === window.location.host) { return mediaEl; }
  47736. }
  47737. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  47738. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  47739. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  47740. mediaEl.crossOrigin = 'anonymous';
  47741. newMediaEl = mediaEl.cloneNode(true);
  47742. return newMediaEl;
  47743. }
  47744. /**
  47745. * Extract domain out of URL.
  47746. *
  47747. * @param {string} url
  47748. * @returns {string}
  47749. */
  47750. function extractDomain (url) {
  47751. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  47752. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  47753. // Find and remove port number.
  47754. return domain.substring(0, domain.indexOf(':'));
  47755. }
  47756. /**
  47757. * Infer response-type attribute from src.
  47758. * Default is text(default XMLHttpRequest.responseType)
  47759. * but we use arraybuffer for .gltf and .glb files
  47760. * because of THREE.GLTFLoader specification.
  47761. *
  47762. * @param {string} src
  47763. * @returns {string}
  47764. */
  47765. function inferResponseType (src) {
  47766. var dotLastIndex = src.lastIndexOf('.');
  47767. if (dotLastIndex >= 0) {
  47768. var extension = src.slice(dotLastIndex, src.length);
  47769. if (extension === '.gltf' || extension === '.glb') {
  47770. return 'arraybuffer';
  47771. }
  47772. }
  47773. return 'text';
  47774. }
  47775. module.exports.inferResponseType = inferResponseType;
  47776. },{"../lib/three":151,"../utils/bind":167,"../utils/debug":169,"./a-node":101,"./a-register-element":102}],98:[function(_dereq_,module,exports){
  47777. var debug = _dereq_('../utils/debug');
  47778. var registerElement = _dereq_('./a-register-element').registerElement;
  47779. var warn = debug('core:cubemap:warn');
  47780. /**
  47781. * Cubemap element that handles validation and exposes list of URLs.
  47782. * Does not listen to updates.
  47783. */
  47784. module.exports = registerElement('a-cubemap', {
  47785. prototype: Object.create(window.HTMLElement.prototype, {
  47786. /**
  47787. * Calculates this.srcs.
  47788. */
  47789. attachedCallback: {
  47790. value: function () {
  47791. this.srcs = this.validate();
  47792. },
  47793. writable: window.debug
  47794. },
  47795. /**
  47796. * Checks for exactly six elements with [src].
  47797. * Does not check explicitly for <img>s in case user does not want
  47798. * prefetching.
  47799. *
  47800. * @returns {Array|null} - six URLs if valid, else null.
  47801. */
  47802. validate: {
  47803. value: function () {
  47804. var elements = this.querySelectorAll('[src]');
  47805. var i;
  47806. var srcs = [];
  47807. if (elements.length === 6) {
  47808. for (i = 0; i < elements.length; i++) {
  47809. srcs.push(elements[i].getAttribute('src'));
  47810. }
  47811. return srcs;
  47812. }
  47813. // Else if there are not six elements, throw a warning.
  47814. warn(
  47815. '<a-cubemap> did not contain exactly six elements each with a ' +
  47816. '`src` attribute.');
  47817. },
  47818. writable: window.debug
  47819. }
  47820. })
  47821. });
  47822. },{"../utils/debug":169,"./a-register-element":102}],99:[function(_dereq_,module,exports){
  47823. var ANode = _dereq_('./a-node');
  47824. var COMPONENTS = _dereq_('./component').components;
  47825. var registerElement = _dereq_('./a-register-element').registerElement;
  47826. var THREE = _dereq_('../lib/three');
  47827. var utils = _dereq_('../utils/');
  47828. var AEntity;
  47829. var debug = utils.debug('core:a-entity:debug');
  47830. var warn = utils.debug('core:a-entity:warn');
  47831. var MULTIPLE_COMPONENT_DELIMITER = '__';
  47832. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  47833. /**
  47834. * Entity is a container object that components are plugged into to comprise everything in
  47835. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  47836. *
  47837. * To be able to take components, the scene element inherits from the entity definition.
  47838. *
  47839. * @member {object} components - entity's currently initialized components.
  47840. * @member {object} object3D - three.js object.
  47841. * @member {array} states
  47842. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  47843. */
  47844. var proto = Object.create(ANode.prototype, {
  47845. createdCallback: {
  47846. value: function () {
  47847. this.components = {};
  47848. // To avoid double initializations and infinite loops.
  47849. this.initializingComponents = {};
  47850. this.componentsToUpdate = {};
  47851. this.isEntity = true;
  47852. this.isPlaying = false;
  47853. this.object3D = new THREE.Group();
  47854. this.object3D.el = this;
  47855. this.object3DMap = {};
  47856. this.parentEl = null;
  47857. this.rotationObj = {};
  47858. this.states = [];
  47859. }
  47860. },
  47861. /**
  47862. * Handle changes coming from the browser DOM inspector.
  47863. */
  47864. attributeChangedCallback: {
  47865. value: function (attr, oldVal, newVal) {
  47866. var component = this.components[attr];
  47867. // If the empty string is passed by the component initialization
  47868. // logic we ignore the component update.
  47869. if (component && component.justInitialized && newVal === '') {
  47870. delete component.justInitialized;
  47871. return;
  47872. }
  47873. // When a component is removed after calling el.removeAttribute('material')
  47874. if (!component && newVal === null) { return; }
  47875. this.setEntityAttribute(attr, oldVal, newVal);
  47876. }
  47877. },
  47878. /**
  47879. * Add to parent, load, play.
  47880. */
  47881. attachedCallback: {
  47882. value: function () {
  47883. var assetsEl; // Asset management system element.
  47884. var sceneEl = this.sceneEl;
  47885. var self = this; // Component.
  47886. this.addToParent();
  47887. // Don't .load() scene on attachedCallback.
  47888. if (this.isScene) { return; }
  47889. // Gracefully not error when outside of <a-scene> (e.g., tests).
  47890. if (!sceneEl) {
  47891. this.load();
  47892. return;
  47893. }
  47894. // Wait for asset management system to finish before loading.
  47895. assetsEl = sceneEl.querySelector('a-assets');
  47896. if (assetsEl && !assetsEl.hasLoaded) {
  47897. assetsEl.addEventListener('loaded', function () { self.load(); });
  47898. return;
  47899. }
  47900. this.load();
  47901. }
  47902. },
  47903. /**
  47904. * Tell parent to remove this element's object3D from its object3D.
  47905. * Do not call on scene element because that will cause a call to document.body.remove().
  47906. */
  47907. detachedCallback: {
  47908. value: function () {
  47909. var componentName;
  47910. if (!this.parentEl) { return; }
  47911. // Remove components.
  47912. for (componentName in this.components) { this.removeComponent(componentName); }
  47913. if (this.isScene) { return; }
  47914. this.removeFromParent();
  47915. ANode.prototype.detachedCallback.call(this);
  47916. // Remove cyclic reference.
  47917. this.object3D.el = null;
  47918. }
  47919. },
  47920. /**
  47921. * Apply mixin to component.
  47922. */
  47923. handleMixinUpdate: {
  47924. value: function (attrName) {
  47925. if (!attrName) {
  47926. this.updateComponents();
  47927. return;
  47928. }
  47929. this.updateComponent(attrName, this.getDOMAttribute(attrName));
  47930. }
  47931. },
  47932. getObject3D: {
  47933. value: function (type) {
  47934. return this.object3DMap[type];
  47935. }
  47936. },
  47937. /**
  47938. * Set a THREE.Object3D into the map.
  47939. *
  47940. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  47941. * @param {object} obj - A THREE.Object3D.
  47942. */
  47943. setObject3D: {
  47944. value: function (type, obj) {
  47945. var oldObj;
  47946. var self = this;
  47947. if (!(obj instanceof THREE.Object3D)) {
  47948. throw new Error(
  47949. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  47950. 'THREE.Object3D.'
  47951. );
  47952. }
  47953. // Remove existing object of the type.
  47954. oldObj = this.getObject3D(type);
  47955. if (oldObj) { this.object3D.remove(oldObj); }
  47956. // Set references to A-Frame entity.
  47957. obj.el = this;
  47958. if (obj.children.length) {
  47959. obj.traverse(function bindEl (child) {
  47960. child.el = self;
  47961. });
  47962. }
  47963. // Add.
  47964. this.object3D.add(obj);
  47965. this.object3DMap[type] = obj;
  47966. this.emit('object3dset', {object: obj, type: type});
  47967. }
  47968. },
  47969. /**
  47970. * Remove object from scene and entity object3D map.
  47971. */
  47972. removeObject3D: {
  47973. value: function (type) {
  47974. var obj = this.getObject3D(type);
  47975. if (!obj) {
  47976. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  47977. return;
  47978. }
  47979. this.object3D.remove(obj);
  47980. delete this.object3DMap[type];
  47981. this.emit('object3dremove', {type: type});
  47982. }
  47983. },
  47984. /**
  47985. * Gets or creates an object3D of a given type.
  47986. *
  47987. * @param {string} type - Type of the object3D.
  47988. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  47989. * @returns {object}
  47990. */
  47991. getOrCreateObject3D: {
  47992. value: function (type, Constructor) {
  47993. var object3D = this.getObject3D(type);
  47994. if (!object3D && Constructor) {
  47995. object3D = new Constructor();
  47996. this.setObject3D(type, object3D);
  47997. }
  47998. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  47999. 'and `object3dset` event instead.');
  48000. return object3D;
  48001. }
  48002. },
  48003. /**
  48004. * Add child entity.
  48005. *
  48006. * @param {Element} el - Child entity.
  48007. */
  48008. add: {
  48009. value: function (el) {
  48010. if (!el.object3D) {
  48011. throw new Error("Trying to add an element that doesn't have an `object3D`");
  48012. }
  48013. this.object3D.add(el.object3D);
  48014. this.emit('child-attached', {el: el});
  48015. }
  48016. },
  48017. /**
  48018. * Tell parentNode to add this entity to itself.
  48019. */
  48020. addToParent: {
  48021. value: function () {
  48022. var parentNode = this.parentEl = this.parentNode;
  48023. // `!parentNode` check primarily for unit tests.
  48024. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  48025. parentNode.add(this);
  48026. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  48027. }
  48028. },
  48029. /**
  48030. * Tell parentNode to remove this entity from itself.
  48031. */
  48032. removeFromParent: {
  48033. value: function () {
  48034. var parentEl = this.parentEl;
  48035. this.parentEl.remove(this);
  48036. this.attachedToParent = false;
  48037. this.parentEl = null;
  48038. parentEl.emit('child-detached', {el: this});
  48039. }
  48040. },
  48041. load: {
  48042. value: function () {
  48043. var self = this;
  48044. if (this.hasLoaded || !this.parentEl) { return; }
  48045. ANode.prototype.load.call(this, function entityLoadCallback () {
  48046. // Check if entity was detached while it was waiting to load.
  48047. if (!self.parentEl) { return; }
  48048. self.updateComponents();
  48049. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  48050. });
  48051. },
  48052. writable: window.debug
  48053. },
  48054. /**
  48055. * Remove child entity.
  48056. *
  48057. * @param {Element} el - Child entity.
  48058. */
  48059. remove: {
  48060. value: function (el) {
  48061. this.object3D.remove(el.object3D);
  48062. }
  48063. },
  48064. /**
  48065. * @returns {array} Direct children that are entities.
  48066. */
  48067. getChildEntities: {
  48068. value: function () {
  48069. var children = this.children;
  48070. var childEntities = [];
  48071. for (var i = 0; i < children.length; i++) {
  48072. var child = children[i];
  48073. if (child instanceof AEntity) {
  48074. childEntities.push(child);
  48075. }
  48076. }
  48077. return childEntities;
  48078. }
  48079. },
  48080. /**
  48081. * Initialize component.
  48082. *
  48083. * @param {string} attrName - Attribute name asociated to the component.
  48084. * @param {object} data - Component data
  48085. * @param {boolean} isDependency - True if the component is a dependency.
  48086. */
  48087. initComponent: {
  48088. value: function (attrName, data, isDependency) {
  48089. var component;
  48090. var componentId;
  48091. var componentInfo;
  48092. var componentName;
  48093. var isComponentDefined;
  48094. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  48095. componentId = componentInfo[1];
  48096. componentName = componentInfo[0];
  48097. // Not a registered component.
  48098. if (!COMPONENTS[componentName]) { return; }
  48099. // Component is not a dependency and is undefined.
  48100. // If a component is a dependency, then it is okay to have no data.
  48101. isComponentDefined = checkComponentDefined(this, attrName) ||
  48102. data !== undefined;
  48103. if (!isComponentDefined && !isDependency) { return; }
  48104. // Component already initialized.
  48105. if (attrName in this.components) { return; }
  48106. // Initialize dependencies first
  48107. this.initComponentDependencies(componentName);
  48108. // If component name has an id we check component type multiplic
  48109. if (componentId && !COMPONENTS[componentName].multiple) {
  48110. throw new Error('Trying to initialize multiple ' +
  48111. 'components of type `' + componentName +
  48112. '`. There can only be one component of this type per entity.');
  48113. }
  48114. component = new COMPONENTS[componentName].Component(this, data, componentId);
  48115. if (this.isPlaying) { component.play(); }
  48116. // Components are reflected in the DOM as attributes but the state is not shown
  48117. // hence we set the attribute to empty string.
  48118. // The flag justInitialized is for attributeChangedCallback to not overwrite
  48119. // the component with the empty string.
  48120. if (!this.hasAttribute(attrName)) {
  48121. component.justInitialized = true;
  48122. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  48123. }
  48124. debug('Component initialized: %s', attrName);
  48125. },
  48126. writable: window.debug
  48127. },
  48128. /**
  48129. * Initialize dependencies of a component.
  48130. *
  48131. * @param {string} name - Root component name.
  48132. */
  48133. initComponentDependencies: {
  48134. value: function (name) {
  48135. var self = this;
  48136. var component = COMPONENTS[name];
  48137. var dependencies;
  48138. var i;
  48139. // Not a component.
  48140. if (!component) { return; }
  48141. // No dependencies.
  48142. dependencies = COMPONENTS[name].dependencies;
  48143. if (!dependencies) { return; }
  48144. // Initialize dependencies.
  48145. for (i = 0; i < dependencies.length; i++) {
  48146. // Call getAttribute to initialize the data from the DOM.
  48147. self.initComponent(
  48148. dependencies[i],
  48149. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  48150. true
  48151. );
  48152. }
  48153. }
  48154. },
  48155. removeComponent: {
  48156. value: function (name) {
  48157. var component;
  48158. component = this.components[name];
  48159. if (!component) { return; }
  48160. // Wait for component to initialize.
  48161. if (!component.initialized) {
  48162. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  48163. if (evt.detail.name !== name) { return; }
  48164. this.removeComponent(name);
  48165. this.removeEventListener('componentinitialized', tryRemoveLater);
  48166. });
  48167. return;
  48168. }
  48169. component.pause();
  48170. component.remove();
  48171. delete this.components[name];
  48172. this.emit('componentremoved', component.evtDetail);
  48173. },
  48174. writable: window.debug
  48175. },
  48176. /**
  48177. * Initialize or update all components.
  48178. * Build data using initial components, defined attributes, mixins, and defaults.
  48179. * Update default components before the rest.
  48180. *
  48181. * @member {function} getExtraComponents - Can be implemented to include component data
  48182. * from other sources (e.g., implemented by primitives).
  48183. */
  48184. updateComponents: {
  48185. value: function () {
  48186. var data;
  48187. var extraComponents;
  48188. var i;
  48189. var name;
  48190. var componentsToUpdate = this.componentsToUpdate;
  48191. if (!this.hasLoaded) { return; }
  48192. // Gather mixin-defined components.
  48193. for (i = 0; i < this.mixinEls.length; i++) {
  48194. for (name in this.mixinEls[i].componentCache) {
  48195. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48196. }
  48197. }
  48198. // Gather from extra initial component data if defined (e.g., primitives).
  48199. if (this.getExtraComponents) {
  48200. extraComponents = this.getExtraComponents();
  48201. for (name in extraComponents) {
  48202. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48203. }
  48204. }
  48205. // Gather entity-defined components.
  48206. for (i = 0; i < this.attributes.length; ++i) {
  48207. name = this.attributes[i].name;
  48208. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  48209. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48210. }
  48211. // object3D components first (position, rotation, scale, visible).
  48212. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  48213. name = OBJECT3D_COMPONENTS[i];
  48214. if (!this.hasAttribute(name)) { continue; }
  48215. this.updateComponent(name, this.getDOMAttribute(name));
  48216. }
  48217. // Initialize or update rest of components.
  48218. for (name in componentsToUpdate) {
  48219. data = mergeComponentData(this.getDOMAttribute(name),
  48220. extraComponents && extraComponents[name]);
  48221. this.updateComponent(name, data);
  48222. delete componentsToUpdate[name];
  48223. }
  48224. },
  48225. writable: window.debug
  48226. },
  48227. /**
  48228. * Initialize, update, or remove a single component.
  48229. *
  48230. * When initializing, we set the component on `this.components`.
  48231. *
  48232. * @param {string} attr - Component name.
  48233. * @param {object} attrValue - Value of the DOM attribute.
  48234. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  48235. */
  48236. updateComponent: {
  48237. value: function (attr, attrValue, clobber) {
  48238. var component = this.components[attr];
  48239. if (component) {
  48240. // Remove component.
  48241. if (attrValue === null && !checkComponentDefined(this, attr)) {
  48242. this.removeComponent(attr);
  48243. return;
  48244. }
  48245. // Component already initialized. Update component.
  48246. component.updateProperties(attrValue, clobber);
  48247. return;
  48248. }
  48249. // Component not yet initialized. Initialize component.
  48250. this.initComponent(attr, attrValue, false);
  48251. }
  48252. },
  48253. /**
  48254. * If `attr` is a component name, detach the component from the entity.
  48255. *
  48256. * If `propertyName` is given, reset the component property value to its default.
  48257. *
  48258. * @param {string} attr - Attribute name, which could also be a component name.
  48259. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  48260. */
  48261. removeAttribute: {
  48262. value: function (attr, propertyName) {
  48263. var component = this.components[attr];
  48264. // Remove component.
  48265. if (component && propertyName === undefined) {
  48266. this.removeComponent(attr);
  48267. }
  48268. // Reset component property value.
  48269. if (component && propertyName !== undefined) {
  48270. component.resetProperty(propertyName);
  48271. return;
  48272. }
  48273. // Remove mixins.
  48274. if (attr === 'mixin') {
  48275. this.mixinUpdate('');
  48276. }
  48277. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  48278. }
  48279. },
  48280. /**
  48281. * Start dynamic behavior associated with entity such as dynamic components and animations.
  48282. * Tell all children entities to also play.
  48283. */
  48284. play: {
  48285. value: function () {
  48286. var entities;
  48287. var i;
  48288. var key;
  48289. // Already playing.
  48290. if (this.isPlaying || !this.hasLoaded) { return; }
  48291. this.isPlaying = true;
  48292. // Wake up all components.
  48293. for (key in this.components) { this.components[key].play(); }
  48294. // Tell all child entities to play.
  48295. entities = this.getChildEntities();
  48296. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  48297. this.emit('play');
  48298. },
  48299. writable: true
  48300. },
  48301. /**
  48302. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  48303. * Tell all children entities to also pause.
  48304. */
  48305. pause: {
  48306. value: function () {
  48307. var entities;
  48308. var i;
  48309. var key;
  48310. if (!this.isPlaying) { return; }
  48311. this.isPlaying = false;
  48312. // Sleep all components.
  48313. for (key in this.components) { this.components[key].pause(); }
  48314. // Tell all child entities to pause.
  48315. entities = this.getChildEntities();
  48316. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  48317. this.emit('pause');
  48318. },
  48319. writable: true
  48320. },
  48321. /**
  48322. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  48323. *
  48324. * @param {string} attr
  48325. * @param {string} oldVal
  48326. * @param {string|object} newVal
  48327. */
  48328. setEntityAttribute: {
  48329. value: function (attr, oldVal, newVal) {
  48330. if (COMPONENTS[attr] || this.components[attr]) {
  48331. this.updateComponent(attr, newVal);
  48332. return;
  48333. }
  48334. if (attr === 'mixin') {
  48335. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  48336. if (newVal === this.computedMixinStr) { return; }
  48337. this.mixinUpdate(newVal, oldVal);
  48338. }
  48339. }
  48340. },
  48341. mixinUpdate: {
  48342. value: function (newMixins, oldMixins) {
  48343. oldMixins = oldMixins || this.getAttribute('mixin');
  48344. this.updateMixins(newMixins, oldMixins);
  48345. this.updateComponents();
  48346. }
  48347. },
  48348. /**
  48349. * setAttribute can:
  48350. *
  48351. * 1. Set a single property of a multi-property component.
  48352. * 2. Set multiple properties of a multi-property component.
  48353. * 3. Replace properties of a multi-property component.
  48354. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  48355. *
  48356. * @param {string} attrName - Component or attribute name.
  48357. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  48358. * object of properties.
  48359. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  48360. * it is a boolean indicating whether to clobber previous values (defaults to false).
  48361. */
  48362. setAttribute: {
  48363. value: function (attrName, arg1, arg2) {
  48364. var newAttrValue;
  48365. var clobber;
  48366. var componentName;
  48367. var delimiterIndex;
  48368. var isDebugMode;
  48369. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  48370. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  48371. // Not a component. Normal set attribute.
  48372. if (!COMPONENTS[componentName]) {
  48373. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  48374. ANode.prototype.setAttribute.call(this, attrName, arg1);
  48375. return;
  48376. }
  48377. // Initialize component first if not yet initialized.
  48378. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  48379. this.updateComponent(attrName,
  48380. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  48381. }
  48382. // Determine new attributes from the arguments
  48383. if (typeof arg2 !== 'undefined' &&
  48384. typeof arg1 === 'string' &&
  48385. arg1.length > 0 &&
  48386. typeof utils.styleParser.parse(arg1) === 'string') {
  48387. // Update a single property of a multi-property component
  48388. newAttrValue = {};
  48389. newAttrValue[arg1] = arg2;
  48390. clobber = false;
  48391. } else {
  48392. // Update with a value, object, or CSS-style property string, with the possiblity
  48393. // of clobbering previous values.
  48394. newAttrValue = arg1;
  48395. clobber = (arg2 === true);
  48396. }
  48397. // Update component
  48398. this.updateComponent(attrName, newAttrValue, clobber);
  48399. // In debug mode, write component data up to the DOM.
  48400. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  48401. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  48402. },
  48403. writable: window.debug
  48404. },
  48405. /**
  48406. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  48407. *
  48408. * @param {bool} recursive - Also flushToDOM on the children.
  48409. **/
  48410. flushToDOM: {
  48411. value: function (recursive) {
  48412. var components = this.components;
  48413. var child;
  48414. var children = this.children;
  48415. var i;
  48416. var key;
  48417. // Flush entity's components to DOM.
  48418. for (key in components) {
  48419. components[key].flushToDOM();
  48420. }
  48421. // Recurse.
  48422. if (!recursive) { return; }
  48423. for (i = 0; i < children.length; ++i) {
  48424. child = children[i];
  48425. if (!child.flushToDOM) { continue; }
  48426. child.flushToDOM(recursive);
  48427. }
  48428. }
  48429. },
  48430. /**
  48431. * If `attr` is a component, returns ALL component data including applied mixins and
  48432. * defaults.
  48433. *
  48434. * If `attr` is not a component, fall back to HTML getAttribute.
  48435. *
  48436. * @param {string} attr
  48437. * @returns {object|string} Object if component, else string.
  48438. */
  48439. getAttribute: {
  48440. value: function (attr) {
  48441. // If component, return component data.
  48442. var component;
  48443. if (attr === 'position') { return this.object3D.position; }
  48444. if (attr === 'rotation') { return getRotation(this); }
  48445. if (attr === 'scale') { return this.object3D.scale; }
  48446. if (attr === 'visible') { return this.object3D.visible; }
  48447. component = this.components[attr];
  48448. if (component) { return component.data; }
  48449. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  48450. },
  48451. writable: window.debug
  48452. },
  48453. /**
  48454. * If `attr` is a component, returns JUST the component data defined on the entity.
  48455. * Like a partial version of `getComputedAttribute` as returned component data
  48456. * does not include applied mixins or defaults.
  48457. *
  48458. * If `attr` is not a component, fall back to HTML getAttribute.
  48459. *
  48460. * @param {string} attr
  48461. * @returns {object|string} Object if component, else string.
  48462. */
  48463. getDOMAttribute: {
  48464. value: function (attr) {
  48465. // If cached value exists, return partial component data.
  48466. var component = this.components[attr];
  48467. if (component) { return component.attrValue; }
  48468. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  48469. },
  48470. writable: window.debug
  48471. },
  48472. addState: {
  48473. value: function (state) {
  48474. if (this.is(state)) { return; }
  48475. this.states.push(state);
  48476. this.emit('stateadded', state);
  48477. }
  48478. },
  48479. removeState: {
  48480. value: function (state) {
  48481. var stateIndex = this.states.indexOf(state);
  48482. if (stateIndex === -1) { return; }
  48483. this.states.splice(stateIndex, 1);
  48484. this.emit('stateremoved', state);
  48485. }
  48486. },
  48487. /**
  48488. * Checks if the element is in a given state. e.g. el.is('alive');
  48489. * @type {string} state - Name of the state we want to check
  48490. */
  48491. is: {
  48492. value: function (state) {
  48493. return this.states.indexOf(state) !== -1;
  48494. }
  48495. }
  48496. });
  48497. /**
  48498. * Check if a component is *defined* for an entity, including defaults and mixins.
  48499. * Does not check whether the component has been *initialized* for an entity.
  48500. *
  48501. * @param {string} el - Entity.
  48502. * @param {string} name - Component name.
  48503. * @returns {boolean}
  48504. */
  48505. function checkComponentDefined (el, name) {
  48506. // Check if element contains the component.
  48507. if (el.components[name] && el.components[name].attrValue) { return true; }
  48508. return isComponentMixedIn(name, el.mixinEls);
  48509. }
  48510. /**
  48511. * Check if any mixins contains a component.
  48512. *
  48513. * @param {string} name - Component name.
  48514. * @param {array} mixinEls - Array of <a-mixin>s.
  48515. */
  48516. function isComponentMixedIn (name, mixinEls) {
  48517. var i;
  48518. var inMixin = false;
  48519. for (i = 0; i < mixinEls.length; ++i) {
  48520. inMixin = mixinEls[i].hasAttribute(name);
  48521. if (inMixin) { break; }
  48522. }
  48523. return inMixin;
  48524. }
  48525. /**
  48526. * Given entity defined value, merge in extra data if necessary.
  48527. * Handle both single and multi-property components.
  48528. *
  48529. * @param {string} attrValue - Entity data.
  48530. * @param extraData - Entity data from another source to merge in.
  48531. */
  48532. function mergeComponentData (attrValue, extraData) {
  48533. // Extra data not defined, just return attrValue.
  48534. if (!extraData) { return attrValue; }
  48535. // Merge multi-property data.
  48536. if (extraData.constructor === Object) {
  48537. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  48538. }
  48539. // Return data, precendence to the defined value.
  48540. return attrValue || extraData;
  48541. }
  48542. function isComponent (componentName) {
  48543. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  48544. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  48545. }
  48546. if (!COMPONENTS[componentName]) { return false; }
  48547. return true;
  48548. }
  48549. function getRotation (entityEl) {
  48550. var radToDeg = THREE.Math.radToDeg;
  48551. var rotation = entityEl.object3D.rotation;
  48552. var rotationObj = entityEl.rotationObj;
  48553. rotationObj.x = radToDeg(rotation.x);
  48554. rotationObj.y = radToDeg(rotation.y);
  48555. rotationObj.z = radToDeg(rotation.z);
  48556. return rotationObj;
  48557. }
  48558. AEntity = registerElement('a-entity', {prototype: proto});
  48559. module.exports = AEntity;
  48560. },{"../lib/three":151,"../utils/":173,"./a-node":101,"./a-register-element":102,"./component":103}],100:[function(_dereq_,module,exports){
  48561. var ANode = _dereq_('./a-node');
  48562. var registerElement = _dereq_('./a-register-element').registerElement;
  48563. var components = _dereq_('./component').components;
  48564. var utils = _dereq_('../utils');
  48565. var MULTIPLE_COMPONENT_DELIMITER = '__';
  48566. /**
  48567. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  48568. * are component names and the values are already parsed by the component.
  48569. */
  48570. module.exports = registerElement('a-mixin', {
  48571. prototype: Object.create(ANode.prototype, {
  48572. createdCallback: {
  48573. value: function () {
  48574. this.componentCache = {};
  48575. this.id = this.getAttribute('id');
  48576. this.isMixin = true;
  48577. }
  48578. },
  48579. attributeChangedCallback: {
  48580. value: function (attr, oldVal, newVal) {
  48581. this.cacheAttribute(attr, newVal);
  48582. }
  48583. },
  48584. attachedCallback: {
  48585. value: function () {
  48586. this.sceneEl = this.closestScene();
  48587. this.cacheAttributes();
  48588. this.updateEntities();
  48589. this.load();
  48590. }
  48591. },
  48592. /**
  48593. * setAttribute that parses and caches component values.
  48594. */
  48595. setAttribute: {
  48596. value: function (attr, value) {
  48597. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  48598. this.cacheAttribute(attr, value);
  48599. }
  48600. },
  48601. /**
  48602. * If `attr` is a component, then parse the value using the schema and store it.
  48603. */
  48604. cacheAttribute: {
  48605. value: function (attr, value) {
  48606. var component;
  48607. var componentName;
  48608. // Get component data.
  48609. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  48610. component = components[componentName];
  48611. if (!component) { return; }
  48612. if (value === undefined) {
  48613. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  48614. }
  48615. this.componentCache[attr] = component.parseAttrValueForCache(value);
  48616. }
  48617. },
  48618. /**
  48619. * If `attr` is a component, then grab pre-parsed value from the cache.
  48620. * Else do a normal getAttribute.
  48621. */
  48622. getAttribute: {
  48623. value: function (attr) {
  48624. return this.componentCache[attr] ||
  48625. window.HTMLElement.prototype.getAttribute.call(this, attr);
  48626. }
  48627. },
  48628. /**
  48629. * Parse and cache every component defined on the mixin.
  48630. */
  48631. cacheAttributes: {
  48632. value: function () {
  48633. var attributes = this.attributes;
  48634. var attrName;
  48635. var i;
  48636. for (i = 0; i < attributes.length; i++) {
  48637. attrName = attributes[i].name;
  48638. this.cacheAttribute(attrName);
  48639. }
  48640. }
  48641. },
  48642. /**
  48643. * For entities that already have been loaded by the time the mixin was attached, tell
  48644. * those entities to register the mixin and refresh their component data.
  48645. */
  48646. updateEntities: {
  48647. value: function () {
  48648. var entity;
  48649. var entities;
  48650. var i;
  48651. if (!this.sceneEl) { return; }
  48652. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  48653. for (i = 0; i < entities.length; i++) {
  48654. entity = entities[i];
  48655. if (!entity.hasLoaded || entity.isMixin) { continue; }
  48656. entity.mixinUpdate(this.id);
  48657. }
  48658. }
  48659. }
  48660. })
  48661. });
  48662. },{"../utils":173,"./a-node":101,"./a-register-element":102,"./component":103}],101:[function(_dereq_,module,exports){
  48663. /* global CustomEvent, MutationObserver */
  48664. var registerElement = _dereq_('./a-register-element').registerElement;
  48665. var isNode = _dereq_('./a-register-element').isNode;
  48666. var utils = _dereq_('../utils/');
  48667. var warn = utils.debug('core:a-node:warn');
  48668. var MIXIN_OBSERVER_CONFIG = {attributes: true};
  48669. /**
  48670. * Base class for A-Frame that manages loading of objects.
  48671. *
  48672. * Nodes can be modified using mixins.
  48673. * Nodes emit a `loaded` event when they and their children have initialized.
  48674. */
  48675. module.exports = registerElement('a-node', {
  48676. prototype: Object.create(window.HTMLElement.prototype, {
  48677. createdCallback: {
  48678. value: function () {
  48679. this.computedMixinStr = '';
  48680. this.hasLoaded = false;
  48681. this.isNode = true;
  48682. this.mixinEls = [];
  48683. this.mixinObservers = {};
  48684. },
  48685. writable: window.debug
  48686. },
  48687. attachedCallback: {
  48688. value: function () {
  48689. var mixins;
  48690. this.sceneEl = this.closestScene();
  48691. if (!this.sceneEl) {
  48692. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  48693. 'scene. Append this element to `<a-scene>` instead.');
  48694. }
  48695. this.hasLoaded = false;
  48696. this.emit('nodeready', undefined, false);
  48697. if (!this.isMixin) {
  48698. mixins = this.getAttribute('mixin');
  48699. if (mixins) { this.updateMixins(mixins); }
  48700. }
  48701. },
  48702. writable: window.debug
  48703. },
  48704. /**
  48705. * Handle mixin.
  48706. */
  48707. attributeChangedCallback: {
  48708. value: function (attr, oldVal, newVal) {
  48709. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  48710. if (newVal === this.computedMixinStr) { return; }
  48711. if (attr === 'mixin' && !this.isMixin) {
  48712. this.updateMixins(newVal, oldVal);
  48713. }
  48714. }
  48715. },
  48716. /**
  48717. * Returns the first scene by traversing up the tree starting from and
  48718. * including receiver element.
  48719. */
  48720. closestScene: {
  48721. value: function closest () {
  48722. var element = this;
  48723. while (element) {
  48724. if (element.isScene) { break; }
  48725. element = element.parentElement;
  48726. }
  48727. return element;
  48728. }
  48729. },
  48730. /**
  48731. * Returns first element matching a selector by traversing up the tree starting
  48732. * from and including receiver element.
  48733. *
  48734. * @param {string} selector - Selector of element to find.
  48735. */
  48736. closest: {
  48737. value: function closest (selector) {
  48738. var matches = this.matches || this.mozMatchesSelector ||
  48739. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  48740. var element = this;
  48741. while (element) {
  48742. if (matches.call(element, selector)) { break; }
  48743. element = element.parentElement;
  48744. }
  48745. return element;
  48746. }
  48747. },
  48748. detachedCallback: {
  48749. value: function () {
  48750. this.hasLoaded = false;
  48751. }
  48752. },
  48753. /**
  48754. * Wait for children to load, if any.
  48755. * Then emit `loaded` event and set `hasLoaded`.
  48756. */
  48757. load: {
  48758. value: function (cb, childFilter) {
  48759. var children;
  48760. var childrenLoaded;
  48761. var self = this;
  48762. if (this.hasLoaded) { return; }
  48763. // Default to waiting for all nodes.
  48764. childFilter = childFilter || isNode;
  48765. // Wait for children to load (if any), then load.
  48766. children = this.getChildren();
  48767. childrenLoaded = children.filter(childFilter).map(function (child) {
  48768. return new Promise(function waitForLoaded (resolve) {
  48769. if (child.hasLoaded) { return resolve(); }
  48770. child.addEventListener('loaded', resolve);
  48771. });
  48772. });
  48773. Promise.all(childrenLoaded).then(function emitLoaded () {
  48774. self.hasLoaded = true;
  48775. if (cb) { cb(); }
  48776. self.emit('loaded', undefined, false);
  48777. });
  48778. },
  48779. writable: true
  48780. },
  48781. getChildren: {
  48782. value: function () {
  48783. return Array.prototype.slice.call(this.children, 0);
  48784. }
  48785. },
  48786. /**
  48787. * Unregister old mixins and listeners.
  48788. * Register new mixins and listeners.
  48789. * Registering means to update `this.mixinEls` with listeners.
  48790. */
  48791. updateMixins: {
  48792. value: (function () {
  48793. var newMixinIdArray = [];
  48794. var oldMixinIdArray = [];
  48795. return function (newMixins, oldMixins) {
  48796. var i;
  48797. var newMixinIds;
  48798. var oldMixinIds;
  48799. newMixinIdArray.length = 0;
  48800. oldMixinIdArray.length = 0;
  48801. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  48802. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  48803. // Unregister old mixins.
  48804. for (i = 0; i < oldMixinIds.length; i++) {
  48805. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  48806. this.unregisterMixin(oldMixinIds[i]);
  48807. }
  48808. }
  48809. // Register new mixins.
  48810. this.computedMixinStr = '';
  48811. this.mixinEls.length = 0;
  48812. for (i = 0; i < newMixinIds.length; i++) {
  48813. this.registerMixin(document.getElementById(newMixinIds[i]));
  48814. }
  48815. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  48816. // update.
  48817. if (this.computedMixinStr) {
  48818. this.computedMixinStr = this.computedMixinStr.trim();
  48819. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  48820. this.computedMixinStr);
  48821. }
  48822. };
  48823. })()
  48824. },
  48825. /**
  48826. * From mixin ID, add mixin element to `mixinEls`.
  48827. *
  48828. * @param {Element} mixinEl
  48829. */
  48830. registerMixin: {
  48831. value: function (mixinEl) {
  48832. var compositedMixinIds;
  48833. var i;
  48834. var mixin;
  48835. if (!mixinEl) { return; }
  48836. // Register composited mixins (if mixin has mixins).
  48837. mixin = mixinEl.getAttribute('mixin');
  48838. if (mixin) {
  48839. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  48840. for (i = 0; i < compositedMixinIds.length; i++) {
  48841. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  48842. }
  48843. }
  48844. // Register mixin.
  48845. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  48846. this.mixinEls.push(mixinEl);
  48847. this.attachMixinListener(mixinEl);
  48848. }
  48849. },
  48850. setAttribute: {
  48851. value: function (attr, newValue) {
  48852. if (attr === 'mixin') { this.updateMixins(newValue); }
  48853. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  48854. }
  48855. },
  48856. unregisterMixin: {
  48857. value: function (mixinId) {
  48858. var i;
  48859. var mixinEls = this.mixinEls;
  48860. var mixinEl;
  48861. for (i = 0; i < mixinEls.length; ++i) {
  48862. mixinEl = mixinEls[i];
  48863. if (mixinId === mixinEl.id) {
  48864. mixinEls.splice(i, 1);
  48865. break;
  48866. }
  48867. }
  48868. this.removeMixinListener(mixinId);
  48869. }
  48870. },
  48871. removeMixinListener: {
  48872. value: function (mixinId) {
  48873. var observer = this.mixinObservers[mixinId];
  48874. if (!observer) { return; }
  48875. observer.disconnect();
  48876. this.mixinObservers[mixinId] = null;
  48877. }
  48878. },
  48879. /**
  48880. * Add mutation observer from entity to mixin.
  48881. */
  48882. attachMixinListener: {
  48883. value: function (mixinEl) {
  48884. var currentObserver;
  48885. var mixinId;
  48886. var observer;
  48887. var self = this;
  48888. if (!mixinEl) { return; }
  48889. mixinId = mixinEl.id;
  48890. currentObserver = this.mixinObservers[mixinId];
  48891. if (currentObserver) { return; }
  48892. // Add observer.
  48893. observer = new MutationObserver(function (mutations) {
  48894. self.handleMixinUpdate(mutations[0].attributeName);
  48895. });
  48896. observer.observe(mixinEl, MIXIN_OBSERVER_CONFIG);
  48897. this.mixinObservers[mixinId] = observer;
  48898. }
  48899. },
  48900. handleMixinUpdate: {
  48901. value: function () { /* no-op */ }
  48902. },
  48903. /**
  48904. * Emit a DOM event.
  48905. *
  48906. * @param {string} name - Name of event.
  48907. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  48908. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  48909. * @param {object} [extraData] - Extra data to pass to the event, if any.
  48910. */
  48911. emit: {
  48912. value: (function () {
  48913. var data = {};
  48914. return function (name, detail, bubbles, extraData) {
  48915. if (bubbles === undefined) { bubbles = true; }
  48916. data.bubbles = !!bubbles;
  48917. data.detail = detail;
  48918. // If extra data is present, we need to create a new object.
  48919. if (extraData) { data = utils.extend({}, extraData, data); }
  48920. this.dispatchEvent(new CustomEvent(name, data));
  48921. };
  48922. })(),
  48923. writable: window.debug
  48924. }
  48925. })
  48926. });
  48927. },{"../utils/":173,"./a-register-element":102}],102:[function(_dereq_,module,exports){
  48928. /*
  48929. ------------------------------------------------------------
  48930. ------------- WARNING WARNING WARNING WARNING --------------
  48931. ------------------------------------------------------------
  48932. This module wraps registerElement to deal with components that inherit from
  48933. `ANode` and `AEntity`. It's a pass through in any other case.
  48934. It wraps some of the prototype methods of the created element to make sure
  48935. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  48936. are also invoked. The method in the base prototype is always called before the one
  48937. in the derived prototype.
  48938. */
  48939. // Polyfill `document.registerElement`.
  48940. _dereq_('document-register-element');
  48941. var ANode; // Must declare before AEntity. Initialized at the bottom.
  48942. var AEntity;
  48943. var knownTags = module.exports.knownTags = {};
  48944. function addTagName (tagName) {
  48945. knownTags[tagName.toLowerCase()] = true;
  48946. }
  48947. /**
  48948. * Return whether the element type is one of our known registered ones.
  48949. *
  48950. * @param {string} node - The name of the tag to register.
  48951. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  48952. */
  48953. module.exports.isNode = function (node) {
  48954. return node.tagName.toLowerCase() in knownTags || node.isNode;
  48955. };
  48956. /**
  48957. * @param {string} tagName - The name of the tag to register.
  48958. * @param {object} obj - The prototype of the new element.
  48959. * @returns {object} The prototype of the new element.
  48960. */
  48961. module.exports.registerElement = function (tagName, obj) {
  48962. var proto = Object.getPrototypeOf(obj.prototype);
  48963. var newObj = obj;
  48964. var isANode = ANode && proto === ANode.prototype;
  48965. var isAEntity = AEntity && proto === AEntity.prototype;
  48966. if (isANode || isAEntity) { addTagName(tagName); }
  48967. // Wrap if element inherits from `ANode`.
  48968. if (isANode) {
  48969. newObj = wrapANodeMethods(obj.prototype);
  48970. newObj = {prototype: Object.create(proto, newObj)};
  48971. }
  48972. // Wrap if element inherits from `AEntity`.
  48973. if (isAEntity) {
  48974. newObj = wrapAEntityMethods(obj.prototype);
  48975. newObj = {prototype: Object.create(proto, newObj)};
  48976. }
  48977. // Give all functions their proper name.
  48978. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  48979. var propVal = newObj.prototype[propName];
  48980. if (typeof propVal === 'function') {
  48981. propVal.displayName = propName;
  48982. }
  48983. });
  48984. return document.registerElement(tagName, newObj);
  48985. };
  48986. /**
  48987. * Wrap some obj methods to call those on `ANode` base prototype.
  48988. *
  48989. * @param {object} obj - Object that contains the methods that will be wrapped.
  48990. * @return {object} An object with the same properties as the input parameter but
  48991. * with some of methods wrapped.
  48992. */
  48993. function wrapANodeMethods (obj) {
  48994. var newObj = {};
  48995. var ANodeMethods = [
  48996. 'attachedCallback',
  48997. 'attributeChangedCallback',
  48998. 'createdCallback'
  48999. ];
  49000. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49001. copyProperties(obj, newObj);
  49002. return newObj;
  49003. }
  49004. /**
  49005. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  49006. *
  49007. * @param {object} obj - The objects that contains the methods that will be wrapped.
  49008. * @return {object} - An object with the same properties as the input parameter but
  49009. * with some of methods wrapped.
  49010. */
  49011. function wrapAEntityMethods (obj) {
  49012. var newObj = {};
  49013. var ANodeMethods = [
  49014. 'attachedCallback',
  49015. 'attributeChangedCallback',
  49016. 'createdCallback'
  49017. ];
  49018. var AEntityMethods = [
  49019. 'attachedCallback',
  49020. 'attributeChangedCallback',
  49021. 'createdCallback',
  49022. 'detachedCallback'
  49023. ];
  49024. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49025. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  49026. // Copies the remaining properties into the new object.
  49027. copyProperties(obj, newObj);
  49028. return newObj;
  49029. }
  49030. /**
  49031. * Wrap a list a methods to ensure that those in the base prototype are called
  49032. * before the derived one.
  49033. *
  49034. * @param {object} targetObj - Object that will contain the wrapped methods.
  49035. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  49036. * @param {object} derivedObject - Object that inherits from the baseObj.
  49037. * @param {object} baseObj - Object that derivedObj inherits from.
  49038. */
  49039. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  49040. methodList.forEach(function (methodName) {
  49041. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  49042. });
  49043. }
  49044. module.exports.wrapMethods = wrapMethods;
  49045. /**
  49046. * Wrap one method to ensure that the one in the base prototype is called before
  49047. * the one in the derived one.
  49048. *
  49049. * @param {object} obj - Object that will contain the wrapped method.
  49050. * @param {string} methodName - The name of the method that will be wrapped.
  49051. * @param {object} derivedObject - Object that inherits from the baseObj.
  49052. * @param {object} baseObj - Object that derivedObj inherits from.
  49053. */
  49054. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  49055. var derivedMethod = derivedObj[methodName];
  49056. var baseMethod = baseObj[methodName];
  49057. // Derived prototype does not define method, no need to wrap.
  49058. if (!derivedMethod || !baseMethod) { return; }
  49059. // Derived prototype doesn't override the one in the base one, no need to wrap.
  49060. if (derivedMethod === baseMethod) { return; }
  49061. // Wrap to ensure the base method is called before the one in the derived prototype.
  49062. obj[methodName] = {
  49063. value: function wrappedMethod () {
  49064. baseMethod.apply(this, arguments);
  49065. return derivedMethod.apply(this, arguments);
  49066. },
  49067. writable: window.debug
  49068. };
  49069. }
  49070. /**
  49071. * It copies the properties from source to destination object if they don't
  49072. * exist already.
  49073. *
  49074. * @param {object} source - The object where properties are copied from.
  49075. * @param {type} destination - The object where properties are copied to.
  49076. */
  49077. function copyProperties (source, destination) {
  49078. var props = Object.getOwnPropertyNames(source);
  49079. props.forEach(function (prop) {
  49080. var desc;
  49081. if (!destination[prop]) {
  49082. desc = Object.getOwnPropertyDescriptor(source, prop);
  49083. destination[prop] = {value: source[prop], writable: desc.writable};
  49084. }
  49085. });
  49086. }
  49087. ANode = _dereq_('./a-node');
  49088. AEntity = _dereq_('./a-entity');
  49089. },{"./a-entity":99,"./a-node":101,"document-register-element":11}],103:[function(_dereq_,module,exports){
  49090. /* global Node */
  49091. var schema = _dereq_('./schema');
  49092. var scenes = _dereq_('./scene/scenes');
  49093. var systems = _dereq_('./system');
  49094. var utils = _dereq_('../utils/');
  49095. var components = module.exports.components = {}; // Keep track of registered components.
  49096. var parseProperties = schema.parseProperties;
  49097. var parseProperty = schema.parseProperty;
  49098. var processSchema = schema.process;
  49099. var isSingleProp = schema.isSingleProperty;
  49100. var stringifyProperties = schema.stringifyProperties;
  49101. var stringifyProperty = schema.stringifyProperty;
  49102. var styleParser = utils.styleParser;
  49103. var warn = utils.debug('core:component:warn');
  49104. var aframeScript = document.currentScript;
  49105. var upperCaseRegExp = new RegExp('[A-Z]+');
  49106. /**
  49107. * Component class definition.
  49108. *
  49109. * Components configure appearance, modify behavior, or add functionality to
  49110. * entities. The behavior and appearance of an entity can be changed at runtime
  49111. * by adding, removing, or updating components. Entities do not share instances
  49112. * of components.
  49113. *
  49114. * @member {object} el - Reference to the entity element.
  49115. * @member {string} attrValue - Value of the corresponding HTML attribute.
  49116. * @member {object} data - Component data populated by parsing the
  49117. * mapped attribute of the component plus applying defaults and mixins.
  49118. */
  49119. var Component = module.exports.Component = function (el, attrValue, id) {
  49120. var self = this;
  49121. this.el = el;
  49122. this.id = id;
  49123. this.attrName = this.name + (id ? '__' + id : '');
  49124. this.evtDetail = {id: this.id, name: this.name};
  49125. this.initialized = false;
  49126. this.el.components[this.attrName] = this;
  49127. // Store component data from previous update call.
  49128. this.oldData = undefined;
  49129. // Last value passed to updateProperties.
  49130. this.previousAttrValue = undefined;
  49131. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  49132. el.emit('componentchanged', self.evtDetail, false);
  49133. }, 200);
  49134. this.updateProperties(attrValue);
  49135. };
  49136. Component.prototype = {
  49137. /**
  49138. * Contains the type schema and defaults for the data values.
  49139. * Data is coerced into the types of the values of the defaults.
  49140. */
  49141. schema: {},
  49142. /**
  49143. * Init handler. Similar to attachedCallback.
  49144. * Called during component initialization and is only run once.
  49145. * Components can use this to set initial state.
  49146. */
  49147. init: function () { /* no-op */ },
  49148. /**
  49149. * Update handler. Similar to attributeChangedCallback.
  49150. * Called whenever component's data changes.
  49151. * Also called on component initialization when the component receives initial data.
  49152. *
  49153. * @param {object} prevData - Previous attributes of the component.
  49154. */
  49155. update: function (prevData) { /* no-op */ },
  49156. updateSchema: undefined,
  49157. /**
  49158. * Tick handler.
  49159. * Called on each tick of the scene render loop.
  49160. * Affected by play and pause.
  49161. *
  49162. * @param {number} time - Scene tick time.
  49163. * @param {number} timeDelta - Difference in current render time and previous render time.
  49164. */
  49165. tick: undefined,
  49166. /**
  49167. * Tock handler.
  49168. * Called on each tock of the scene render loop.
  49169. * Affected by play and pause.
  49170. *
  49171. * @param {number} time - Scene tick time.
  49172. * @param {number} timeDelta - Difference in current render time and previous render time.
  49173. * @param {object} camera - Camera used to render the last frame.
  49174. */
  49175. tock: undefined,
  49176. /**
  49177. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  49178. */
  49179. play: function () { /* no-op */ },
  49180. /**
  49181. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  49182. */
  49183. pause: function () { /* no-op */ },
  49184. /**
  49185. * Remove handler. Similar to detachedCallback.
  49186. * Called whenever component is removed from the entity (i.e., removeAttribute).
  49187. * Components can use this to reset behavior on the entity.
  49188. */
  49189. remove: function () { /* no-op */ },
  49190. /**
  49191. * Parses each property based on property type.
  49192. * If component is single-property, then parses the single property value.
  49193. *
  49194. * @param {string} value - HTML attribute value.
  49195. * @param {boolean} silent - Suppress warning messages.
  49196. * @returns {object} Component data.
  49197. */
  49198. parse: function (value, silent) {
  49199. var schema = this.schema;
  49200. if (isSingleProp(schema)) { return parseProperty(value, schema); }
  49201. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  49202. },
  49203. /**
  49204. * Stringify properties if necessary.
  49205. *
  49206. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  49207. * value (e.g., selector, vec3 property types).
  49208. *
  49209. * @param {object} data - Complete component data.
  49210. * @returns {string}
  49211. */
  49212. stringify: function (data) {
  49213. var schema = this.schema;
  49214. if (typeof data === 'string') { return data; }
  49215. if (isSingleProp(schema)) { return stringifyProperty(data, schema); }
  49216. data = stringifyProperties(data, schema);
  49217. return styleParser.stringify(data);
  49218. },
  49219. /**
  49220. * Update the cache of the pre-parsed attribute value.
  49221. *
  49222. * @param {string} value - New data.
  49223. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  49224. */
  49225. updateCachedAttrValue: function (value, clobber) {
  49226. var attrValue = this.parseAttrValueForCache(value);
  49227. var isSinglePropSchema = isSingleProp(this.schema);
  49228. var property;
  49229. if (value === undefined) { return; }
  49230. // Merge new data with previous `attrValue` if updating and not clobbering.
  49231. if (!isSinglePropSchema && !clobber) {
  49232. this.attrValue = this.attrValue ? cloneData(this.attrValue) : {};
  49233. for (property in attrValue) {
  49234. this.attrValue[property] = attrValue[property];
  49235. }
  49236. return;
  49237. }
  49238. // If single-prop schema or clobber.
  49239. this.attrValue = attrValue;
  49240. },
  49241. /**
  49242. * Given an HTML attribute value parses the string
  49243. * based on the component schema. To avoid double parsings of
  49244. * strings into strings we store the original instead
  49245. * of the parsed one
  49246. *
  49247. * @param {string} value - HTML attribute value
  49248. */
  49249. parseAttrValueForCache: function (value) {
  49250. var parsedValue;
  49251. if (typeof value !== 'string') { return value; }
  49252. if (isSingleProp(this.schema)) {
  49253. parsedValue = this.schema.parse(value);
  49254. /**
  49255. * To avoid bogus double parsings. Cached values will be parsed when building
  49256. * component data. For instance when parsing a src id to its url, we want to cache
  49257. * original string and not the parsed one (#monster -> models/monster.dae)
  49258. * so when building data we parse the expected value.
  49259. */
  49260. if (typeof parsedValue === 'string') { parsedValue = value; }
  49261. } else {
  49262. // Parse using the style parser to avoid double parsing of individual properties.
  49263. parsedValue = styleParser.parse(value);
  49264. }
  49265. return parsedValue;
  49266. },
  49267. /**
  49268. * Write cached attribute data to the entity DOM element.
  49269. *
  49270. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  49271. * default components.
  49272. */
  49273. flushToDOM: function (isDefault) {
  49274. var attrValue = isDefault ? this.data : this.attrValue;
  49275. if (!attrValue) { return; }
  49276. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  49277. this.stringify(attrValue));
  49278. },
  49279. /**
  49280. * Apply new component data if data has changed.
  49281. *
  49282. * @param {string} attrValue - HTML attribute value.
  49283. * If undefined, use the cached attribute value and continue updating properties.
  49284. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  49285. */
  49286. updateProperties: function (attrValue, clobber) {
  49287. var el = this.el;
  49288. var isSinglePropSchema;
  49289. var key;
  49290. var skipTypeChecking;
  49291. var oldData = this.oldData;
  49292. // Just cache the attribute if the entity has not loaded
  49293. // Components are not initialized until the entity has loaded
  49294. if (!el.hasLoaded) {
  49295. this.updateCachedAttrValue(attrValue);
  49296. return;
  49297. }
  49298. isSinglePropSchema = isSingleProp(this.schema);
  49299. // Disable type checking if the passed attribute is an object and has not changed.
  49300. skipTypeChecking = attrValue !== null && typeof this.previousAttrValue === 'object' &&
  49301. attrValue === this.previousAttrValue;
  49302. if (skipTypeChecking) {
  49303. for (key in this.attrValue) {
  49304. if (!(key in attrValue)) {
  49305. skipTypeChecking = false;
  49306. break;
  49307. }
  49308. }
  49309. for (key in attrValue) {
  49310. if (!(key in this.attrValue)) {
  49311. skipTypeChecking = false;
  49312. break;
  49313. }
  49314. }
  49315. }
  49316. // Cache previously passed attribute to decide if we skip type checking.
  49317. this.previousAttrValue = attrValue;
  49318. // Cache current attrValue for future updates. Updates `this.attrValue`.
  49319. attrValue = this.parseAttrValueForCache(attrValue);
  49320. this.updateCachedAttrValue(attrValue, clobber);
  49321. if (this.updateSchema) {
  49322. this.updateSchema(this.buildData(this.attrValue, false, true));
  49323. }
  49324. this.data = this.buildData(this.attrValue, clobber, false, skipTypeChecking);
  49325. if (!this.initialized) {
  49326. // Component is being already initialized.
  49327. if (el.initializingComponents[this.name]) { return; }
  49328. // Prevent infinite loop in case of init method setting same component on the entity.
  49329. el.initializingComponents[this.name] = true;
  49330. // Initialize component.
  49331. this.init();
  49332. this.initialized = true;
  49333. delete el.initializingComponents[this.name];
  49334. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  49335. // Pass undefined to rest of types.
  49336. oldData = (!isSinglePropSchema ||
  49337. typeof parseProperty(undefined, this.schema) === 'object') ? {} : undefined;
  49338. // Store current data as previous data for future updates.
  49339. this.oldData = extendProperties({}, this.data, isSinglePropSchema);
  49340. this.update(oldData);
  49341. // Play the component if the entity is playing.
  49342. if (el.isPlaying) { this.play(); }
  49343. el.emit('componentinitialized', this.evtDetail, false);
  49344. } else {
  49345. // Don't update if properties haven't changed
  49346. if (utils.deepEqual(this.oldData, this.data)) { return; }
  49347. // Store current data as previous data for future updates.
  49348. this.oldData = extendProperties({}, this.data, isSinglePropSchema);
  49349. // Update component.
  49350. this.update(oldData);
  49351. this.throttledEmitComponentChanged();
  49352. }
  49353. },
  49354. /**
  49355. * Reset value of a property to the property's default value.
  49356. * If single-prop component, reset value to component's default value.
  49357. *
  49358. * @param {string} propertyName - Name of property to reset.
  49359. */
  49360. resetProperty: function (propertyName) {
  49361. if (isSingleProp(this.schema)) {
  49362. this.attrValue = undefined;
  49363. } else {
  49364. if (!(propertyName in this.attrValue)) { return; }
  49365. delete this.attrValue[propertyName];
  49366. }
  49367. this.updateProperties(this.attrValue);
  49368. },
  49369. /**
  49370. * Extend schema of component given a partial schema.
  49371. *
  49372. * Some components might want to mutate their schema based on certain properties.
  49373. * e.g., Material component changes its schema based on `shader` to account for different
  49374. * uniforms
  49375. *
  49376. * @param {object} schemaAddon - Schema chunk that extend base schema.
  49377. */
  49378. extendSchema: function (schemaAddon) {
  49379. // Clone base schema.
  49380. var extendedSchema = utils.extend({}, components[this.name].schema);
  49381. // Extend base schema with new schema chunk.
  49382. utils.extend(extendedSchema, schemaAddon);
  49383. this.schema = processSchema(extendedSchema);
  49384. this.el.emit('schemachanged', {component: this.name});
  49385. },
  49386. /**
  49387. * Builds component data from the current state of the entity, ultimately
  49388. * updating this.data.
  49389. *
  49390. * If the component was detached completely, set data to null.
  49391. *
  49392. * Precedence:
  49393. * 1. Defaults data
  49394. * 2. Mixin data.
  49395. * 3. Attribute data.
  49396. *
  49397. * Finally coerce the data to the types of the defaults.
  49398. *
  49399. * @param {object} newData - Element new data.
  49400. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  49401. * @param {boolean} silent - Suppress warning messages.
  49402. * @param {boolean} skipTypeChecking - Skip type checking and cohercion.
  49403. * @return {object} The component data
  49404. */
  49405. buildData: function (newData, clobber, silent, skipTypeChecking) {
  49406. var componentDefined;
  49407. var data;
  49408. var defaultValue;
  49409. var keys;
  49410. var keysLength;
  49411. var mixinData;
  49412. var schema = this.schema;
  49413. var i;
  49414. var isSinglePropSchema = isSingleProp(schema);
  49415. var mixinEls = this.el.mixinEls;
  49416. var previousData;
  49417. // Whether component has a defined value. For arrays, treat empty as not defined.
  49418. componentDefined = newData && newData.constructor === Array
  49419. ? newData.length
  49420. : newData !== undefined && newData !== null;
  49421. // 1. Default values (lowest precendence).
  49422. if (isSinglePropSchema) {
  49423. // Clone default value if plain object so components don't share the same object
  49424. // that might be modified by the user.
  49425. data = isObjectOrArray(schema.default) ? utils.clone(schema.default) : schema.default;
  49426. } else {
  49427. // Preserve previously set properties if clobber not enabled.
  49428. previousData = !clobber && this.attrValue;
  49429. // Clone previous data to prevent sharing references with attrValue that might be
  49430. // modified by the user.
  49431. data = typeof previousData === 'object' ? cloneData(previousData) : {};
  49432. // Apply defaults.
  49433. for (i = 0, keys = Object.keys(schema), keysLength = keys.length; i < keysLength; i++) {
  49434. defaultValue = schema[keys[i]].default;
  49435. if (data[keys[i]] !== undefined) { continue; }
  49436. // Clone default value if object so components don't share object
  49437. data[keys[i]] = isObjectOrArray(defaultValue) ? utils.clone(defaultValue) : defaultValue;
  49438. }
  49439. }
  49440. // 2. Mixin values.
  49441. for (i = 0; i < mixinEls.length; i++) {
  49442. mixinData = mixinEls[i].getAttribute(this.attrName);
  49443. if (mixinData) {
  49444. data = extendProperties(data, mixinData, isSinglePropSchema);
  49445. }
  49446. }
  49447. // 3. Attribute values (highest precendence).
  49448. if (componentDefined) {
  49449. if (isSinglePropSchema) {
  49450. if (skipTypeChecking === true) { return newData; }
  49451. return parseProperty(newData, schema);
  49452. }
  49453. data = extendProperties(data, newData, isSinglePropSchema);
  49454. } else {
  49455. if (skipTypeChecking === true) { return data; }
  49456. // Parse and coerce using the schema.
  49457. if (isSinglePropSchema) { return parseProperty(data, schema); }
  49458. }
  49459. if (skipTypeChecking === true) { return data; }
  49460. return parseProperties(data, schema, undefined, this.name, silent);
  49461. }
  49462. };
  49463. // For testing.
  49464. if (window.debug) {
  49465. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  49466. }
  49467. /**
  49468. * Registers a component to A-Frame.
  49469. *
  49470. * @param {string} name - Component name.
  49471. * @param {object} definition - Component schema and lifecycle method handlers.
  49472. * @returns {object} Component.
  49473. */
  49474. module.exports.registerComponent = function (name, definition) {
  49475. var NewComponent;
  49476. var proto = {};
  49477. // Warning if component is statically registered after the scene.
  49478. if (document.currentScript && document.currentScript !== aframeScript) {
  49479. scenes.forEach(function checkPosition (sceneEl) {
  49480. // Okay to register component after the scene at runtime.
  49481. if (sceneEl.hasLoaded) { return; }
  49482. // Check that component is declared before the scene.
  49483. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  49484. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  49485. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  49486. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  49487. 'such that the component is available to entities during scene initialization.');
  49488. // For testing.
  49489. if (window.debug) { registrationOrderWarnings[name] = true; }
  49490. });
  49491. }
  49492. if (upperCaseRegExp.test(name) === true) {
  49493. warn('The component name `' + name + '` contains uppercase characters, but ' +
  49494. 'HTML will ignore the capitalization of attribute names. ' +
  49495. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  49496. }
  49497. if (name.indexOf('__') !== -1) {
  49498. throw new Error('The component name `' + name + '` is not allowed. ' +
  49499. 'The sequence __ (double underscore) is reserved to specify an id' +
  49500. ' for multiple components of the same type');
  49501. }
  49502. // Format definition object to prototype object.
  49503. Object.keys(definition).forEach(function (key) {
  49504. proto[key] = {
  49505. value: definition[key],
  49506. writable: true
  49507. };
  49508. });
  49509. if (components[name]) {
  49510. throw new Error('The component `' + name + '` has been already registered. ' +
  49511. 'Check that you are not loading two versions of the same component ' +
  49512. 'or two different components of the same name.');
  49513. }
  49514. NewComponent = function (el, attr, id) {
  49515. Component.call(this, el, attr, id);
  49516. };
  49517. NewComponent.prototype = Object.create(Component.prototype, proto);
  49518. NewComponent.prototype.name = name;
  49519. NewComponent.prototype.constructor = NewComponent;
  49520. NewComponent.prototype.system = systems && systems.systems[name];
  49521. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  49522. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  49523. components[name] = {
  49524. Component: NewComponent,
  49525. dependencies: NewComponent.prototype.dependencies,
  49526. isSingleProp: isSingleProp(NewComponent.prototype.schema),
  49527. multiple: NewComponent.prototype.multiple,
  49528. parse: NewComponent.prototype.parse,
  49529. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  49530. schema: utils.extend(processSchema(NewComponent.prototype.schema, NewComponent.prototype.name)),
  49531. stringify: NewComponent.prototype.stringify,
  49532. type: NewComponent.prototype.type
  49533. };
  49534. return NewComponent;
  49535. };
  49536. /**
  49537. * Clone component data.
  49538. * Clone only the properties that are plain objects while keeping a reference for the rest.
  49539. *
  49540. * @param data - Component data to clone.
  49541. * @returns Cloned data.
  49542. */
  49543. function cloneData (data) {
  49544. var clone = {};
  49545. var parsedProperty;
  49546. var key;
  49547. for (key in data) {
  49548. parsedProperty = data[key];
  49549. clone[key] = isObjectOrArray(parsedProperty) ? utils.clone(parsedProperty) : parsedProperty;
  49550. }
  49551. return clone;
  49552. }
  49553. /**
  49554. * Object extending with checking for single-property schema.
  49555. *
  49556. * @param dest - Destination object or value.
  49557. * @param source - Source object or value
  49558. * @param {boolean} isSinglePropSchema - Whether or not schema is only a single property.
  49559. * @returns Overridden object or value.
  49560. */
  49561. function extendProperties (dest, source, isSinglePropSchema) {
  49562. if (isSinglePropSchema && (source === null || typeof source !== 'object')) { return source; }
  49563. var copy = utils.extend(dest, source);
  49564. var key;
  49565. for (key in copy) {
  49566. if (!copy[key] || copy[key].constructor !== Object) { continue; }
  49567. copy[key] = utils.clone(copy[key]);
  49568. }
  49569. return copy;
  49570. }
  49571. /**
  49572. * Checks if a component has defined a method that needs to run every frame.
  49573. */
  49574. function hasBehavior (component) {
  49575. return component.tick || component.tock;
  49576. }
  49577. /**
  49578. * Wrapper for user defined pause method
  49579. * Pause component by removing tick behavior and calling user's pause method.
  49580. *
  49581. * @param pauseMethod {function} - user defined pause method
  49582. */
  49583. function wrapPause (pauseMethod) {
  49584. return function pause () {
  49585. var sceneEl = this.el.sceneEl;
  49586. if (!this.isPlaying) { return; }
  49587. pauseMethod.call(this);
  49588. this.isPlaying = false;
  49589. // Remove tick behavior.
  49590. if (!hasBehavior(this)) { return; }
  49591. sceneEl.removeBehavior(this);
  49592. };
  49593. }
  49594. /**
  49595. * Wrapper for user defined play method
  49596. * Play component by adding tick behavior and calling user's play method.
  49597. *
  49598. * @param playMethod {function} - user defined play method
  49599. *
  49600. */
  49601. function wrapPlay (playMethod) {
  49602. return function play () {
  49603. var sceneEl = this.el.sceneEl;
  49604. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  49605. if (!this.initialized || !shouldPlay) { return; }
  49606. playMethod.call(this);
  49607. this.isPlaying = true;
  49608. // Add tick behavior.
  49609. if (!hasBehavior(this)) { return; }
  49610. sceneEl.addBehavior(this);
  49611. };
  49612. }
  49613. function isObjectOrArray (value) {
  49614. return value && (value.constructor === Object || value.constructor === Array);
  49615. }
  49616. },{"../utils/":173,"./scene/scenes":109,"./schema":111,"./system":113}],104:[function(_dereq_,module,exports){
  49617. var schema = _dereq_('./schema');
  49618. var processSchema = schema.process;
  49619. var geometries = module.exports.geometries = {}; // Registered geometries.
  49620. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  49621. var THREE = _dereq_('../lib/three');
  49622. /**
  49623. * Geometry class definition.
  49624. *
  49625. * Geometries extend the geometry component API to create and register geometry types.
  49626. */
  49627. var Geometry = module.exports.Geometry = function () {};
  49628. Geometry.prototype = {
  49629. /**
  49630. * Contains the type schema and defaults for the data values.
  49631. * Data is coerced into the types of the values of the defaults.
  49632. */
  49633. schema: {},
  49634. /**
  49635. * Init handler. Similar to attachedCallback.
  49636. * Called during shader initialization and is only run once.
  49637. */
  49638. init: function (data) {
  49639. this.geometry = new THREE.Geometry();
  49640. return this.geometry;
  49641. },
  49642. /**
  49643. * Update handler. Similar to attributeChangedCallback.
  49644. * Called whenever the associated geometry data changes.
  49645. *
  49646. * @param {object} data - New geometry data.
  49647. */
  49648. update: function (data) { /* no-op */ }
  49649. };
  49650. /**
  49651. * Registers a geometry to A-Frame.
  49652. *
  49653. * @param {string} name - Geometry name.
  49654. * @param {object} definition - Geometry property and methods.
  49655. * @returns {object} Geometry.
  49656. */
  49657. module.exports.registerGeometry = function (name, definition) {
  49658. var NewGeometry;
  49659. var proto = {};
  49660. // Format definition object to prototype object.
  49661. Object.keys(definition).forEach(function expandDefinition (key) {
  49662. proto[key] = {
  49663. value: definition[key],
  49664. writable: true
  49665. };
  49666. });
  49667. if (geometries[name]) {
  49668. throw new Error('The geometry `' + name + '` has been already registered');
  49669. }
  49670. NewGeometry = function () { Geometry.call(this); };
  49671. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  49672. NewGeometry.prototype.name = name;
  49673. NewGeometry.prototype.constructor = NewGeometry;
  49674. geometries[name] = {
  49675. Geometry: NewGeometry,
  49676. schema: processSchema(NewGeometry.prototype.schema)
  49677. };
  49678. geometryNames.push(name);
  49679. return NewGeometry;
  49680. };
  49681. },{"../lib/three":151,"./schema":111}],105:[function(_dereq_,module,exports){
  49682. var coordinates = _dereq_('../utils/coordinates');
  49683. var debug = _dereq_('debug');
  49684. var error = debug('core:propertyTypes:warn');
  49685. var warn = debug('core:propertyTypes:warn');
  49686. var propertyTypes = module.exports.propertyTypes = {};
  49687. var nonCharRegex = /[,> .[\]:]/;
  49688. // Built-in property types.
  49689. registerPropertyType('audio', '', assetParse);
  49690. registerPropertyType('array', [], arrayParse, arrayStringify);
  49691. registerPropertyType('asset', '', assetParse);
  49692. registerPropertyType('boolean', false, boolParse);
  49693. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  49694. registerPropertyType('int', 0, intParse);
  49695. registerPropertyType('number', 0, numberParse);
  49696. registerPropertyType('map', '', assetParse);
  49697. registerPropertyType('model', '', assetParse);
  49698. registerPropertyType('selector', null, selectorParse, selectorStringify);
  49699. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  49700. registerPropertyType('src', '', srcParse);
  49701. registerPropertyType('string', '', defaultParse, defaultStringify);
  49702. registerPropertyType('time', 0, intParse);
  49703. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  49704. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  49705. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  49706. /**
  49707. * Register a parser for re-use such that when someone uses `type` in the schema,
  49708. * `schema.process` will set the property `parse` and `stringify`.
  49709. *
  49710. * @param {string} type - Type name.
  49711. * @param [defaultValue=null] -
  49712. * Default value to use if component does not define default value.
  49713. * @param {function} [parse=defaultParse] - Parse string function.
  49714. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  49715. */
  49716. function registerPropertyType (type, defaultValue, parse, stringify) {
  49717. if ('type' in propertyTypes) {
  49718. error('Property type ' + type + ' is already registered.');
  49719. return;
  49720. }
  49721. propertyTypes[type] = {
  49722. default: defaultValue,
  49723. parse: parse || defaultParse,
  49724. stringify: stringify || defaultStringify
  49725. };
  49726. }
  49727. module.exports.registerPropertyType = registerPropertyType;
  49728. function arrayParse (value) {
  49729. if (Array.isArray(value)) { return value; }
  49730. if (!value || typeof value !== 'string') { return []; }
  49731. return value.split(',').map(trim);
  49732. function trim (str) { return str.trim(); }
  49733. }
  49734. function arrayStringify (value) {
  49735. return value.join(', ');
  49736. }
  49737. /**
  49738. * For general assets.
  49739. *
  49740. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  49741. * just string.
  49742. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  49743. * just string.
  49744. */
  49745. function assetParse (value) {
  49746. var el;
  49747. var parsedUrl;
  49748. // If an element was provided (e.g. canvas or video), just return it.
  49749. if (typeof value !== 'string') { return value; }
  49750. // Wrapped `url()` in case of data URI.
  49751. parsedUrl = value.match(/\url\((.+)\)/);
  49752. if (parsedUrl) { return parsedUrl[1]; }
  49753. // ID.
  49754. if (value.charAt(0) === '#') {
  49755. el = document.getElementById(value.substring(1));
  49756. if (el) {
  49757. // Pass through media elements. If we have the elements, we don't have to call
  49758. // three.js loaders which would re-request the assets.
  49759. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  49760. return el;
  49761. }
  49762. return el.getAttribute('src');
  49763. }
  49764. warn('"' + value + '" asset not found.');
  49765. return;
  49766. }
  49767. // Non-wrapped url().
  49768. return value;
  49769. }
  49770. function defaultParse (value) {
  49771. return value;
  49772. }
  49773. function defaultStringify (value) {
  49774. if (value === null) { return 'null'; }
  49775. return value.toString();
  49776. }
  49777. function boolParse (value) {
  49778. return value !== 'false' && value !== false;
  49779. }
  49780. function intParse (value) {
  49781. return parseInt(value, 10);
  49782. }
  49783. function numberParse (value) {
  49784. return parseFloat(value, 10);
  49785. }
  49786. function selectorParse (value) {
  49787. if (!value) { return null; }
  49788. if (typeof value !== 'string') { return value; }
  49789. if (value[0] === '#' && !nonCharRegex.test(value)) {
  49790. // When selecting element by ID only, use getElementById for better performance.
  49791. // Don't match like #myId .child.
  49792. return document.getElementById(value.substring(1));
  49793. }
  49794. return document.querySelector(value);
  49795. }
  49796. function selectorAllParse (value) {
  49797. if (!value) { return null; }
  49798. if (typeof value !== 'string') { return value; }
  49799. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  49800. }
  49801. function selectorStringify (value) {
  49802. if (value.getAttribute) {
  49803. return '#' + value.getAttribute('id');
  49804. }
  49805. return defaultStringify(value);
  49806. }
  49807. function selectorAllStringify (value) {
  49808. if (value instanceof Array) {
  49809. return value.map(function (element) {
  49810. return '#' + element.getAttribute('id');
  49811. }).join(', ');
  49812. }
  49813. return defaultStringify(value);
  49814. }
  49815. function srcParse (value) {
  49816. warn('`src` property type is deprecated. Use `asset` instead.');
  49817. return assetParse(value);
  49818. }
  49819. function vecParse (value) {
  49820. return coordinates.parse(value, this.default);
  49821. }
  49822. /**
  49823. * Validate the default values in a schema to match their type.
  49824. *
  49825. * @param {string} type - Property type name.
  49826. * @param defaultVal - Property type default value.
  49827. * @returns {boolean} Whether default value is accurate given the type.
  49828. */
  49829. function isValidDefaultValue (type, defaultVal) {
  49830. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  49831. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  49832. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  49833. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  49834. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  49835. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  49836. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  49837. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  49838. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  49839. if (type === 'selector' && typeof defaultVal !== 'string' &&
  49840. defaultVal !== null) { return false; }
  49841. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  49842. defaultVal !== null) { return false; }
  49843. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  49844. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  49845. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  49846. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  49847. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  49848. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  49849. return true;
  49850. }
  49851. module.exports.isValidDefaultValue = isValidDefaultValue;
  49852. /**
  49853. * Checks if default coordinates are valid.
  49854. *
  49855. * @param possibleCoordinates
  49856. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  49857. * @returns {boolean} Whether coordinates are parsed correctly.
  49858. */
  49859. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  49860. if (possibleCoordinates === null) { return true; }
  49861. if (typeof possibleCoordinates !== 'object') { return false; }
  49862. if (Object.keys(possibleCoordinates).length !== dimensions) {
  49863. return false;
  49864. } else {
  49865. var x = possibleCoordinates.x;
  49866. var y = possibleCoordinates.y;
  49867. var z = possibleCoordinates.z;
  49868. var w = possibleCoordinates.w;
  49869. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  49870. if (dimensions > 2 && typeof z !== 'number') { return false; }
  49871. if (dimensions > 3 && typeof w !== 'number') { return false; }
  49872. }
  49873. return true;
  49874. }
  49875. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  49876. },{"../utils/coordinates":168,"debug":8}],106:[function(_dereq_,module,exports){
  49877. /* global Promise, screen */
  49878. var initMetaTags = _dereq_('./metaTags').inject;
  49879. var initWakelock = _dereq_('./wakelock');
  49880. var re = _dereq_('../a-register-element');
  49881. var scenes = _dereq_('./scenes');
  49882. var systems = _dereq_('../system').systems;
  49883. var THREE = _dereq_('../../lib/three');
  49884. var TWEEN = _dereq_('@tweenjs/tween.js');
  49885. var utils = _dereq_('../../utils/');
  49886. // Require after.
  49887. var AEntity = _dereq_('../a-entity');
  49888. var ANode = _dereq_('../a-node');
  49889. var initPostMessageAPI = _dereq_('./postMessage');
  49890. var bind = utils.bind;
  49891. var isIOS = utils.device.isIOS();
  49892. var isMobile = utils.device.isMobile();
  49893. var registerElement = re.registerElement;
  49894. var warn = utils.debug('core:a-scene:warn');
  49895. /**
  49896. * Scene element, holds all entities.
  49897. *
  49898. * @member {array} behaviors - Component instances that have registered themselves to be
  49899. updated on every tick.
  49900. * @member {object} camera - three.js Camera object.
  49901. * @member {object} canvas
  49902. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  49903. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  49904. * @member {object} object3D - Root three.js Scene object.
  49905. * @member {object} renderer
  49906. * @member {bool} renderStarted
  49907. * @member {object} systems - Registered instantiated systems.
  49908. * @member {number} time
  49909. */
  49910. module.exports.AScene = registerElement('a-scene', {
  49911. prototype: Object.create(AEntity.prototype, {
  49912. createdCallback: {
  49913. value: function () {
  49914. this.isIOS = isIOS;
  49915. this.isMobile = isMobile;
  49916. this.isScene = true;
  49917. this.object3D = new THREE.Scene();
  49918. var self = this;
  49919. this.object3D.onAfterRender = function (renderer, scene, camera) {
  49920. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  49921. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  49922. };
  49923. this.render = bind(this.render, this);
  49924. this.systems = {};
  49925. this.systemNames = [];
  49926. this.time = this.delta = 0;
  49927. this.init();
  49928. }
  49929. },
  49930. init: {
  49931. value: function () {
  49932. this.behaviors = {tick: [], tock: []};
  49933. this.hasLoaded = false;
  49934. this.isPlaying = false;
  49935. this.originalHTML = this.innerHTML;
  49936. this.renderTarget = null;
  49937. setupCanvas(this);
  49938. this.setupRenderer();
  49939. this.resize();
  49940. this.addFullScreenStyles();
  49941. initPostMessageAPI(this);
  49942. // Default components.
  49943. this.setAttribute('inspector', '');
  49944. this.setAttribute('keyboard-shortcuts', '');
  49945. this.setAttribute('screenshot', '');
  49946. this.setAttribute('vr-mode-ui', '');
  49947. },
  49948. writable: true
  49949. },
  49950. addFullScreenStyles: {
  49951. value: function () {
  49952. var htmlEl = document.documentElement;
  49953. htmlEl.classList.add('a-html');
  49954. document.body.classList.add('a-body');
  49955. this.classList.add('fullscreen');
  49956. }
  49957. },
  49958. removeFullScreenStyles: {
  49959. value: function () {
  49960. var htmlEl = document.documentElement;
  49961. htmlEl.classList.remove('a-html');
  49962. document.body.classList.remove('a-body');
  49963. this.classList.remove('fullscreen');
  49964. }
  49965. },
  49966. attachedCallback: {
  49967. value: function () {
  49968. var resize;
  49969. var self = this;
  49970. initMetaTags(this);
  49971. initWakelock(this);
  49972. this.initSystems();
  49973. resize = bind(this.resize, this);
  49974. window.addEventListener('load', resize);
  49975. window.addEventListener('resize', function () {
  49976. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  49977. // where the window does not contain the correct viewport size
  49978. // after an orientation change. The window size is correct if the operation
  49979. // is postponed a few milliseconds.
  49980. // self.resize can be called directly once the bug above is fixed.
  49981. if (this.isIOS) {
  49982. setTimeout(resize, 100);
  49983. } else {
  49984. resize();
  49985. }
  49986. });
  49987. this.play();
  49988. // Add to scene index.
  49989. scenes.push(this);
  49990. // Handler to exit VR (e.g., Oculus Browser back button).
  49991. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  49992. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  49993. // bind functions
  49994. this.enterVRBound = function () { self.enterVR(); };
  49995. this.exitVRBound = function () { self.exitVR(); };
  49996. this.exitVRTrueBound = function () { self.exitVR(true); };
  49997. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  49998. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  49999. // Enter VR on `vrdisplayactivate` (e.g. putting on Rift headset).
  50000. window.addEventListener('vrdisplayactivate', this.enterVRBound);
  50001. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  50002. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  50003. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  50004. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  50005. // Register for mouse restricted events while in VR
  50006. // (e.g. mouse no longer available on desktop 2D view)
  50007. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  50008. // Register for mouse unrestricted events while in VR
  50009. // (e.g. mouse once again available on desktop 2D view)
  50010. window.addEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  50011. },
  50012. writable: window.debug
  50013. },
  50014. /**
  50015. * Initialize all systems.
  50016. */
  50017. initSystems: {
  50018. value: function () {
  50019. Object.keys(systems).forEach(bind(this.initSystem, this));
  50020. }
  50021. },
  50022. /**
  50023. * Initialize a system.
  50024. */
  50025. initSystem: {
  50026. value: function (name) {
  50027. if (this.systems[name]) { return; }
  50028. this.systems[name] = new systems[name](this);
  50029. this.systemNames.push(name);
  50030. }
  50031. },
  50032. /**
  50033. * Shut down scene on detach.
  50034. */
  50035. detachedCallback: {
  50036. value: function () {
  50037. // Remove from scene index.
  50038. var sceneIndex = scenes.indexOf(this);
  50039. scenes.splice(sceneIndex, 1);
  50040. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  50041. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  50042. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  50043. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  50044. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  50045. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  50046. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  50047. }
  50048. },
  50049. /**
  50050. * Add ticks and tocks.
  50051. *
  50052. * @param {object} behavior - A component.
  50053. */
  50054. addBehavior: {
  50055. value: function (behavior) {
  50056. var behaviorArr;
  50057. var behaviors = this.behaviors;
  50058. var behaviorType;
  50059. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  50060. for (behaviorType in behaviors) {
  50061. if (!behavior[behaviorType]) { continue; }
  50062. behaviorArr = this.behaviors[behaviorType];
  50063. if (behaviorArr.indexOf(behavior) === -1) {
  50064. behaviorArr.push(behavior);
  50065. }
  50066. }
  50067. }
  50068. },
  50069. /**
  50070. * For tests.
  50071. */
  50072. getPointerLockElement: {
  50073. value: function () {
  50074. return document.pointerLockElement;
  50075. },
  50076. writable: window.debug
  50077. },
  50078. /**
  50079. * For tests.
  50080. */
  50081. checkHeadsetConnected: {
  50082. value: utils.device.checkHeadsetConnected,
  50083. writable: window.debug
  50084. },
  50085. /**
  50086. * Call `requestPresent` if WebVR or WebVR polyfill.
  50087. * Call `requestFullscreen` on desktop.
  50088. * Handle events, states, fullscreen styles.
  50089. *
  50090. * @param {bool} fromExternal - Whether exiting VR due to an external event (e.g.,
  50091. * manually calling requestPresent via WebVR API directly).
  50092. * @returns {Promise}
  50093. */
  50094. enterVR: {
  50095. value: function (fromExternal) {
  50096. var self = this;
  50097. var vrDisplay;
  50098. var vrManager = self.renderer.vr;
  50099. // Don't enter VR if already in VR.
  50100. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  50101. // Enter VR via WebVR API.
  50102. if (!fromExternal && (this.checkHeadsetConnected() || this.isMobile)) {
  50103. vrDisplay = utils.device.getVRDisplay();
  50104. vrManager.setDevice(vrDisplay);
  50105. vrManager.enabled = true;
  50106. return vrDisplay.requestPresent([{source: this.canvas}])
  50107. .then(enterVRSuccess, enterVRFailure);
  50108. }
  50109. enterVRSuccess();
  50110. return Promise.resolve();
  50111. function enterVRSuccess () {
  50112. self.addState('vr-mode');
  50113. self.emit('enter-vr', {target: self});
  50114. // Lock to landscape orientation on mobile.
  50115. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  50116. screen.orientation.lock('landscape');
  50117. }
  50118. self.addFullScreenStyles();
  50119. // On mobile, the polyfill handles fullscreen.
  50120. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  50121. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  50122. // connected.
  50123. if (!self.isMobile && !self.checkHeadsetConnected()) {
  50124. requestFullscreen(self.canvas);
  50125. }
  50126. self.resize();
  50127. }
  50128. function enterVRFailure (err) {
  50129. if (err && err.message) {
  50130. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  50131. } else {
  50132. throw new Error('Failed to enter VR mode (`requestPresent`).');
  50133. }
  50134. }
  50135. },
  50136. writable: true
  50137. },
  50138. /**
  50139. * Call `exitPresent` if WebVR or WebVR polyfill.
  50140. * Handle events, states, fullscreen styles.
  50141. *
  50142. * @param {bool} fromExternal - Whether exiting VR due to an external event (e.g.,
  50143. * Oculus Browser GearVR back button).
  50144. * @returns {Promise}
  50145. */
  50146. exitVR: {
  50147. value: function (fromExternal) {
  50148. var self = this;
  50149. var vrDisplay;
  50150. // Don't exit VR if not in VR.
  50151. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  50152. exitFullscreen();
  50153. // Handle exiting VR if not yet already and in a headset or polyfill.
  50154. if (!fromExternal && (this.checkHeadsetConnected() || this.isMobile)) {
  50155. this.renderer.vr.enabled = false;
  50156. vrDisplay = utils.device.getVRDisplay();
  50157. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  50158. }
  50159. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  50160. exitVRSuccess();
  50161. return Promise.resolve();
  50162. function exitVRSuccess () {
  50163. self.removeState('vr-mode');
  50164. // Lock to landscape orientation on mobile.
  50165. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  50166. screen.orientation.unlock();
  50167. }
  50168. // Exiting VR in embedded mode, no longer need fullscreen styles.
  50169. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  50170. self.resize();
  50171. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  50172. self.emit('exit-vr', {target: self});
  50173. }
  50174. function exitVRFailure (err) {
  50175. if (err && err.message) {
  50176. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  50177. } else {
  50178. throw new Error('Failed to exit VR mode (`exitPresent`).');
  50179. }
  50180. }
  50181. },
  50182. writable: true
  50183. },
  50184. pointerRestricted: {
  50185. value: function () {
  50186. if (this.canvas) {
  50187. var pointerLockElement = this.getPointerLockElement();
  50188. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  50189. // Recreate pointer lock on the canvas, if taken on another element.
  50190. document.exitPointerLock();
  50191. }
  50192. if (this.canvas.requestPointerLock) {
  50193. this.canvas.requestPointerLock();
  50194. }
  50195. }
  50196. }
  50197. },
  50198. pointerUnrestricted: {
  50199. value: function () {
  50200. var pointerLockElement = this.getPointerLockElement();
  50201. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  50202. document.exitPointerLock();
  50203. }
  50204. }
  50205. },
  50206. /**
  50207. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  50208. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  50209. */
  50210. onVRPresentChange: {
  50211. value: function (evt) {
  50212. // Polyfill places display inside the detail property
  50213. var display = evt.display || evt.detail.display;
  50214. // Entering VR.
  50215. if (display.isPresenting) {
  50216. this.enterVR(true);
  50217. return;
  50218. }
  50219. // Exiting VR.
  50220. this.exitVR(true);
  50221. }
  50222. },
  50223. /**
  50224. * Wraps Entity.getAttribute to take into account for systems.
  50225. * If system exists, then return system data rather than possible component data.
  50226. */
  50227. getAttribute: {
  50228. value: function (attr) {
  50229. var system = this.systems[attr];
  50230. if (system) { return system.data; }
  50231. return AEntity.prototype.getAttribute.call(this, attr);
  50232. }
  50233. },
  50234. /**
  50235. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  50236. * what `getAttribute` is now. Now legacy code.
  50237. */
  50238. getComputedAttribute: {
  50239. value: function (attr) {
  50240. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  50241. this.getAttribute(attr);
  50242. }
  50243. },
  50244. /**
  50245. * Wraps Entity.getDOMAttribute to take into account for systems.
  50246. * If system exists, then return system data rather than possible component data.
  50247. */
  50248. getDOMAttribute: {
  50249. value: function (attr) {
  50250. var system = this.systems[attr];
  50251. if (system) { return system.data; }
  50252. return AEntity.prototype.getDOMAttribute.call(this, attr);
  50253. }
  50254. },
  50255. /**
  50256. * Wrap Entity.setAttribute to take into account for systems.
  50257. * If system exists, then skip component initialization checks and do a normal
  50258. * setAttribute.
  50259. */
  50260. setAttribute: {
  50261. value: function (attr, value, componentPropValue) {
  50262. var system = this.systems[attr];
  50263. if (system) {
  50264. ANode.prototype.setAttribute.call(this, attr, value);
  50265. system.updateProperties(value);
  50266. return;
  50267. }
  50268. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  50269. }
  50270. },
  50271. /**
  50272. * @param {object} behavior - A component.
  50273. */
  50274. removeBehavior: {
  50275. value: function (behavior) {
  50276. var behaviorArr;
  50277. var behaviorType;
  50278. var behaviors = this.behaviors;
  50279. var index;
  50280. // Check if behavior has tick and/or tock and remove the behavior from the appropriate array.
  50281. for (behaviorType in behaviors) {
  50282. if (!behavior[behaviorType]) { continue; }
  50283. behaviorArr = this.behaviors[behaviorType];
  50284. index = behaviorArr.indexOf(behavior);
  50285. if (index !== -1) { behaviorArr.splice(index, 1); }
  50286. }
  50287. }
  50288. },
  50289. resize: {
  50290. value: function () {
  50291. var camera = this.camera;
  50292. var canvas = this.canvas;
  50293. var embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  50294. var size;
  50295. var vrDevice;
  50296. var isVRPresenting;
  50297. vrDevice = this.renderer.vr.getDevice();
  50298. isVRPresenting = this.renderer.vr.enabled && vrDevice && vrDevice.isPresenting;
  50299. // Do not update renderer, if a camera or a canvas have not been injected.
  50300. // In VR mode, three handles canvas resize based on the dimensions returned by
  50301. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  50302. // the window size, therefore should not be overwritten with the window's width and height,
  50303. // except when in fullscreen mode.
  50304. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) { return; }
  50305. // Update camera.
  50306. size = getCanvasSize(canvas, embedded);
  50307. camera.aspect = size.width / size.height;
  50308. camera.updateProjectionMatrix();
  50309. // Notify renderer of size change.
  50310. this.renderer.setSize(size.width, size.height, false);
  50311. },
  50312. writable: true
  50313. },
  50314. setupRenderer: {
  50315. value: function () {
  50316. var self = this;
  50317. var renderer;
  50318. var rendererAttr;
  50319. var rendererAttrString;
  50320. var rendererConfig = {
  50321. canvas: this.canvas,
  50322. antialias: !isMobile,
  50323. alpha: true
  50324. };
  50325. if (this.hasAttribute('antialias')) {
  50326. rendererConfig.antialias = this.getAttribute('antialias') === 'true';
  50327. }
  50328. if (this.hasAttribute('renderer')) {
  50329. rendererAttrString = this.getAttribute('renderer');
  50330. rendererAttr = utils.styleParser.parse(rendererAttrString);
  50331. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  50332. rendererConfig.antialias = rendererAttr.antialias === 'true';
  50333. }
  50334. }
  50335. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  50336. renderer.setPixelRatio(window.devicePixelRatio);
  50337. renderer.sortObjects = false;
  50338. // We expect camera-set-active to be triggered at least once in the life of an a-frame app. Usually soon after
  50339. // it is initialized.
  50340. this.addEventListener('camera-set-active', function () {
  50341. renderer.vr.setPoseTarget(self.camera.el.object3D);
  50342. });
  50343. },
  50344. writable: window.debug
  50345. },
  50346. /**
  50347. * Handler attached to elements to help scene know when to kick off.
  50348. * Scene waits for all entities to load.
  50349. */
  50350. play: {
  50351. value: function () {
  50352. var self = this;
  50353. if (this.renderStarted) {
  50354. AEntity.prototype.play.call(this);
  50355. return;
  50356. }
  50357. this.addEventListener('loaded', function () {
  50358. AEntity.prototype.play.call(this); // .play() *before* render.
  50359. // Wait for camera if necessary before rendering.
  50360. if (this.camera) {
  50361. startRender(this);
  50362. return;
  50363. }
  50364. this.addEventListener('camera-set-active', function () { startRender(this); });
  50365. function startRender (sceneEl) {
  50366. if (sceneEl.renderStarted) { return; }
  50367. sceneEl.resize();
  50368. // Kick off render loop.
  50369. if (sceneEl.renderer) {
  50370. if (window.performance) {
  50371. window.performance.mark('render-started');
  50372. }
  50373. sceneEl.clock = new THREE.Clock();
  50374. sceneEl.render();
  50375. sceneEl.renderStarted = true;
  50376. sceneEl.emit('renderstart');
  50377. }
  50378. }
  50379. });
  50380. // setTimeout to wait for all nodes to attach and run their callbacks.
  50381. setTimeout(function () {
  50382. AEntity.prototype.load.call(self);
  50383. });
  50384. }
  50385. },
  50386. /**
  50387. * Wrap `updateComponent` to not initialize the component if the component has a system
  50388. * (aframevr/aframe#2365).
  50389. */
  50390. updateComponent: {
  50391. value: function (componentName) {
  50392. if (componentName in systems) { return; }
  50393. AEntity.prototype.updateComponent.apply(this, arguments);
  50394. }
  50395. },
  50396. /**
  50397. * Behavior-updater meant to be called from scene render.
  50398. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  50399. * needing to render.
  50400. */
  50401. tick: {
  50402. value: function (time, timeDelta) {
  50403. var i;
  50404. var systems = this.systems;
  50405. // Animations.
  50406. TWEEN.update();
  50407. // Components.
  50408. for (i = 0; i < this.behaviors.tick.length; i++) {
  50409. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  50410. this.behaviors.tick[i].tick(time, timeDelta);
  50411. }
  50412. // Systems.
  50413. for (i = 0; i < this.systemNames.length; i++) {
  50414. if (!systems[this.systemNames[i]].tick) { continue; }
  50415. systems[this.systemNames[i]].tick(time, timeDelta);
  50416. }
  50417. }
  50418. },
  50419. /**
  50420. * Behavior-updater meant to be called after scene render for post processing purposes.
  50421. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  50422. * needing to render.
  50423. */
  50424. tock: {
  50425. value: function (time, timeDelta, camera) {
  50426. var i;
  50427. var systems = this.systems;
  50428. // Components.
  50429. for (i = 0; i < this.behaviors.tock.length; i++) {
  50430. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  50431. this.behaviors.tock[i].tock(time, timeDelta, camera);
  50432. }
  50433. // Systems.
  50434. for (i = 0; i < this.systemNames.length; i++) {
  50435. if (!systems[this.systemNames[i]].tock) { continue; }
  50436. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  50437. }
  50438. }
  50439. },
  50440. /**
  50441. * The render loop.
  50442. *
  50443. * Updates animations.
  50444. * Updates behaviors.
  50445. * Renders with request animation frame.
  50446. */
  50447. render: {
  50448. value: function () {
  50449. this.delta = this.clock.getDelta() * 1000;
  50450. var renderer = this.renderer;
  50451. this.time = this.clock.elapsedTime * 1000;
  50452. if (this.isPlaying) { this.tick(this.time, this.delta); }
  50453. renderer.animate(this.render);
  50454. renderer.render(this.object3D, this.camera, this.renderTarget);
  50455. },
  50456. writable: true
  50457. }
  50458. })
  50459. });
  50460. /**
  50461. * Return the canvas size where the scene will be rendered
  50462. * It will be always the window size except when the scene
  50463. * is embedded. The parent size will be returned in that case
  50464. *
  50465. * @param {object} canvasEl - the canvas element
  50466. * @param {boolean} embedded - Is the scene embedded?
  50467. */
  50468. function getCanvasSize (canvasEl, embedded) {
  50469. if (embedded) {
  50470. return {
  50471. height: canvasEl.parentElement.offsetHeight,
  50472. width: canvasEl.parentElement.offsetWidth
  50473. };
  50474. }
  50475. return {
  50476. height: window.innerHeight,
  50477. width: window.innerWidth
  50478. };
  50479. }
  50480. function requestFullscreen (canvas) {
  50481. var requestFullscreen =
  50482. canvas.requestFullscreen ||
  50483. canvas.webkitRequestFullscreen ||
  50484. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  50485. canvas.msRequestFullscreen;
  50486. requestFullscreen.apply(canvas);
  50487. }
  50488. function exitFullscreen () {
  50489. if (document.exitFullscreen) {
  50490. document.exitFullscreen();
  50491. } else if (document.mozCancelFullScreen) {
  50492. document.mozCancelFullScreen();
  50493. } else if (document.webkitExitFullscreen) {
  50494. document.webkitExitFullscreen();
  50495. }
  50496. }
  50497. function setupCanvas (sceneEl) {
  50498. var canvasEl;
  50499. canvasEl = document.createElement('canvas');
  50500. canvasEl.classList.add('a-canvas');
  50501. // Mark canvas as provided/injected by A-Frame.
  50502. canvasEl.dataset.aframeCanvas = true;
  50503. sceneEl.appendChild(canvasEl);
  50504. document.addEventListener('fullscreenchange', onFullScreenChange);
  50505. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  50506. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  50507. // Prevent overscroll on mobile.
  50508. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  50509. // Set canvas on scene.
  50510. sceneEl.canvas = canvasEl;
  50511. sceneEl.emit('render-target-loaded', {target: canvasEl});
  50512. // For unknown reasons a synchronous resize does not work on desktop when
  50513. // entering/exiting fullscreen.
  50514. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  50515. function onFullScreenChange () {
  50516. var fullscreenEl =
  50517. document.fullscreenElement ||
  50518. document.mozFullScreenElement ||
  50519. document.webkitFullscreenElement;
  50520. // No fullscren element === exit fullscreen
  50521. if (!fullscreenEl) { sceneEl.exitVR(); }
  50522. document.activeElement.blur();
  50523. document.body.focus();
  50524. }
  50525. }
  50526. module.exports.setupCanvas = setupCanvas; // For testing.
  50527. },{"../../lib/three":151,"../../utils/":173,"../a-entity":99,"../a-node":101,"../a-register-element":102,"../system":113,"./metaTags":107,"./postMessage":108,"./scenes":109,"./wakelock":110,"@tweenjs/tween.js":1}],107:[function(_dereq_,module,exports){
  50528. var constants = _dereq_('../../constants/');
  50529. var extend = _dereq_('../../utils').extend;
  50530. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  50531. Meta({name: 'viewport', content: 'width=device-width,initial-scale=1,maximum-scale=1,shrink-to-fit=no,user-scalable=no,minimal-ui'}),
  50532. // W3C-standardised meta tags.
  50533. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  50534. Meta({name: 'theme-color', content: 'black'})
  50535. ];
  50536. var MOBILE_IOS_HEAD_TAGS = [
  50537. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  50538. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  50539. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  50540. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  50541. ];
  50542. function Meta (attrs) {
  50543. return {
  50544. tagName: 'meta',
  50545. attributes: attrs,
  50546. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  50547. };
  50548. }
  50549. function Link (attrs) {
  50550. return {
  50551. tagName: 'link',
  50552. attributes: attrs,
  50553. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  50554. };
  50555. }
  50556. /**
  50557. * Injects the necessary metatags in the document for mobile support:
  50558. * 1. Prevent the user to zoom in the document.
  50559. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  50560. * values and the canvas is properly scaled.
  50561. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  50562. * iOS.
  50563. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  50564. *
  50565. * @param {object} scene - Scene element
  50566. * @returns {Array}
  50567. */
  50568. module.exports.inject = function injectHeadTags (scene) {
  50569. var headEl = document.head;
  50570. var headScriptEl = headEl.querySelector('script');
  50571. var tag;
  50572. var headTags = [];
  50573. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  50574. if (scene.isIOS) {
  50575. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  50576. }
  50577. return headTags;
  50578. function createAndInjectTag (tagObj) {
  50579. if (!tagObj || tagObj.exists()) { return; }
  50580. tag = createTag(tagObj);
  50581. if (!tag) { return; }
  50582. if (headScriptEl) {
  50583. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  50584. } else {
  50585. headEl.appendChild(tag);
  50586. }
  50587. headTags.push(tag);
  50588. }
  50589. };
  50590. function createTag (tagObj) {
  50591. if (!tagObj || !tagObj.tagName) { return; }
  50592. var meta = document.createElement(tagObj.tagName);
  50593. meta.setAttribute(constants.AFRAME_INJECTED, '');
  50594. return extend(meta, tagObj.attributes);
  50595. }
  50596. },{"../../constants/":94,"../../utils":173}],108:[function(_dereq_,module,exports){
  50597. var bind = _dereq_('../../utils/bind');
  50598. var isIframed = _dereq_('../../utils/').isIframed;
  50599. /**
  50600. * Provides a post message API for scenes contained
  50601. * in an iframe.
  50602. */
  50603. module.exports = function initPostMessageAPI (scene) {
  50604. // Handles fullscreen behavior when inside an iframe.
  50605. if (!isIframed()) { return; }
  50606. // postMessage API handler
  50607. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  50608. };
  50609. function postMessageAPIHandler (event) {
  50610. var scene = this;
  50611. if (!event.data) { return; }
  50612. switch (event.data.type) {
  50613. case 'vr': {
  50614. switch (event.data.data) {
  50615. case 'enter':
  50616. scene.enterVR();
  50617. break;
  50618. case 'exit':
  50619. scene.exitVR();
  50620. break;
  50621. }
  50622. }
  50623. }
  50624. }
  50625. },{"../../utils/":173,"../../utils/bind":167}],109:[function(_dereq_,module,exports){
  50626. /*
  50627. Scene index for keeping track of created scenes.
  50628. */
  50629. module.exports = [];
  50630. },{}],110:[function(_dereq_,module,exports){
  50631. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  50632. module.exports = function initWakelock (scene) {
  50633. if (!scene.isMobile) { return; }
  50634. var wakelock = scene.wakelock = new Wakelock();
  50635. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  50636. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  50637. };
  50638. },{"../../../vendor/wakelock/wakelock":183}],111:[function(_dereq_,module,exports){
  50639. var utils = _dereq_('../utils/');
  50640. var PropertyTypes = _dereq_('./propertyTypes');
  50641. var debug = utils.debug;
  50642. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  50643. var propertyTypes = PropertyTypes.propertyTypes;
  50644. var warn = debug('core:schema:warn');
  50645. /**
  50646. * A schema is classified as a schema for a single property if:
  50647. * - `type` is defined on the schema as a string.
  50648. * - OR `default` is defined on the schema, as a reserved keyword.
  50649. * - OR schema is empty.
  50650. */
  50651. function isSingleProperty (schema) {
  50652. if ('type' in schema) {
  50653. return typeof schema.type === 'string';
  50654. }
  50655. return 'default' in schema;
  50656. }
  50657. module.exports.isSingleProperty = isSingleProperty;
  50658. /**
  50659. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  50660. *
  50661. * @param {object} schema
  50662. * @param {string} componentName
  50663. * @returns {object} Schema.
  50664. */
  50665. module.exports.process = function (schema, componentName) {
  50666. var propName;
  50667. // For single property schema, run processPropDefinition over the whole schema.
  50668. if (isSingleProperty(schema)) {
  50669. return processPropertyDefinition(schema, componentName);
  50670. }
  50671. // For multi-property schema, run processPropDefinition over each property definition.
  50672. for (propName in schema) {
  50673. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  50674. }
  50675. return schema;
  50676. };
  50677. /**
  50678. * Inject default value, parser, stringifier for single property.
  50679. *
  50680. * @param {object} propDefinition
  50681. * @param {string} componentName
  50682. */
  50683. function processPropertyDefinition (propDefinition, componentName) {
  50684. var defaultVal = propDefinition.default;
  50685. var isCustomType;
  50686. var propType;
  50687. var typeName = propDefinition.type;
  50688. // Type inference.
  50689. if (!propDefinition.type) {
  50690. if (defaultVal !== undefined &&
  50691. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  50692. // Type inference.
  50693. typeName = typeof defaultVal;
  50694. } else if (Array.isArray(defaultVal)) {
  50695. typeName = 'array';
  50696. } else {
  50697. // Fall back to string.
  50698. typeName = 'string';
  50699. }
  50700. } else if (propDefinition.type === 'bool') {
  50701. typeName = 'boolean';
  50702. } else if (propDefinition.type === 'float') {
  50703. typeName = 'number';
  50704. }
  50705. propType = propertyTypes[typeName];
  50706. if (!propType) {
  50707. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  50708. }
  50709. // Fill in parse and stringify using property types.
  50710. isCustomType = !!propDefinition.parse;
  50711. propDefinition.parse = propDefinition.parse || propType.parse;
  50712. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  50713. // Fill in type name.
  50714. propDefinition.type = typeName;
  50715. // Check that default value exists.
  50716. if ('default' in propDefinition) {
  50717. // Check that default values are valid.
  50718. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  50719. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  50720. '` in component `' + componentName + '`');
  50721. }
  50722. } else {
  50723. // Fill in default value.
  50724. propDefinition.default = propType.default;
  50725. }
  50726. return propDefinition;
  50727. }
  50728. module.exports.processPropertyDefinition = processPropertyDefinition;
  50729. /**
  50730. * Parse propData using schema. Use default values if not existing in propData.
  50731. *
  50732. * @param {object} propData - Unparsed properties.
  50733. * @param {object} schema - Property types definition.
  50734. * @param {boolean} getPartialData - Whether to return full component data or just the data
  50735. * with keys in `propData`.
  50736. * @param {string } componentName - Name of the component, used for the property warning.
  50737. * @param {boolean} silent - Suppress warning messages.
  50738. */
  50739. module.exports.parseProperties = (function () {
  50740. var propNames = [];
  50741. return function (propData, schema, getPartialData, componentName, silent) {
  50742. var i;
  50743. var propName;
  50744. var propDefinition;
  50745. var propValue;
  50746. propNames.length = 0;
  50747. for (propName in (getPartialData ? propData : schema)) { propNames.push(propName); }
  50748. if (propData === null || typeof propData !== 'object') { return propData; }
  50749. // Validation errors.
  50750. for (propName in propData) {
  50751. if (!schema[propName] && !silent) {
  50752. warn('Unknown property `' + propName +
  50753. '` for component/system `' + componentName + '`.');
  50754. }
  50755. }
  50756. for (i = 0; i < propNames.length; i++) {
  50757. propName = propNames[i];
  50758. propDefinition = schema[propName];
  50759. propValue = propData[propName];
  50760. if (!(schema[propName])) { return; }
  50761. propData[propName] = parseProperty(propValue, propDefinition);
  50762. }
  50763. return propData;
  50764. };
  50765. })();
  50766. /**
  50767. * Deserialize a single property.
  50768. */
  50769. function parseProperty (value, propDefinition) {
  50770. // Use default value if value is falsy.
  50771. if (value === undefined || value === null || value === '') {
  50772. value = propDefinition.default;
  50773. if (Array.isArray(value)) { value = value.slice(); }
  50774. }
  50775. // Invoke property type parser.
  50776. return propDefinition.parse(value, propDefinition.default);
  50777. }
  50778. module.exports.parseProperty = parseProperty;
  50779. /**
  50780. * Serialize a group of properties.
  50781. */
  50782. module.exports.stringifyProperties = function (propData, schema) {
  50783. var propName;
  50784. var propDefinition;
  50785. var propValue;
  50786. var stringifiedData = {};
  50787. var value;
  50788. for (propName in propData) {
  50789. propDefinition = schema[propName];
  50790. propValue = propData[propName];
  50791. value = propValue;
  50792. if (typeof value === 'object') {
  50793. value = stringifyProperty(propValue, propDefinition);
  50794. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  50795. }
  50796. stringifiedData[propName] = value;
  50797. }
  50798. return stringifiedData;
  50799. };
  50800. /**
  50801. * Serialize a single property.
  50802. */
  50803. function stringifyProperty (value, propDefinition) {
  50804. // This function stringifies but it's used in a context where
  50805. // there's always second stringification pass. By returning the original
  50806. // value when it's not an object we save one unnecessary call
  50807. // to JSON.stringify.
  50808. if (typeof value !== 'object') { return value; }
  50809. // if there's no schema for the property we use standar JSON stringify
  50810. if (!propDefinition || value === null) { return JSON.stringify(value); }
  50811. return propDefinition.stringify(value);
  50812. }
  50813. module.exports.stringifyProperty = stringifyProperty;
  50814. },{"../utils/":173,"./propertyTypes":105}],112:[function(_dereq_,module,exports){
  50815. var schema = _dereq_('./schema');
  50816. var processSchema = schema.process;
  50817. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  50818. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  50819. var THREE = _dereq_('../lib/three');
  50820. var utils = _dereq_('../utils');
  50821. // A-Frame properties to three.js uniform types.
  50822. var propertyToThreeMapping = {
  50823. array: 'v3',
  50824. color: 'v3',
  50825. int: 'i',
  50826. number: 'f',
  50827. map: 't',
  50828. time: 'f',
  50829. vec2: 'v2',
  50830. vec3: 'v3',
  50831. vec4: 'v4'
  50832. };
  50833. /**
  50834. * Shader class definition.
  50835. *
  50836. * Shaders extend the material component API so you can create your own library
  50837. * of customized materials
  50838. *
  50839. */
  50840. var Shader = module.exports.Shader = function () {};
  50841. Shader.prototype = {
  50842. /**
  50843. * Contains the type schema and defaults for the data values.
  50844. * Data is coerced into the types of the values of the defaults.
  50845. */
  50846. schema: {},
  50847. vertexShader:
  50848. 'void main() {' +
  50849. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  50850. '}',
  50851. fragmentShader:
  50852. 'void main() {' +
  50853. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  50854. '}',
  50855. /**
  50856. * Init handler. Similar to attachedCallback.
  50857. * Called during shader initialization and is only run once.
  50858. */
  50859. init: function (data) {
  50860. this.attributes = this.initVariables(data, 'attribute');
  50861. this.uniforms = this.initVariables(data, 'uniform');
  50862. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  50863. // attributes: this.attributes,
  50864. uniforms: this.uniforms,
  50865. vertexShader: this.vertexShader,
  50866. fragmentShader: this.fragmentShader
  50867. });
  50868. return this.material;
  50869. },
  50870. initVariables: function (data, type) {
  50871. var key;
  50872. var schema = this.schema;
  50873. var variables = {};
  50874. var varType;
  50875. for (key in schema) {
  50876. if (schema[key].is !== type) { continue; }
  50877. varType = propertyToThreeMapping[schema[key].type];
  50878. variables[key] = {
  50879. type: varType,
  50880. value: undefined // Let updateVariables handle setting these.
  50881. };
  50882. }
  50883. return variables;
  50884. },
  50885. /**
  50886. * Update handler. Similar to attributeChangedCallback.
  50887. * Called whenever the associated material data changes.
  50888. *
  50889. * @param {object} data - New material data.
  50890. */
  50891. update: function (data) {
  50892. this.updateVariables(data, 'attribute');
  50893. this.updateVariables(data, 'uniform');
  50894. },
  50895. updateVariables: function (data, type) {
  50896. var key;
  50897. var materialKey;
  50898. var schema = this.schema;
  50899. var variables;
  50900. variables = type === 'uniform' ? this.uniforms : this.attributes;
  50901. for (key in data) {
  50902. if (!schema[key] || schema[key].is !== type) { continue; }
  50903. if (schema[key].type === 'map') {
  50904. // If data unchanged, get out early.
  50905. if (!variables[key] || variables[key].value === data[key]) { continue; }
  50906. // Special handling is needed for textures.
  50907. materialKey = '_texture_' + key;
  50908. // We can't actually set the variable correctly until we've loaded the texture.
  50909. this.setMapOnTextureLoad(variables, key, materialKey);
  50910. // Kick off the texture update now that handler is added.
  50911. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  50912. continue;
  50913. }
  50914. variables[key].value = this.parseValue(schema[key].type, data[key]);
  50915. variables[key].needsUpdate = true;
  50916. }
  50917. },
  50918. parseValue: function (type, value) {
  50919. var color;
  50920. switch (type) {
  50921. case 'vec2': {
  50922. return new THREE.Vector2(value.x, value.y);
  50923. }
  50924. case 'vec3': {
  50925. return new THREE.Vector3(value.x, value.y, value.z);
  50926. }
  50927. case 'vec4': {
  50928. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  50929. }
  50930. case 'color': {
  50931. color = new THREE.Color(value);
  50932. return new THREE.Vector3(color.r, color.g, color.b);
  50933. }
  50934. case 'map': {
  50935. return THREE.ImageUtils.loadTexture(value);
  50936. }
  50937. default: {
  50938. return value;
  50939. }
  50940. }
  50941. },
  50942. setMapOnTextureLoad: function (variables, key, materialKey) {
  50943. var self = this;
  50944. this.el.addEventListener('materialtextureloaded', function () {
  50945. variables[key].value = self.material[materialKey];
  50946. variables[key].needsUpdate = true;
  50947. });
  50948. }
  50949. };
  50950. /**
  50951. * Registers a shader to A-Frame.
  50952. *
  50953. * @param {string} name - shader name.
  50954. * @param {object} definition - shader property and methods.
  50955. * @returns {object} Shader.
  50956. */
  50957. module.exports.registerShader = function (name, definition) {
  50958. var NewShader;
  50959. var proto = {};
  50960. // Format definition object to prototype object.
  50961. Object.keys(definition).forEach(function (key) {
  50962. proto[key] = {
  50963. value: definition[key],
  50964. writable: true
  50965. };
  50966. });
  50967. if (shaders[name]) {
  50968. throw new Error('The shader ' + name + ' has been already registered');
  50969. }
  50970. NewShader = function () { Shader.call(this); };
  50971. NewShader.prototype = Object.create(Shader.prototype, proto);
  50972. NewShader.prototype.name = name;
  50973. NewShader.prototype.constructor = NewShader;
  50974. shaders[name] = {
  50975. Shader: NewShader,
  50976. schema: processSchema(NewShader.prototype.schema)
  50977. };
  50978. shaderNames.push(name);
  50979. return NewShader;
  50980. };
  50981. },{"../lib/three":151,"../utils":173,"./schema":111}],113:[function(_dereq_,module,exports){
  50982. var components = _dereq_('./component');
  50983. var schema = _dereq_('./schema');
  50984. var utils = _dereq_('../utils/');
  50985. var parseProperties = schema.parseProperties;
  50986. var parseProperty = schema.parseProperty;
  50987. var processSchema = schema.process;
  50988. var isSingleProp = schema.isSingleProperty;
  50989. var styleParser = utils.styleParser;
  50990. var systems = module.exports.systems = {}; // Keep track of registered systems.
  50991. /**
  50992. * System class definition.
  50993. *
  50994. * Systems provide global scope and services to a group of instantiated components of the
  50995. * same class. They can also help abstract logic away from components such that components
  50996. * only have to worry about data.
  50997. *
  50998. * For example, a physics component that creates a physics world that oversees
  50999. * all entities with a physics or rigid body component.
  51000. *
  51001. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  51002. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  51003. * setAttribute behavior).
  51004. *
  51005. * @member {string} name - Name that system is registered under.
  51006. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  51007. */
  51008. var System = module.exports.System = function (sceneEl) {
  51009. var component = components && components.components[this.name];
  51010. // Set reference to scene.
  51011. this.el = sceneEl;
  51012. this.sceneEl = sceneEl;
  51013. // Set reference to matching component (if exists).
  51014. if (component) { component.Component.prototype.system = this; }
  51015. // Process system configuration.
  51016. this.buildData();
  51017. this.init();
  51018. this.update({});
  51019. };
  51020. System.prototype = {
  51021. /**
  51022. * Schema to configure system.
  51023. */
  51024. schema: {},
  51025. /**
  51026. * Init handler. Called during scene initialization and is only run once.
  51027. * Systems can use this to set initial state.
  51028. */
  51029. init: function () { /* no-op */ },
  51030. /**
  51031. * Update handler. Called during scene attribute updates.
  51032. * Systems can use this to dynamically update their state.
  51033. */
  51034. update: function (oldData) { /* no-op */ },
  51035. /**
  51036. * Build data and call update handler.
  51037. *
  51038. * @private
  51039. */
  51040. updateProperties: function (rawData) {
  51041. var oldData = this.data;
  51042. if (!Object.keys(schema).length) { return; }
  51043. this.buildData(rawData);
  51044. this.update(oldData);
  51045. },
  51046. /**
  51047. * Parse data.
  51048. */
  51049. buildData: function (rawData) {
  51050. var schema = this.schema;
  51051. if (!Object.keys(schema).length) { return; }
  51052. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  51053. if (isSingleProp(schema)) {
  51054. this.data = parseProperty(rawData, schema);
  51055. } else {
  51056. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  51057. }
  51058. },
  51059. /**
  51060. * Tick handler.
  51061. * Called on each tick of the scene render loop.
  51062. * Affected by play and pause.
  51063. *
  51064. * @param {number} time - Scene tick time.
  51065. * @param {number} timeDelta - Difference in current render time and previous render time.
  51066. */
  51067. tick: undefined,
  51068. /**
  51069. * Tock handler.
  51070. * Called on each tock of the scene render loop.
  51071. * Affected by play and pause.
  51072. *
  51073. * @param {number} time - Scene tick time.
  51074. * @param {number} timeDelta - Difference in current render time and previous render time.
  51075. */
  51076. tock: undefined,
  51077. /**
  51078. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  51079. */
  51080. play: function () { /* no-op */ },
  51081. /**
  51082. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  51083. */
  51084. pause: function () { /* no-op */ }
  51085. };
  51086. /**
  51087. * Registers a system to A-Frame.
  51088. *
  51089. * @param {string} name - Component name.
  51090. * @param {object} definition - Component property and methods.
  51091. * @returns {object} Component.
  51092. */
  51093. module.exports.registerSystem = function (name, definition) {
  51094. var i;
  51095. var NewSystem;
  51096. var proto = {};
  51097. var scenes = utils.findAllScenes(document);
  51098. // Format definition object to prototype object.
  51099. Object.keys(definition).forEach(function (key) {
  51100. proto[key] = {
  51101. value: definition[key],
  51102. writable: true
  51103. };
  51104. });
  51105. if (systems[name]) {
  51106. throw new Error('The system `' + name + '` has been already registered. ' +
  51107. 'Check that you are not loading two versions of the same system ' +
  51108. 'or two different systems of the same name.');
  51109. }
  51110. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  51111. NewSystem.prototype = Object.create(System.prototype, proto);
  51112. NewSystem.prototype.name = name;
  51113. NewSystem.prototype.constructor = NewSystem;
  51114. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  51115. systems[name] = NewSystem;
  51116. // Initialize systems for existing scenes
  51117. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  51118. };
  51119. },{"../utils/":173,"./component":103,"./schema":111}],114:[function(_dereq_,module,exports){
  51120. _dereq_('./pivot');
  51121. },{"./pivot":115}],115:[function(_dereq_,module,exports){
  51122. var registerComponent = _dereq_('../../core/component').registerComponent;
  51123. var THREE = _dereq_('../../lib/three');
  51124. var originalPosition = new THREE.Vector3();
  51125. var originalRotation = new THREE.Vector3();
  51126. /**
  51127. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  51128. */
  51129. registerComponent('pivot', {
  51130. dependencies: ['position'],
  51131. schema: {type: 'vec3'},
  51132. init: function () {
  51133. var data = this.data;
  51134. var el = this.el;
  51135. var originalParent = el.object3D.parent;
  51136. var originalGroup = el.object3D;
  51137. var outerGroup = new THREE.Group();
  51138. originalPosition.copy(originalGroup.position);
  51139. originalRotation.copy(originalGroup.rotation);
  51140. // Detach current group from parent.
  51141. originalParent.remove(originalGroup);
  51142. outerGroup.add(originalGroup);
  51143. // Set new group as the outer group.
  51144. originalParent.add(outerGroup);
  51145. // Set outer group as new object3D.
  51146. el.object3D = outerGroup;
  51147. // Apply pivot to original group.
  51148. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  51149. // Offset the pivot so that world position not affected.
  51150. // And restore position onto outer group.
  51151. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  51152. data.z + originalPosition.z);
  51153. // Transfer rotation to outer group.
  51154. outerGroup.rotation.copy(originalGroup.rotation);
  51155. originalGroup.rotation.set(0, 0, 0);
  51156. }
  51157. });
  51158. },{"../../core/component":103,"../../lib/three":151}],116:[function(_dereq_,module,exports){
  51159. /**
  51160. * Common mesh defaults, mappings, and transforms.
  51161. */
  51162. var components = _dereq_('../../core/component').components;
  51163. var shaders = _dereq_('../../core/shader').shaders;
  51164. var utils = _dereq_('../../utils/');
  51165. var materialMappings = {};
  51166. Object.keys(components.material.schema).forEach(addMapping);
  51167. Object.keys(shaders.standard.schema).forEach(addMapping);
  51168. function addMapping (prop) {
  51169. // To hyphenated.
  51170. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  51171. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  51172. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  51173. materialMappings[htmlAttrName] = 'material.' + prop;
  51174. }
  51175. module.exports = function getMeshMixin () {
  51176. return {
  51177. defaultComponents: {material: {}},
  51178. mappings: utils.extend({}, materialMappings)
  51179. };
  51180. };
  51181. },{"../../core/component":103,"../../core/shader":112,"../../utils/":173}],117:[function(_dereq_,module,exports){
  51182. _dereq_('./primitives/a-camera');
  51183. _dereq_('./primitives/a-collada-model');
  51184. _dereq_('./primitives/a-cursor');
  51185. _dereq_('./primitives/a-curvedimage');
  51186. _dereq_('./primitives/a-gltf-model');
  51187. _dereq_('./primitives/a-image');
  51188. _dereq_('./primitives/a-light');
  51189. _dereq_('./primitives/a-link');
  51190. _dereq_('./primitives/a-obj-model');
  51191. _dereq_('./primitives/a-sky');
  51192. _dereq_('./primitives/a-sound');
  51193. _dereq_('./primitives/a-text');
  51194. _dereq_('./primitives/a-video');
  51195. _dereq_('./primitives/a-videosphere');
  51196. _dereq_('./primitives/meshPrimitives');
  51197. },{"./primitives/a-camera":119,"./primitives/a-collada-model":120,"./primitives/a-cursor":121,"./primitives/a-curvedimage":122,"./primitives/a-gltf-model":123,"./primitives/a-image":124,"./primitives/a-light":125,"./primitives/a-link":126,"./primitives/a-obj-model":127,"./primitives/a-sky":128,"./primitives/a-sound":129,"./primitives/a-text":130,"./primitives/a-video":131,"./primitives/a-videosphere":132,"./primitives/meshPrimitives":133}],118:[function(_dereq_,module,exports){
  51198. var AEntity = _dereq_('../../core/a-entity');
  51199. var components = _dereq_('../../core/component').components;
  51200. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  51201. var utils = _dereq_('../../utils/');
  51202. var debug = utils.debug;
  51203. var setComponentProperty = utils.entity.setComponentProperty;
  51204. var log = debug('extras:primitives:debug');
  51205. var warn = debug('extras:primitives:warn');
  51206. var primitives = module.exports.primitives = {};
  51207. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  51208. name = name.toLowerCase();
  51209. log('Registering <%s>', name);
  51210. // Deprecation warning for defaultAttributes usage.
  51211. if (definition.defaultAttributes) {
  51212. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  51213. }
  51214. var primitive = registerElement(name, {
  51215. prototype: Object.create(AEntity.prototype, {
  51216. defaultComponentsFromPrimitive: {
  51217. value: definition.defaultComponents || definition.defaultAttributes || {}
  51218. },
  51219. deprecated: {value: definition.deprecated || null},
  51220. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  51221. mappings: {value: definition.mappings || {}},
  51222. createdCallback: {
  51223. value: function () {
  51224. if (definition.deprecated) { console.warn(definition.deprecated); }
  51225. this.resolveMappingCollisions();
  51226. }
  51227. },
  51228. /**
  51229. * If a mapping collides with a registered component name
  51230. * it renames the mapping to componentname-property
  51231. */
  51232. resolveMappingCollisions: {
  51233. value: function () {
  51234. var mappings = this.mappings;
  51235. var self = this;
  51236. Object.keys(mappings).forEach(function resolveCollision (key) {
  51237. var newAttribute;
  51238. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  51239. if (components[key]) {
  51240. newAttribute = mappings[key].replace('.', '-');
  51241. mappings[newAttribute] = mappings[key];
  51242. delete mappings[key];
  51243. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  51244. 'The attribute ' + key + ' has the same name as a registered component and' +
  51245. ' has been renamed to ' + newAttribute);
  51246. }
  51247. });
  51248. }
  51249. },
  51250. getExtraComponents: {
  51251. value: function () {
  51252. var attr;
  51253. var data;
  51254. var i;
  51255. var mapping;
  51256. var mixins;
  51257. var path;
  51258. var self = this;
  51259. // Gather component data from default components.
  51260. data = utils.clone(this.defaultComponentsFromPrimitive);
  51261. // Factor in mixins to overwrite default components.
  51262. mixins = this.getAttribute('mixin');
  51263. if (mixins) {
  51264. mixins = mixins.trim().split(' ');
  51265. mixins.forEach(function applyMixin (mixinId) {
  51266. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  51267. Object.keys(mixinComponents).forEach(function setComponent (name) {
  51268. data[name] = extend(data[name], mixinComponents[name]);
  51269. });
  51270. });
  51271. }
  51272. // Gather component data from mappings.
  51273. for (i = 0; i < this.attributes.length; i++) {
  51274. attr = this.attributes[i];
  51275. mapping = this.mappings[attr.name];
  51276. if (mapping) {
  51277. path = utils.entity.getComponentPropertyPath(mapping);
  51278. if (path.constructor === Array) {
  51279. data[path[0]] = data[path[0]] || {};
  51280. data[path[0]][path[1]] = attr.value.trim();
  51281. } else {
  51282. data[path] = attr.value.trim();
  51283. }
  51284. continue;
  51285. }
  51286. }
  51287. return data;
  51288. /**
  51289. * For the base to be extensible, both objects must be pure JavaScript objects.
  51290. * The function assumes that base is undefined, or null or a pure object.
  51291. */
  51292. function extend (base, extension) {
  51293. if (isUndefined(base)) {
  51294. return copy(extension);
  51295. }
  51296. if (isUndefined(extension)) {
  51297. return copy(base);
  51298. }
  51299. if (isPureObject(base) && isPureObject(extension)) {
  51300. return utils.extendDeep(base, extension);
  51301. }
  51302. return copy(extension);
  51303. }
  51304. function isUndefined (value) {
  51305. return typeof value === 'undefined';
  51306. }
  51307. function copy (value) {
  51308. if (isPureObject(value)) {
  51309. return utils.extendDeep({}, value);
  51310. }
  51311. return value;
  51312. }
  51313. function isPureObject (value) {
  51314. return value !== null && value.constructor === Object;
  51315. }
  51316. }
  51317. },
  51318. /**
  51319. * Sync to attribute to component property whenever mapped attribute changes.
  51320. * If attribute is mapped to a component property, set the component property using
  51321. * the attribute value.
  51322. */
  51323. attributeChangedCallback: {
  51324. value: function (attr, oldVal, value) {
  51325. var componentName = this.mappings[attr];
  51326. if (attr in this.deprecatedMappings) {
  51327. console.warn(this.deprecatedMappings[attr]);
  51328. }
  51329. if (!attr || !componentName) { return; }
  51330. // Set value.
  51331. setComponentProperty(this, componentName, value);
  51332. }
  51333. }
  51334. })
  51335. });
  51336. // Store.
  51337. primitives[name] = primitive;
  51338. return primitive;
  51339. };
  51340. /**
  51341. * Add component mappings using schema.
  51342. */
  51343. function addComponentMapping (componentName, mappings) {
  51344. var schema = components[componentName].schema;
  51345. Object.keys(schema).map(function (prop) {
  51346. // Hyphenate where there is camelCase.
  51347. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  51348. // If there is a mapping collision, prefix with component name and hyphen.
  51349. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  51350. mappings[attrName] = componentName + '.' + prop;
  51351. });
  51352. }
  51353. /**
  51354. * Helper to define a primitive, building mappings using a component schema.
  51355. */
  51356. function definePrimitive (tagName, defaultComponents, mappings) {
  51357. // If no initial mappings provided, start from empty map.
  51358. mappings = mappings || {};
  51359. // From the default components, add mapping automagically.
  51360. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  51361. addComponentMapping(componentName, mappings);
  51362. });
  51363. // Register the primitive.
  51364. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  51365. defaultComponents: defaultComponents,
  51366. mappings: mappings
  51367. }));
  51368. }
  51369. module.exports.definePrimitive = definePrimitive;
  51370. },{"../../core/a-entity":99,"../../core/a-register-element":102,"../../core/component":103,"../../utils/":173}],119:[function(_dereq_,module,exports){
  51371. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51372. registerPrimitive('a-camera', {
  51373. defaultComponents: {
  51374. 'camera': {},
  51375. 'look-controls': {},
  51376. 'wasd-controls': {},
  51377. 'position': {y: 1.6}
  51378. },
  51379. mappings: {
  51380. active: 'camera.active',
  51381. far: 'camera.far',
  51382. fov: 'camera.fov',
  51383. 'look-controls-enabled': 'look-controls.enabled',
  51384. near: 'camera.near',
  51385. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  51386. 'wasd-controls-enabled': 'wasd-controls.enabled',
  51387. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  51388. zoom: 'camera.zoom'
  51389. }
  51390. });
  51391. },{"../primitives":118}],120:[function(_dereq_,module,exports){
  51392. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51393. registerPrimitive('a-collada-model', {
  51394. mappings: {
  51395. src: 'collada-model'
  51396. }
  51397. });
  51398. },{"../primitives":118}],121:[function(_dereq_,module,exports){
  51399. var getMeshMixin = _dereq_('../getMeshMixin');
  51400. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51401. var utils = _dereq_('../../../utils/');
  51402. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  51403. defaultComponents: {
  51404. cursor: {},
  51405. geometry: {
  51406. primitive: 'ring',
  51407. radiusOuter: 0.016,
  51408. radiusInner: 0.01,
  51409. segmentsTheta: 32
  51410. },
  51411. material: {
  51412. color: '#000',
  51413. shader: 'flat',
  51414. opacity: 0.8
  51415. },
  51416. position: {
  51417. x: 0,
  51418. y: 0,
  51419. z: -1
  51420. }
  51421. },
  51422. mappings: {
  51423. far: 'raycaster.far',
  51424. fuse: 'cursor.fuse',
  51425. 'fuse-timeout': 'cursor.fuseTimeout',
  51426. interval: 'raycaster.interval',
  51427. objects: 'raycaster.objects'
  51428. }
  51429. }));
  51430. },{"../../../utils/":173,"../getMeshMixin":116,"../primitives":118}],122:[function(_dereq_,module,exports){
  51431. var getMeshMixin = _dereq_('../getMeshMixin');
  51432. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51433. var utils = _dereq_('../../../utils/');
  51434. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  51435. defaultComponents: {
  51436. geometry: {
  51437. height: 1,
  51438. primitive: 'cylinder',
  51439. radius: 2,
  51440. segmentsRadial: 48,
  51441. thetaLength: 270,
  51442. openEnded: true,
  51443. thetaStart: 0
  51444. },
  51445. material: {
  51446. color: '#FFF',
  51447. shader: 'flat',
  51448. side: 'double',
  51449. transparent: true,
  51450. repeat: '-1 1'
  51451. }
  51452. },
  51453. mappings: {
  51454. height: 'geometry.height',
  51455. 'open-ended': 'geometry.openEnded',
  51456. radius: 'geometry.radius',
  51457. segments: 'geometry.segmentsRadial',
  51458. start: 'geometry.thetaStart',
  51459. 'theta-length': 'geometry.thetaLength',
  51460. 'theta-start': 'geometry.thetaStart',
  51461. 'width': 'geometry.thetaLength'
  51462. }
  51463. }));
  51464. },{"../../../utils/":173,"../getMeshMixin":116,"../primitives":118}],123:[function(_dereq_,module,exports){
  51465. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51466. registerPrimitive('a-gltf-model', {
  51467. mappings: {
  51468. src: 'gltf-model'
  51469. }
  51470. });
  51471. },{"../primitives":118}],124:[function(_dereq_,module,exports){
  51472. var getMeshMixin = _dereq_('../getMeshMixin');
  51473. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51474. var utils = _dereq_('../../../utils/');
  51475. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  51476. defaultComponents: {
  51477. geometry: {
  51478. primitive: 'plane'
  51479. },
  51480. material: {
  51481. color: '#FFF',
  51482. shader: 'flat',
  51483. side: 'double',
  51484. transparent: true
  51485. }
  51486. },
  51487. mappings: {
  51488. height: 'geometry.height',
  51489. width: 'geometry.width'
  51490. }
  51491. }));
  51492. },{"../../../utils/":173,"../getMeshMixin":116,"../primitives":118}],125:[function(_dereq_,module,exports){
  51493. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51494. registerPrimitive('a-light', {
  51495. defaultComponents: {
  51496. light: {}
  51497. },
  51498. mappings: {
  51499. angle: 'light.angle',
  51500. color: 'light.color',
  51501. 'ground-color': 'light.groundColor',
  51502. decay: 'light.decay',
  51503. distance: 'light.distance',
  51504. intensity: 'light.intensity',
  51505. penumbra: 'light.penumbra',
  51506. type: 'light.type',
  51507. target: 'light.target'
  51508. }
  51509. });
  51510. },{"../primitives":118}],126:[function(_dereq_,module,exports){
  51511. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51512. registerPrimitive('a-link', {
  51513. defaultComponents: {},
  51514. mappings: {
  51515. href: 'link.href',
  51516. image: 'link.image',
  51517. title: 'link.title'
  51518. }
  51519. });
  51520. },{"../primitives":118}],127:[function(_dereq_,module,exports){
  51521. var meshMixin = _dereq_('../getMeshMixin')();
  51522. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51523. var utils = _dereq_('../../../utils/');
  51524. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  51525. defaultComponents: {
  51526. 'obj-model': {}
  51527. },
  51528. mappings: {
  51529. src: 'obj-model.obj',
  51530. mtl: 'obj-model.mtl'
  51531. }
  51532. }));
  51533. },{"../../../utils/":173,"../getMeshMixin":116,"../primitives":118}],128:[function(_dereq_,module,exports){
  51534. var getMeshMixin = _dereq_('../getMeshMixin');
  51535. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51536. var utils = _dereq_('../../../utils/');
  51537. var meshPrimitives = _dereq_('./meshPrimitives');
  51538. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  51539. defaultComponents: {
  51540. geometry: {
  51541. primitive: 'sphere',
  51542. radius: 5000,
  51543. segmentsWidth: 64,
  51544. segmentsHeight: 32
  51545. },
  51546. material: {
  51547. color: '#FFF',
  51548. side: 'back',
  51549. shader: 'flat',
  51550. npot: true
  51551. },
  51552. scale: '-1 1 1'
  51553. },
  51554. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  51555. }));
  51556. },{"../../../utils/":173,"../getMeshMixin":116,"../primitives":118,"./meshPrimitives":133}],129:[function(_dereq_,module,exports){
  51557. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51558. registerPrimitive('a-sound', {
  51559. defaultComponents: {
  51560. sound: {}
  51561. },
  51562. mappings: {
  51563. src: 'sound.src',
  51564. on: 'sound.on',
  51565. autoplay: 'sound.autoplay',
  51566. loop: 'sound.loop',
  51567. volume: 'sound.volume'
  51568. }
  51569. });
  51570. },{"../primitives":118}],130:[function(_dereq_,module,exports){
  51571. // <a-text> using `definePrimitive` helper.
  51572. var definePrimitive = _dereq_('../primitives').definePrimitive;
  51573. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  51574. },{"../primitives":118}],131:[function(_dereq_,module,exports){
  51575. var getMeshMixin = _dereq_('../getMeshMixin');
  51576. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51577. var utils = _dereq_('../../../utils/');
  51578. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  51579. defaultComponents: {
  51580. geometry: {
  51581. primitive: 'plane'
  51582. },
  51583. material: {
  51584. color: '#FFF',
  51585. shader: 'flat',
  51586. side: 'double',
  51587. transparent: true
  51588. }
  51589. },
  51590. mappings: {
  51591. height: 'geometry.height',
  51592. width: 'geometry.width'
  51593. }
  51594. }));
  51595. },{"../../../utils/":173,"../getMeshMixin":116,"../primitives":118}],132:[function(_dereq_,module,exports){
  51596. var getMeshMixin = _dereq_('../getMeshMixin');
  51597. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51598. var utils = _dereq_('../../../utils/');
  51599. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  51600. defaultComponents: {
  51601. geometry: {
  51602. primitive: 'sphere',
  51603. radius: 5000,
  51604. segmentsWidth: 64,
  51605. segmentsHeight: 32
  51606. },
  51607. material: {
  51608. color: '#FFF',
  51609. shader: 'flat',
  51610. side: 'back',
  51611. npot: true
  51612. },
  51613. scale: '-1 1 1'
  51614. },
  51615. mappings: {
  51616. radius: 'geometry.radius',
  51617. 'segments-height': 'geometry.segmentsHeight',
  51618. 'segments-width': 'geometry.segmentsWidth'
  51619. }
  51620. }));
  51621. },{"../../../utils/":173,"../getMeshMixin":116,"../primitives":118}],133:[function(_dereq_,module,exports){
  51622. /**
  51623. * Automated mesh primitive registration.
  51624. */
  51625. var getMeshMixin = _dereq_('../getMeshMixin');
  51626. var geometries = _dereq_('../../../core/geometry').geometries;
  51627. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  51628. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51629. var utils = _dereq_('../../../utils/');
  51630. // For testing.
  51631. var meshPrimitives = module.exports = {};
  51632. // Generate primitive for each geometry type.
  51633. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  51634. var geometry = geometries[geometryName];
  51635. var geometryHyphened = unCamelCase(geometryName);
  51636. // Generate mappings.
  51637. var mappings = {};
  51638. Object.keys(geometry.schema).forEach(function createMapping (property) {
  51639. mappings[unCamelCase(property)] = 'geometry.' + property;
  51640. });
  51641. // Register.
  51642. var tagName = 'a-' + geometryHyphened;
  51643. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  51644. defaultComponents: {geometry: {primitive: geometryName}},
  51645. mappings: mappings
  51646. }));
  51647. meshPrimitives[tagName] = primitive;
  51648. });
  51649. /**
  51650. * camelCase to hyphened-string.
  51651. */
  51652. function unCamelCase (str) {
  51653. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  51654. }
  51655. },{"../../../core/geometry":104,"../../../utils/":173,"../getMeshMixin":116,"../primitives":118}],134:[function(_dereq_,module,exports){
  51656. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51657. var THREE = _dereq_('../lib/three');
  51658. registerGeometry('box', {
  51659. schema: {
  51660. depth: {default: 1, min: 0},
  51661. height: {default: 1, min: 0},
  51662. width: {default: 1, min: 0},
  51663. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  51664. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  51665. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  51666. },
  51667. init: function (data) {
  51668. this.geometry = new THREE.BoxGeometry(
  51669. data.width, data.height, data.depth,
  51670. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  51671. }
  51672. });
  51673. },{"../core/geometry":104,"../lib/three":151}],135:[function(_dereq_,module,exports){
  51674. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51675. var THREE = _dereq_('../lib/three');
  51676. var degToRad = THREE.Math.degToRad;
  51677. registerGeometry('circle', {
  51678. schema: {
  51679. radius: {default: 1, min: 0},
  51680. segments: {default: 32, min: 3, type: 'int'},
  51681. thetaLength: {default: 360, min: 0},
  51682. thetaStart: {default: 0}
  51683. },
  51684. init: function (data) {
  51685. this.geometry = new THREE.CircleGeometry(
  51686. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  51687. }
  51688. });
  51689. },{"../core/geometry":104,"../lib/three":151}],136:[function(_dereq_,module,exports){
  51690. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51691. var THREE = _dereq_('../lib/three');
  51692. var degToRad = THREE.Math.degToRad;
  51693. registerGeometry('cone', {
  51694. schema: {
  51695. height: {default: 1, min: 0},
  51696. openEnded: {default: false},
  51697. radiusBottom: {default: 1, min: 0},
  51698. radiusTop: {default: 0.01, min: 0},
  51699. segmentsHeight: {default: 18, min: 1, type: 'int'},
  51700. segmentsRadial: {default: 36, min: 3, type: 'int'},
  51701. thetaLength: {default: 360, min: 0},
  51702. thetaStart: {default: 0}
  51703. },
  51704. init: function (data) {
  51705. this.geometry = new THREE.CylinderGeometry(
  51706. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  51707. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  51708. degToRad(data.thetaLength));
  51709. }
  51710. });
  51711. },{"../core/geometry":104,"../lib/three":151}],137:[function(_dereq_,module,exports){
  51712. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51713. var THREE = _dereq_('../lib/three');
  51714. var degToRad = THREE.Math.degToRad;
  51715. registerGeometry('cylinder', {
  51716. schema: {
  51717. height: {default: 1, min: 0},
  51718. openEnded: {default: false},
  51719. radius: {default: 1, min: 0},
  51720. segmentsHeight: {default: 18, min: 1, type: 'int'},
  51721. segmentsRadial: {default: 36, min: 3, type: 'int'},
  51722. thetaLength: {default: 360, min: 0},
  51723. thetaStart: {default: 0}
  51724. },
  51725. init: function (data) {
  51726. this.geometry = new THREE.CylinderGeometry(
  51727. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  51728. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  51729. }
  51730. });
  51731. },{"../core/geometry":104,"../lib/three":151}],138:[function(_dereq_,module,exports){
  51732. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51733. var THREE = _dereq_('../lib/three');
  51734. registerGeometry('dodecahedron', {
  51735. schema: {
  51736. detail: {default: 0, min: 0, max: 5, type: 'int'},
  51737. radius: {default: 1, min: 0}
  51738. },
  51739. init: function (data) {
  51740. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  51741. }
  51742. });
  51743. },{"../core/geometry":104,"../lib/three":151}],139:[function(_dereq_,module,exports){
  51744. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51745. var THREE = _dereq_('../lib/three');
  51746. registerGeometry('icosahedron', {
  51747. schema: {
  51748. detail: {default: 0, min: 0, max: 5, type: 'int'},
  51749. radius: {default: 1, min: 0}
  51750. },
  51751. init: function (data) {
  51752. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  51753. }
  51754. });
  51755. },{"../core/geometry":104,"../lib/three":151}],140:[function(_dereq_,module,exports){
  51756. _dereq_('./box.js');
  51757. _dereq_('./circle.js');
  51758. _dereq_('./cone.js');
  51759. _dereq_('./cylinder.js');
  51760. _dereq_('./dodecahedron.js');
  51761. _dereq_('./icosahedron.js');
  51762. _dereq_('./octahedron.js');
  51763. _dereq_('./plane.js');
  51764. _dereq_('./ring.js');
  51765. _dereq_('./sphere.js');
  51766. _dereq_('./tetrahedron.js');
  51767. _dereq_('./torus.js');
  51768. _dereq_('./torusKnot.js');
  51769. _dereq_('./triangle.js');
  51770. },{"./box.js":134,"./circle.js":135,"./cone.js":136,"./cylinder.js":137,"./dodecahedron.js":138,"./icosahedron.js":139,"./octahedron.js":141,"./plane.js":142,"./ring.js":143,"./sphere.js":144,"./tetrahedron.js":145,"./torus.js":146,"./torusKnot.js":147,"./triangle.js":148}],141:[function(_dereq_,module,exports){
  51771. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51772. var THREE = _dereq_('../lib/three');
  51773. registerGeometry('octahedron', {
  51774. schema: {
  51775. detail: {default: 0, min: 0, max: 5, type: 'int'},
  51776. radius: {default: 1, min: 0}
  51777. },
  51778. init: function (data) {
  51779. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  51780. }
  51781. });
  51782. },{"../core/geometry":104,"../lib/three":151}],142:[function(_dereq_,module,exports){
  51783. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51784. var THREE = _dereq_('../lib/three');
  51785. registerGeometry('plane', {
  51786. schema: {
  51787. height: {default: 1, min: 0},
  51788. width: {default: 1, min: 0},
  51789. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  51790. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  51791. },
  51792. init: function (data) {
  51793. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  51794. }
  51795. });
  51796. },{"../core/geometry":104,"../lib/three":151}],143:[function(_dereq_,module,exports){
  51797. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51798. var THREE = _dereq_('../lib/three');
  51799. var degToRad = THREE.Math.degToRad;
  51800. registerGeometry('ring', {
  51801. schema: {
  51802. radiusInner: {default: 0.8, min: 0},
  51803. radiusOuter: {default: 1.2, min: 0},
  51804. segmentsPhi: {default: 10, min: 1, type: 'int'},
  51805. segmentsTheta: {default: 32, min: 3, type: 'int'},
  51806. thetaLength: {default: 360, min: 0},
  51807. thetaStart: {default: 0}
  51808. },
  51809. init: function (data) {
  51810. this.geometry = new THREE.RingGeometry(
  51811. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  51812. degToRad(data.thetaStart), degToRad(data.thetaLength));
  51813. }
  51814. });
  51815. },{"../core/geometry":104,"../lib/three":151}],144:[function(_dereq_,module,exports){
  51816. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51817. var THREE = _dereq_('../lib/three');
  51818. var degToRad = THREE.Math.degToRad;
  51819. registerGeometry('sphere', {
  51820. schema: {
  51821. radius: {default: 1, min: 0},
  51822. phiLength: {default: 360},
  51823. phiStart: {default: 0, min: 0},
  51824. thetaLength: {default: 180, min: 0},
  51825. thetaStart: {default: 0},
  51826. segmentsHeight: {default: 18, min: 2, type: 'int'},
  51827. segmentsWidth: {default: 36, min: 3, type: 'int'}
  51828. },
  51829. init: function (data) {
  51830. this.geometry = new THREE.SphereGeometry(
  51831. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  51832. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  51833. }
  51834. });
  51835. },{"../core/geometry":104,"../lib/three":151}],145:[function(_dereq_,module,exports){
  51836. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51837. var THREE = _dereq_('../lib/three');
  51838. registerGeometry('tetrahedron', {
  51839. schema: {
  51840. detail: {default: 0, min: 0, max: 5, type: 'int'},
  51841. radius: {default: 1, min: 0}
  51842. },
  51843. init: function (data) {
  51844. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  51845. }
  51846. });
  51847. },{"../core/geometry":104,"../lib/three":151}],146:[function(_dereq_,module,exports){
  51848. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51849. var THREE = _dereq_('../lib/three');
  51850. var degToRad = THREE.Math.degToRad;
  51851. registerGeometry('torus', {
  51852. schema: {
  51853. arc: {default: 360},
  51854. radius: {default: 1, min: 0},
  51855. radiusTubular: {default: 0.2, min: 0},
  51856. segmentsRadial: {default: 36, min: 2, type: 'int'},
  51857. segmentsTubular: {default: 32, min: 3, type: 'int'}
  51858. },
  51859. init: function (data) {
  51860. this.geometry = new THREE.TorusGeometry(
  51861. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  51862. degToRad(data.arc));
  51863. }
  51864. });
  51865. },{"../core/geometry":104,"../lib/three":151}],147:[function(_dereq_,module,exports){
  51866. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51867. var THREE = _dereq_('../lib/three');
  51868. registerGeometry('torusKnot', {
  51869. schema: {
  51870. p: {default: 2, min: 1},
  51871. q: {default: 3, min: 1},
  51872. radius: {default: 1, min: 0},
  51873. radiusTubular: {default: 0.2, min: 0},
  51874. segmentsRadial: {default: 8, min: 3, type: 'int'},
  51875. segmentsTubular: {default: 100, min: 3, type: 'int'}
  51876. },
  51877. init: function (data) {
  51878. this.geometry = new THREE.TorusKnotGeometry(
  51879. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  51880. data.p, data.q);
  51881. }
  51882. });
  51883. },{"../core/geometry":104,"../lib/three":151}],148:[function(_dereq_,module,exports){
  51884. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51885. var THREE = _dereq_('../lib/three');
  51886. var quaternion = new THREE.Quaternion();
  51887. var rotateVector = new THREE.Vector3(0, 0, 1);
  51888. var uvMinVector = new THREE.Vector2();
  51889. var uvMaxVector = new THREE.Vector2();
  51890. var uvScaleVector = new THREE.Vector2();
  51891. registerGeometry('triangle', {
  51892. schema: {
  51893. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  51894. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  51895. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  51896. },
  51897. init: function (data) {
  51898. var geometry;
  51899. var normal;
  51900. var triangle;
  51901. var uvA;
  51902. var uvB;
  51903. var uvC;
  51904. triangle = new THREE.Triangle();
  51905. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  51906. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  51907. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  51908. normal = triangle.normal();
  51909. // Rotate the 3D triangle to be parallel to XY plane.
  51910. quaternion.setFromUnitVectors(normal, rotateVector);
  51911. uvA = triangle.a.clone().applyQuaternion(quaternion);
  51912. uvB = triangle.b.clone().applyQuaternion(quaternion);
  51913. uvC = triangle.c.clone().applyQuaternion(quaternion);
  51914. // Compute UVs.
  51915. // Normalize x/y values of UV so they are within 0 to 1.
  51916. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  51917. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  51918. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  51919. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  51920. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  51921. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  51922. geometry = this.geometry = new THREE.Geometry();
  51923. geometry.vertices.push(triangle.a);
  51924. geometry.vertices.push(triangle.b);
  51925. geometry.vertices.push(triangle.c);
  51926. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  51927. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  51928. }
  51929. });
  51930. },{"../core/geometry":104,"../lib/three":151}],149:[function(_dereq_,module,exports){
  51931. // Check before the polyfill runs.
  51932. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays || !!window.navigator.getVRDevices;
  51933. // WebVR polyfill
  51934. var WebVRPolyfill = _dereq_('webvr-polyfill');
  51935. window.webvrpolyfill = new WebVRPolyfill({
  51936. BUFFER_SCALE: 1,
  51937. CARDBOARD_UI_DISABLED: true,
  51938. ROTATE_INSTRUCTIONS_DISABLED: true
  51939. });
  51940. var utils = _dereq_('./utils/');
  51941. var debug = utils.debug;
  51942. var error = debug('A-Frame:error');
  51943. var warn = debug('A-Frame:warn');
  51944. if (window.document.currentScript && window.document.currentScript.parentNode !==
  51945. window.document.head && !window.debug) {
  51946. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  51947. 'ensure everything for A-Frame is properly registered before they are used from ' +
  51948. 'HTML.');
  51949. }
  51950. // Error if not using a server.
  51951. if (window.location.protocol === 'file:') {
  51952. error(
  51953. 'This HTML file is currently being served via the file:// protocol. ' +
  51954. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  51955. 'Please use a local or hosted server: ' +
  51956. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  51957. }
  51958. // Polyfill `Promise`.
  51959. window.Promise = window.Promise || _dereq_('promise-polyfill');
  51960. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  51961. // Only for iOS on versions older than 10.
  51962. if (utils.device.isIOSOlderThan10(window.navigator.userAgent)) {
  51963. window.WebVRConfig.BUFFER_SCALE = 1 / window.devicePixelRatio;
  51964. }
  51965. _dereq_('present'); // Polyfill `performance.now()`.
  51966. // CSS.
  51967. if (utils.device.isBrowserEnvironment) {
  51968. _dereq_('./style/aframe.css');
  51969. _dereq_('./style/rStats.css');
  51970. }
  51971. // Required before `AEntity` so that all components are registered.
  51972. var AScene = _dereq_('./core/scene/a-scene').AScene;
  51973. var components = _dereq_('./core/component').components;
  51974. var registerComponent = _dereq_('./core/component').registerComponent;
  51975. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  51976. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  51977. var registerShader = _dereq_('./core/shader').registerShader;
  51978. var registerSystem = _dereq_('./core/system').registerSystem;
  51979. var shaders = _dereq_('./core/shader').shaders;
  51980. var systems = _dereq_('./core/system').systems;
  51981. // Exports THREE to window so three.js can be used without alteration.
  51982. var THREE = window.THREE = _dereq_('./lib/three');
  51983. var TWEEN = window.TWEEN = _dereq_('@tweenjs/tween.js');
  51984. var pkg = _dereq_('../package');
  51985. _dereq_('./components/index'); // Register standard components.
  51986. _dereq_('./geometries/index'); // Register standard geometries.
  51987. _dereq_('./shaders/index'); // Register standard shaders.
  51988. _dereq_('./systems/index'); // Register standard systems.
  51989. var ANode = _dereq_('./core/a-node');
  51990. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  51991. _dereq_('./core/a-animation');
  51992. _dereq_('./core/a-assets');
  51993. _dereq_('./core/a-cubemap');
  51994. _dereq_('./core/a-mixin');
  51995. // Extras.
  51996. _dereq_('./extras/components/');
  51997. _dereq_('./extras/primitives/');
  51998. console.log('A-Frame Version: 0.8.2 (Date 2018-05-10, Commit #e4e40b0)');
  51999. console.log('three Version:', pkg.dependencies['three']);
  52000. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  52001. module.exports = window.AFRAME = {
  52002. AComponent: _dereq_('./core/component').Component,
  52003. AEntity: AEntity,
  52004. ANode: ANode,
  52005. AScene: AScene,
  52006. components: components,
  52007. geometries: _dereq_('./core/geometry').geometries,
  52008. registerComponent: registerComponent,
  52009. registerElement: _dereq_('./core/a-register-element').registerElement,
  52010. registerGeometry: registerGeometry,
  52011. registerPrimitive: registerPrimitive,
  52012. registerShader: registerShader,
  52013. registerSystem: registerSystem,
  52014. primitives: {
  52015. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  52016. primitives: _dereq_('./extras/primitives/primitives').primitives
  52017. },
  52018. scenes: _dereq_('./core/scene/scenes'),
  52019. schema: _dereq_('./core/schema'),
  52020. shaders: shaders,
  52021. systems: systems,
  52022. THREE: THREE,
  52023. TWEEN: TWEEN,
  52024. utils: utils,
  52025. version: pkg.version
  52026. };
  52027. },{"../package":51,"./components/index":60,"./core/a-animation":96,"./core/a-assets":97,"./core/a-cubemap":98,"./core/a-entity":99,"./core/a-mixin":100,"./core/a-node":101,"./core/a-register-element":102,"./core/component":103,"./core/geometry":104,"./core/scene/a-scene":106,"./core/scene/scenes":109,"./core/schema":111,"./core/shader":112,"./core/system":113,"./extras/components/":114,"./extras/primitives/":117,"./extras/primitives/getMeshMixin":116,"./extras/primitives/primitives":118,"./geometries/index":140,"./lib/three":151,"./shaders/index":153,"./style/aframe.css":158,"./style/rStats.css":159,"./systems/index":162,"./utils/":173,"@tweenjs/tween.js":1,"present":31,"promise-polyfill":33,"webvr-polyfill":46}],150:[function(_dereq_,module,exports){
  52028. window.aframeStats = function (scene) {
  52029. var _rS = null;
  52030. var _scene = scene;
  52031. var _values = {
  52032. te: {
  52033. caption: 'Entities'
  52034. },
  52035. lt: {
  52036. caption: 'Load Time'
  52037. }
  52038. };
  52039. var _groups = [ {
  52040. caption: 'A-Frame',
  52041. values: [ 'te', 'lt' ]
  52042. } ];
  52043. function _update () {
  52044. _rS('te').set(getEntityCount());
  52045. if (window.performance.getEntriesByName) {
  52046. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  52047. }
  52048. }
  52049. function getEntityCount () {
  52050. var elements = _scene.querySelectorAll('*');
  52051. Array.prototype.slice.call(elements).filter(function (el) {
  52052. return el.isEntity;
  52053. });
  52054. return elements.length;
  52055. }
  52056. function _start () {}
  52057. function _end () {}
  52058. function _attach (r) {
  52059. _rS = r;
  52060. }
  52061. return {
  52062. update: _update,
  52063. start: _start,
  52064. end: _end,
  52065. attach: _attach,
  52066. values: _values,
  52067. groups: _groups,
  52068. fractions: []
  52069. };
  52070. };
  52071. if (typeof module === 'object') {
  52072. module.exports = {
  52073. aframeStats: window.aframeStats
  52074. };
  52075. }
  52076. },{}],151:[function(_dereq_,module,exports){
  52077. (function (global){
  52078. var THREE = global.THREE = _dereq_('three');
  52079. // Allow cross-origin images to be loaded.
  52080. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  52081. // Must be on `THREE.TextureLoader`.
  52082. if (THREE.TextureLoader) {
  52083. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  52084. }
  52085. // This is for images loaded from the model loaders.
  52086. if (THREE.ImageLoader) {
  52087. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  52088. }
  52089. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  52090. if (THREE.Cache) {
  52091. THREE.Cache.enabled = true;
  52092. }
  52093. // TODO: Eventually include these only if they are needed by a component.
  52094. _dereq_('three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  52095. _dereq_('three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  52096. _dereq_('three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  52097. _dereq_('three/examples/js/loaders/ColladaLoader'); // THREE.ColladaLoader
  52098. THREE.ColladaLoader.prototype.crossOrigin = 'anonymous';
  52099. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  52100. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  52101. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  52102. module.exports = THREE;
  52103. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  52104. },{"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}],152:[function(_dereq_,module,exports){
  52105. var registerShader = _dereq_('../core/shader').registerShader;
  52106. var THREE = _dereq_('../lib/three');
  52107. var utils = _dereq_('../utils/');
  52108. /**
  52109. * Flat shader using THREE.MeshBasicMaterial.
  52110. */
  52111. module.exports.Shader = registerShader('flat', {
  52112. schema: {
  52113. color: {type: 'color'},
  52114. fog: {default: true},
  52115. height: {default: 256},
  52116. offset: {type: 'vec2', default: {x: 0, y: 0}},
  52117. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  52118. src: {type: 'map'},
  52119. width: {default: 512},
  52120. wireframe: {default: false},
  52121. wireframeLinewidth: {default: 2}
  52122. },
  52123. /**
  52124. * Initializes the shader.
  52125. * Adds a reference from the scene to this entity as the camera.
  52126. */
  52127. init: function (data) {
  52128. this.textureSrc = null;
  52129. this.material = new THREE.MeshBasicMaterial(getMaterialData(data));
  52130. utils.material.updateMap(this, data);
  52131. },
  52132. update: function (data) {
  52133. this.updateMaterial(data);
  52134. utils.material.updateMap(this, data);
  52135. },
  52136. /**
  52137. * Updating existing material.
  52138. *
  52139. * @param {object} data - Material component data.
  52140. */
  52141. updateMaterial: function (data) {
  52142. var material = this.material;
  52143. data = getMaterialData(data);
  52144. Object.keys(data).forEach(function (key) {
  52145. material[key] = data[key];
  52146. });
  52147. }
  52148. });
  52149. /**
  52150. * Builds and normalize material data, normalizing stuff along the way.
  52151. *
  52152. * @param {object} data - Material data.
  52153. * @returns {object} data - Processed material data.
  52154. */
  52155. function getMaterialData (data) {
  52156. return {
  52157. fog: data.fog,
  52158. color: new THREE.Color(data.color),
  52159. wireframe: data.wireframe,
  52160. wireframeLinewidth: data.wireframeLinewidth
  52161. };
  52162. }
  52163. },{"../core/shader":112,"../lib/three":151,"../utils/":173}],153:[function(_dereq_,module,exports){
  52164. _dereq_('./flat');
  52165. _dereq_('./standard');
  52166. _dereq_('./sdf');
  52167. _dereq_('./msdf');
  52168. _dereq_('./ios10hls');
  52169. },{"./flat":152,"./ios10hls":154,"./msdf":155,"./sdf":156,"./standard":157}],154:[function(_dereq_,module,exports){
  52170. var registerShader = _dereq_('../core/shader').registerShader;
  52171. /**
  52172. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  52173. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  52174. */
  52175. module.exports.Shader = registerShader('ios10hls', {
  52176. schema: {
  52177. src: {type: 'map', is: 'uniform'},
  52178. opacity: {type: 'number', is: 'uniform', default: 1}
  52179. },
  52180. vertexShader: [
  52181. 'varying vec2 vUV;',
  52182. 'void main(void) {',
  52183. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  52184. ' vUV = uv;',
  52185. '}'
  52186. ].join('\n'),
  52187. fragmentShader: [
  52188. 'uniform sampler2D src;',
  52189. 'uniform float opacity;',
  52190. 'varying vec2 vUV;',
  52191. 'void main() {',
  52192. ' vec2 offset = vec2(0, 0);',
  52193. ' vec2 repeat = vec2(1, 1);',
  52194. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  52195. ' gl_FragColor = vec4(color.rgb, opacity);',
  52196. '}'
  52197. ].join('\n')
  52198. });
  52199. },{"../core/shader":112}],155:[function(_dereq_,module,exports){
  52200. var registerShader = _dereq_('../core/shader').registerShader;
  52201. /**
  52202. * Multi-channel signed distance field.
  52203. * Used by text component.
  52204. */
  52205. module.exports.Shader = registerShader('msdf', {
  52206. schema: {
  52207. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  52208. color: {type: 'color', is: 'uniform', default: 'white'},
  52209. map: {type: 'map', is: 'uniform'},
  52210. negate: {type: 'boolean', is: 'uniform', default: true},
  52211. opacity: {type: 'number', is: 'uniform', default: 1.0}
  52212. },
  52213. raw: true,
  52214. vertexShader: [
  52215. 'attribute vec2 uv;',
  52216. 'attribute vec3 position;',
  52217. 'uniform mat4 projectionMatrix;',
  52218. 'uniform mat4 modelViewMatrix;',
  52219. 'varying vec2 vUV;',
  52220. 'void main(void) {',
  52221. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  52222. ' vUV = uv;',
  52223. '}'
  52224. ].join('\n'),
  52225. fragmentShader: [
  52226. '#ifdef GL_OES_standard_derivatives',
  52227. '#extension GL_OES_standard_derivatives: enable',
  52228. '#endif',
  52229. 'precision highp float;',
  52230. // FIXME: Experimentally determined constants.
  52231. '#define BIG_ENOUGH 0.001',
  52232. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  52233. '#define ALL_SMOOTH 0.4',
  52234. '#define ALL_ROUGH 0.02',
  52235. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  52236. 'uniform sampler2D map;',
  52237. 'uniform vec3 color;',
  52238. 'uniform float opacity;',
  52239. 'uniform float alphaTest;',
  52240. 'uniform bool negate;',
  52241. 'varying vec2 vUV;',
  52242. 'float median(float r, float g, float b) {',
  52243. ' return max(min(r, g), min(max(r, g), b));',
  52244. '}',
  52245. 'void main() {',
  52246. ' vec3 sample = texture2D(map, vUV).rgb;',
  52247. ' if (negate) {',
  52248. ' sample = 1.0 - sample;',
  52249. ' }',
  52250. ' float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
  52251. ' float alpha = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0);',
  52252. ' float dscale = 0.353505;',
  52253. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  52254. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  52255. // When texel is too small, blend raw alpha value rather than supersampling.
  52256. // FIXME: Experimentally determined constant.
  52257. ' if (isBigEnough > BIG_ENOUGH) {',
  52258. ' float ratio = BIG_ENOUGH / isBigEnough;',
  52259. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  52260. ' }',
  52261. // When texel is big enough, do standard alpha test.
  52262. // FIXME: Experimentally determined constant.
  52263. // Looks much better if we *don't* do this, but do we get Z fighting?
  52264. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  52265. // Else, do modified alpha test.
  52266. // FIXME: Experimentally determined constant.
  52267. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  52268. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  52269. '}'
  52270. ].join('\n')
  52271. });
  52272. },{"../core/shader":112}],156:[function(_dereq_,module,exports){
  52273. var registerShader = _dereq_('../core/shader').registerShader;
  52274. /**
  52275. * Signed distance field.
  52276. * Used by text component.
  52277. */
  52278. module.exports.Shader = registerShader('sdf', {
  52279. schema: {
  52280. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  52281. color: {type: 'color', is: 'uniform', default: 'white'},
  52282. map: {type: 'map', is: 'uniform'},
  52283. opacity: {type: 'number', is: 'uniform', default: 1.0}
  52284. },
  52285. raw: true,
  52286. vertexShader: [
  52287. 'attribute vec2 uv;',
  52288. 'attribute vec3 position;',
  52289. 'uniform mat4 projectionMatrix;',
  52290. 'uniform mat4 modelViewMatrix;',
  52291. 'varying vec2 vUV;',
  52292. 'void main(void) {',
  52293. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  52294. ' vUV = uv;',
  52295. '}'
  52296. ].join('\n'),
  52297. fragmentShader: [
  52298. '#ifdef GL_OES_standard_derivatives',
  52299. '#extension GL_OES_standard_derivatives: enable',
  52300. '#endif',
  52301. 'precision highp float;',
  52302. // FIXME: experimentally determined constants
  52303. '#define BIG_ENOUGH 0.001',
  52304. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  52305. '#define ALL_SMOOTH 0.4',
  52306. '#define ALL_ROUGH 0.02',
  52307. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  52308. 'uniform sampler2D map;',
  52309. 'uniform vec3 color;',
  52310. 'uniform float opacity;',
  52311. 'uniform float alphaTest;',
  52312. 'varying vec2 vUV;',
  52313. '#ifdef GL_OES_standard_derivatives',
  52314. 'float contour(float width, float value) {',
  52315. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  52316. '}',
  52317. '#else',
  52318. 'float aastep(float value, float afwidth) {',
  52319. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  52320. '}',
  52321. '#endif',
  52322. 'void main() {',
  52323. '#ifdef GL_OES_standard_derivatives',
  52324. // when we have derivatives and can get texel size etc., that allows supersampling etc.
  52325. ' vec2 uv = vUV;',
  52326. ' vec4 texColor = texture2D(map, uv);',
  52327. ' float dist = texColor.a;',
  52328. ' float width = fwidth(dist);',
  52329. ' float alpha = contour(dist, width);',
  52330. ' float dscale = 0.353505;',
  52331. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  52332. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  52333. // when texel is too small, blend raw alpha value rather than supersampling etc.
  52334. // FIXME: experimentally determined constant
  52335. ' if (isBigEnough > BIG_ENOUGH) {',
  52336. ' float ratio = BIG_ENOUGH / isBigEnough;',
  52337. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  52338. ' }',
  52339. // otherwise do weighted supersampling
  52340. // FIXME: why this weighting?
  52341. ' else if (isBigEnough <= BIG_ENOUGH) {',
  52342. ' vec4 box = vec4 (uv - duv, uv + duv);',
  52343. ' alpha = (alpha + 0.5 * (',
  52344. ' contour(texture2D(map, box.xy).a, width)',
  52345. ' + contour(texture2D(map, box.zw).a, width)',
  52346. ' + contour(texture2D(map, box.xw).a, width)',
  52347. ' + contour(texture2D(map, box.zy).a, width)',
  52348. ' )) / 3.0;',
  52349. ' }',
  52350. // when texel is big enough, do standard alpha test
  52351. // FIXME: experimentally determined constant
  52352. // looks much better if we DON'T do this, but do we get Z fighting etc.?
  52353. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  52354. // else do modified alpha test
  52355. // FIXME: experimentally determined constant
  52356. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  52357. '#else',
  52358. ' vec4 texColor = texture2D(map, vUV);',
  52359. ' float value = texColor.a;',
  52360. // when we don't have derivatives, use approximations
  52361. // FIXME: if we understood font pixel dimensions, this could probably be improved
  52362. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  52363. ' float alpha = aastep(value, afwidth);',
  52364. // use gl_FragCoord.w to guess when we should blend
  52365. // FIXME: if we understood font pixel dimensions, this could probably be improved
  52366. ' 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);',
  52367. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  52368. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  52369. ' if (ratio < 1.0)',
  52370. ' if (alpha <= DISCARD_ALPHA) { discard; return; }',
  52371. '#endif',
  52372. ' gl_FragColor = vec4(color, opacity * alpha);',
  52373. '}'
  52374. ].join('\n')
  52375. });
  52376. },{"../core/shader":112}],157:[function(_dereq_,module,exports){
  52377. var registerShader = _dereq_('../core/shader').registerShader;
  52378. var THREE = _dereq_('../lib/three');
  52379. var utils = _dereq_('../utils/');
  52380. var CubeLoader = new THREE.CubeTextureLoader();
  52381. var texturePromises = {};
  52382. /**
  52383. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  52384. */
  52385. module.exports.Shader = registerShader('standard', {
  52386. schema: {
  52387. ambientOcclusionMap: {type: 'map'},
  52388. ambientOcclusionMapIntensity: {default: 1},
  52389. ambientOcclusionTextureOffset: {type: 'vec2'},
  52390. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52391. color: {type: 'color'},
  52392. displacementMap: {type: 'map'},
  52393. displacementScale: {default: 1},
  52394. displacementBias: {default: 0.5},
  52395. displacementTextureOffset: {type: 'vec2'},
  52396. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52397. emissive: {type: 'color', default: '#000'},
  52398. emissiveIntensity: {default: 1},
  52399. envMap: {default: ''},
  52400. fog: {default: true},
  52401. height: {default: 256},
  52402. metalness: {default: 0.0, min: 0.0, max: 1.0},
  52403. metalnessMap: {type: 'map'},
  52404. metalnessTextureOffset: {type: 'vec2'},
  52405. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52406. normalMap: {type: 'map'},
  52407. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  52408. normalTextureOffset: {type: 'vec2'},
  52409. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52410. offset: {type: 'vec2', default: {x: 0, y: 0}},
  52411. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  52412. roughness: {default: 0.5, min: 0.0, max: 1.0},
  52413. roughnessMap: {type: 'map'},
  52414. roughnessTextureOffset: {type: 'vec2'},
  52415. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52416. sphericalEnvMap: {type: 'map'},
  52417. src: {type: 'map'},
  52418. width: {default: 512},
  52419. wireframe: {default: false},
  52420. wireframeLinewidth: {default: 2}
  52421. },
  52422. /**
  52423. * Initializes the shader.
  52424. * Adds a reference from the scene to this entity as the camera.
  52425. */
  52426. init: function (data) {
  52427. this.material = new THREE.MeshStandardMaterial(getMaterialData(data));
  52428. utils.material.updateMap(this, data);
  52429. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  52430. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  52431. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  52432. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  52433. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  52434. this.updateEnvMap(data);
  52435. },
  52436. update: function (data) {
  52437. this.updateMaterial(data);
  52438. utils.material.updateMap(this, data);
  52439. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  52440. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  52441. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  52442. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  52443. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  52444. this.updateEnvMap(data);
  52445. },
  52446. /**
  52447. * Updating existing material.
  52448. *
  52449. * @param {object} data - Material component data.
  52450. * @returns {object} Material.
  52451. */
  52452. updateMaterial: function (data) {
  52453. var material = this.material;
  52454. data = getMaterialData(data);
  52455. Object.keys(data).forEach(function (key) {
  52456. material[key] = data[key];
  52457. });
  52458. },
  52459. /**
  52460. * Handle environment cubemap. Textures are cached in texturePromises.
  52461. */
  52462. updateEnvMap: function (data) {
  52463. var self = this;
  52464. var material = this.material;
  52465. var envMap = data.envMap;
  52466. var sphericalEnvMap = data.sphericalEnvMap;
  52467. // No envMap defined or already loading.
  52468. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  52469. material.envMap = null;
  52470. material.needsUpdate = true;
  52471. return;
  52472. }
  52473. this.isLoadingEnvMap = true;
  52474. // if a spherical env map is defined then use it.
  52475. if (sphericalEnvMap) {
  52476. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  52477. self.isLoadingEnvMap = false;
  52478. texture.mapping = THREE.SphericalReflectionMapping;
  52479. material.envMap = texture;
  52480. utils.material.handleTextureEvents(self.el, texture);
  52481. material.needsUpdate = true;
  52482. });
  52483. return;
  52484. }
  52485. // Another material is already loading this texture. Wait on promise.
  52486. if (texturePromises[envMap]) {
  52487. texturePromises[envMap].then(function (cube) {
  52488. self.isLoadingEnvMap = false;
  52489. material.envMap = cube;
  52490. utils.material.handleTextureEvents(self.el, cube);
  52491. material.needsUpdate = true;
  52492. });
  52493. return;
  52494. }
  52495. // Material is first to load this texture. Load and resolve texture.
  52496. texturePromises[envMap] = new Promise(function (resolve) {
  52497. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  52498. CubeLoader.load(urls, function (cube) {
  52499. // Texture loaded.
  52500. self.isLoadingEnvMap = false;
  52501. material.envMap = cube;
  52502. utils.material.handleTextureEvents(self.el, cube);
  52503. resolve(cube);
  52504. });
  52505. });
  52506. });
  52507. }
  52508. });
  52509. /**
  52510. * Builds and normalize material data, normalizing stuff along the way.
  52511. *
  52512. * @param {object} data - Material data.
  52513. * @returns {object} data - Processed material data.
  52514. */
  52515. function getMaterialData (data) {
  52516. var newData = {
  52517. color: new THREE.Color(data.color),
  52518. emissive: new THREE.Color(data.emissive),
  52519. emissiveIntensity: data.emissiveIntensity,
  52520. fog: data.fog,
  52521. metalness: data.metalness,
  52522. roughness: data.roughness,
  52523. wireframe: data.wireframe,
  52524. wireframeLinewidth: data.wireframeLinewidth
  52525. };
  52526. if (data.normalMap) { newData.normalScale = data.normalScale; }
  52527. if (data.ambientOcclusionMap) { newData.aoMapIntensity = data.ambientOcclusionMapIntensity; }
  52528. if (data.displacementMap) {
  52529. newData.displacementScale = data.displacementScale;
  52530. newData.displacementBias = data.displacementBias;
  52531. }
  52532. return newData;
  52533. }
  52534. },{"../core/shader":112,"../lib/three":151,"../utils/":173}],158:[function(_dereq_,module,exports){
  52535. 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;
  52536. },{"browserify-css":5}],159:[function(_dereq_,module,exports){
  52537. 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;
  52538. },{"browserify-css":5}],160:[function(_dereq_,module,exports){
  52539. var constants = _dereq_('../constants/');
  52540. var registerSystem = _dereq_('../core/system').registerSystem;
  52541. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  52542. /**
  52543. * Camera system. Manages which camera is active among multiple cameras in scene.
  52544. *
  52545. * @member {object} activeCameraEl - Active camera entity.
  52546. */
  52547. module.exports.System = registerSystem('camera', {
  52548. init: function () {
  52549. this.activeCameraEl = null;
  52550. this.bindMethods();
  52551. // Wait for all entities to fully load before checking for existence of camera.
  52552. // Since entities wait for <a-assets> to load, any cameras attaching to the scene
  52553. // will do so asynchronously.
  52554. this.sceneEl.addEventListener('loaded', this.setupDefaultCamera);
  52555. },
  52556. bindMethods: function () {
  52557. this.setupDefaultCamera = this.setupDefaultCamera.bind(this);
  52558. this.wrapRender = this.wrapRender.bind(this);
  52559. this.unwrapRender = this.unwrapRender.bind(this);
  52560. this.render = this.render.bind(this);
  52561. },
  52562. /**
  52563. * Create a default camera if user has not added one during the initial scene traversal.
  52564. *
  52565. * Default camera offset height is at average eye level (~1.6m).
  52566. */
  52567. setupDefaultCamera: function () {
  52568. var sceneEl = this.sceneEl;
  52569. var defaultCameraEl;
  52570. // Camera already defined or the one defined it is an spectator one.
  52571. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  52572. sceneEl.emit('camera-ready', {cameraEl: sceneEl.camera.el});
  52573. return;
  52574. }
  52575. // Set up default camera.
  52576. defaultCameraEl = document.createElement('a-entity');
  52577. defaultCameraEl.setAttribute('camera', {active: true});
  52578. defaultCameraEl.setAttribute('wasd-controls', '');
  52579. defaultCameraEl.setAttribute('look-controls', '');
  52580. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  52581. defaultCameraEl.setAttribute('position', {
  52582. x: 0,
  52583. y: constants.DEFAULT_CAMERA_HEIGHT,
  52584. z: 0
  52585. });
  52586. sceneEl.appendChild(defaultCameraEl);
  52587. sceneEl.emit('camera-ready', {cameraEl: defaultCameraEl});
  52588. },
  52589. /**
  52590. * Set a different active camera.
  52591. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  52592. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  52593. * the new camera.
  52594. */
  52595. disableActiveCamera: function () {
  52596. var cameraEls = this.sceneEl.querySelectorAll('[camera]');
  52597. var newActiveCameraEl = cameraEls[cameraEls.length - 1];
  52598. newActiveCameraEl.setAttribute('camera', 'active', true);
  52599. },
  52600. /**
  52601. * Set active camera to be used by renderer.
  52602. * Removes the default camera (if present).
  52603. * Disables all other cameras in the scene.
  52604. *
  52605. * @param {Element} newCameraEl - Entity with camera component.
  52606. */
  52607. setActiveCamera: function (newCameraEl) {
  52608. var cameraEl;
  52609. var cameraEls;
  52610. var i;
  52611. var newCamera;
  52612. var previousCamera = this.activeCameraEl;
  52613. var sceneEl = this.sceneEl;
  52614. // Same camera.
  52615. newCamera = newCameraEl.getObject3D('camera');
  52616. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  52617. // Grab the default camera.
  52618. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  52619. var defaultCameraEl = defaultCameraWrapper &&
  52620. defaultCameraWrapper.querySelector('[camera]');
  52621. // Remove default camera if new camera is not the default camera.
  52622. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  52623. // Make new camera active.
  52624. this.activeCameraEl = newCameraEl;
  52625. this.activeCameraEl.play();
  52626. sceneEl.camera = newCamera;
  52627. // Disable current camera
  52628. if (previousCamera) {
  52629. previousCamera.setAttribute('camera', 'active', false);
  52630. }
  52631. // Disable other cameras in the scene
  52632. cameraEls = sceneEl.querySelectorAll('[camera]');
  52633. for (i = 0; i < cameraEls.length; i++) {
  52634. cameraEl = cameraEls[i];
  52635. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  52636. cameraEl.setAttribute('camera', 'active', false);
  52637. cameraEl.pause();
  52638. }
  52639. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  52640. },
  52641. /**
  52642. * Set spectator camera to render the scene on a 2D display.
  52643. *
  52644. * @param {Element} newCameraEl - Entity with camera component.
  52645. */
  52646. setSpectatorCamera: function (newCameraEl) {
  52647. var newCamera;
  52648. var previousCamera = this.spectatorCameraEl;
  52649. var sceneEl = this.sceneEl;
  52650. var spectatorCameraEl;
  52651. // Same camera.
  52652. newCamera = newCameraEl.getObject3D('camera');
  52653. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  52654. // Disable current camera
  52655. if (previousCamera) {
  52656. previousCamera.setAttribute('camera', 'spectator', false);
  52657. }
  52658. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  52659. sceneEl.addEventListener('enter-vr', this.wrapRender);
  52660. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  52661. spectatorCameraEl.setAttribute('camera', 'active', false);
  52662. spectatorCameraEl.play();
  52663. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  52664. },
  52665. /**
  52666. * Disables current spectator camera.
  52667. */
  52668. disableSpectatorCamera: function () {
  52669. this.spectatorCameraEl = undefined;
  52670. },
  52671. /**
  52672. * Wrap the render method of the renderer to render
  52673. * the spectator camera after vrDisplay.submitFrame.
  52674. */
  52675. wrapRender: function () {
  52676. if (!this.spectatorCameraEl) { return; }
  52677. this.originalRender = this.sceneEl.renderer.render;
  52678. this.sceneEl.renderer.render = this.render;
  52679. },
  52680. unwrapRender: function () {
  52681. if (!this.originalRender) { return; }
  52682. this.sceneEl.renderer.render = this.originalRender;
  52683. this.originalRender = undefined;
  52684. },
  52685. render: function (scene, camera, renderTarget) {
  52686. var spectatorCamera;
  52687. var sceneEl = this.sceneEl;
  52688. var isVREnabled = sceneEl.renderer.vr.enabled;
  52689. this.originalRender.call(sceneEl.renderer, scene, camera, renderTarget);
  52690. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  52691. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  52692. sceneEl.renderer.vr.enabled = false;
  52693. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  52694. sceneEl.renderer.vr.enabled = isVREnabled;
  52695. }
  52696. });
  52697. /**
  52698. * Remove injected default camera from scene, if present.
  52699. *
  52700. * @param {Element} sceneEl
  52701. */
  52702. function removeDefaultCamera (sceneEl) {
  52703. var defaultCamera;
  52704. var camera = sceneEl.camera;
  52705. if (!camera) { return; }
  52706. // Remove default camera if present.
  52707. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  52708. if (!defaultCamera) { return; }
  52709. sceneEl.removeChild(defaultCamera);
  52710. }
  52711. },{"../constants/":94,"../core/system":113}],161:[function(_dereq_,module,exports){
  52712. var geometries = _dereq_('../core/geometry').geometries;
  52713. var registerSystem = _dereq_('../core/system').registerSystem;
  52714. var THREE = _dereq_('../lib/three');
  52715. /**
  52716. * System for geometry component.
  52717. * Handle geometry caching.
  52718. *
  52719. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  52720. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  52721. * know whether to dispose on removal.
  52722. */
  52723. module.exports.System = registerSystem('geometry', {
  52724. init: function () {
  52725. this.cache = {};
  52726. this.cacheCount = {};
  52727. },
  52728. /**
  52729. * Reset cache. Mainly for testing.
  52730. */
  52731. clearCache: function () {
  52732. this.cache = {};
  52733. this.cacheCount = {};
  52734. },
  52735. /**
  52736. * Attempt to retrieve from cache.
  52737. *
  52738. * @returns {Object|null} A geometry if it exists, else null.
  52739. */
  52740. getOrCreateGeometry: function (data) {
  52741. var cache = this.cache;
  52742. var cachedGeometry;
  52743. var hash;
  52744. // Skip all caching logic.
  52745. if (data.skipCache) { return createGeometry(data); }
  52746. // Try to retrieve from cache first.
  52747. hash = this.hash(data);
  52748. cachedGeometry = cache[hash];
  52749. incrementCacheCount(this.cacheCount, hash);
  52750. if (cachedGeometry) { return cachedGeometry; }
  52751. // Create geometry.
  52752. cachedGeometry = createGeometry(data);
  52753. // Cache and return geometry.
  52754. cache[hash] = cachedGeometry;
  52755. return cachedGeometry;
  52756. },
  52757. /**
  52758. * Let system know that an entity is no longer using a geometry.
  52759. */
  52760. unuseGeometry: function (data) {
  52761. var cache = this.cache;
  52762. var cacheCount = this.cacheCount;
  52763. var geometry;
  52764. var hash;
  52765. if (data.skipCache) { return; }
  52766. hash = this.hash(data);
  52767. if (!cache[hash]) { return; }
  52768. decrementCacheCount(cacheCount, hash);
  52769. // Another entity is still using this geometry. No need to do anything.
  52770. if (cacheCount[hash] > 0) { return; }
  52771. // No more entities are using this geometry. Dispose.
  52772. geometry = cache[hash];
  52773. geometry.dispose();
  52774. delete cache[hash];
  52775. delete cacheCount[hash];
  52776. },
  52777. /**
  52778. * Use JSON.stringify to turn component data into hash.
  52779. * Should be deterministic within a single browser engine.
  52780. * If not, then look into json-stable-stringify.
  52781. */
  52782. hash: function (data) {
  52783. return JSON.stringify(data);
  52784. }
  52785. });
  52786. /**
  52787. * Create geometry using component data.
  52788. *
  52789. * @param {object} data - Component data.
  52790. * @returns {object} Geometry.
  52791. */
  52792. function createGeometry (data) {
  52793. var geometryType = data.primitive;
  52794. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  52795. var geometryInstance = new GeometryClass();
  52796. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  52797. geometryInstance.init(data);
  52798. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  52799. }
  52800. /**
  52801. * Decreate count of entity using a geometry.
  52802. */
  52803. function decrementCacheCount (cacheCount, hash) {
  52804. cacheCount[hash]--;
  52805. }
  52806. /**
  52807. * Increase count of entity using a geometry.
  52808. */
  52809. function incrementCacheCount (cacheCount, hash) {
  52810. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  52811. }
  52812. /**
  52813. * Transform geometry to BufferGeometry if `doBuffer`.
  52814. *
  52815. * @param {object} geometry
  52816. * @param {boolean} doBuffer
  52817. * @returns {object} Geometry.
  52818. */
  52819. function toBufferGeometry (geometry, doBuffer) {
  52820. var bufferGeometry;
  52821. if (!doBuffer) { return geometry; }
  52822. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  52823. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  52824. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  52825. return bufferGeometry;
  52826. }
  52827. },{"../core/geometry":104,"../core/system":113,"../lib/three":151}],162:[function(_dereq_,module,exports){
  52828. _dereq_('./camera');
  52829. _dereq_('./geometry');
  52830. _dereq_('./light');
  52831. _dereq_('./material');
  52832. _dereq_('./shadow');
  52833. _dereq_('./tracked-controls');
  52834. },{"./camera":160,"./geometry":161,"./light":163,"./material":164,"./shadow":165,"./tracked-controls":166}],163:[function(_dereq_,module,exports){
  52835. var registerSystem = _dereq_('../core/system').registerSystem;
  52836. var bind = _dereq_('../utils/bind');
  52837. var constants = _dereq_('../constants/');
  52838. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  52839. /**
  52840. * Light system.
  52841. *
  52842. * Prescribes default lighting if not specified (one ambient, one directional).
  52843. * Removes default lighting from the scene when a new light is added.
  52844. *
  52845. * @param {bool} defaultLights - Whether default lighting are defined.
  52846. * @param {bool} userDefinedLights - Whether user lighting is defined.
  52847. */
  52848. module.exports.System = registerSystem('light', {
  52849. schema: {
  52850. defaultLightsEnabled: {default: true}
  52851. },
  52852. init: function () {
  52853. this.defaultLights = false;
  52854. this.userDefinedLights = false;
  52855. // Wait for all entities to fully load before checking for existence of lights.
  52856. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  52857. // will do so asynchronously.
  52858. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  52859. },
  52860. /**
  52861. * Notify scene that light has been added and to remove the default.
  52862. *
  52863. * @param {object} el - element holding the light component.
  52864. */
  52865. registerLight: function (el) {
  52866. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  52867. // User added a light, remove default lights through DOM.
  52868. this.removeDefaultLights();
  52869. this.userDefinedLights = true;
  52870. }
  52871. },
  52872. removeDefaultLights: function () {
  52873. var defaultLights;
  52874. var sceneEl = this.sceneEl;
  52875. if (!this.defaultLights) { return; }
  52876. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  52877. for (var i = 0; i < defaultLights.length; i++) {
  52878. sceneEl.removeChild(defaultLights[i]);
  52879. }
  52880. this.defaultLights = false;
  52881. },
  52882. /**
  52883. * Prescibe default lights to the scene.
  52884. * Does so by injecting markup such that this state is not invisible.
  52885. * These lights are removed if the user adds any lights.
  52886. */
  52887. setupDefaultLights: function () {
  52888. var sceneEl = this.sceneEl;
  52889. var ambientLight;
  52890. var directionalLight;
  52891. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  52892. return;
  52893. }
  52894. ambientLight = document.createElement('a-entity');
  52895. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  52896. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  52897. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  52898. sceneEl.appendChild(ambientLight);
  52899. directionalLight = document.createElement('a-entity');
  52900. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  52901. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  52902. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  52903. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  52904. sceneEl.appendChild(directionalLight);
  52905. this.defaultLights = true;
  52906. }
  52907. });
  52908. },{"../constants/":94,"../core/system":113,"../utils/bind":167}],164:[function(_dereq_,module,exports){
  52909. var registerSystem = _dereq_('../core/system').registerSystem;
  52910. var THREE = _dereq_('../lib/three');
  52911. var utils = _dereq_('../utils/');
  52912. var isHLS = _dereq_('../utils/material').isHLS;
  52913. var bind = utils.bind;
  52914. var debug = utils.debug;
  52915. var error = debug('components:texture:error');
  52916. var TextureLoader = new THREE.TextureLoader();
  52917. var warn = debug('components:texture:warn');
  52918. TextureLoader.setCrossOrigin('anonymous');
  52919. /**
  52920. * System for material component.
  52921. * Handle material registration, updates (for fog), and texture caching.
  52922. *
  52923. * @member {object} materials - Registered materials.
  52924. * @member {object} textureCounts - Number of times each texture is used. Tracked
  52925. * separately from textureCache, because the cache (1) is populated in
  52926. * multiple places, and (2) may be cleared at any time.
  52927. * @member {object} textureCache - Texture cache for:
  52928. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  52929. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  52930. */
  52931. module.exports.System = registerSystem('material', {
  52932. init: function () {
  52933. this.materials = {};
  52934. this.textureCounts = {};
  52935. this.textureCache = {};
  52936. this.sceneEl.addEventListener(
  52937. 'materialtextureloaded',
  52938. bind(this.onMaterialTextureLoaded, this)
  52939. );
  52940. },
  52941. clearTextureCache: function () {
  52942. this.textureCache = {};
  52943. },
  52944. /**
  52945. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  52946. *
  52947. * @param {string, or element} src - Texture URL or element.
  52948. * @param {string} data - Relevant texture data used for caching.
  52949. * @param {function} cb - Callback to pass texture to.
  52950. */
  52951. loadTexture: function (src, data, cb) {
  52952. var self = this;
  52953. // Canvas.
  52954. if (src.tagName === 'CANVAS') {
  52955. this.loadCanvas(src, data, cb);
  52956. return;
  52957. }
  52958. // Video element.
  52959. if (src.tagName === 'VIDEO') {
  52960. if (!src.src && !src.srcObject && !src.childElementCount) {
  52961. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  52962. }
  52963. this.loadVideo(src, data, cb);
  52964. return;
  52965. }
  52966. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  52967. function loadImageCb (src) { self.loadImage(src, data, cb); }
  52968. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  52969. },
  52970. /**
  52971. * High-level function for loading image textures (THREE.Texture).
  52972. *
  52973. * @param {Element|string} src - Texture source.
  52974. * @param {object} data - Texture data.
  52975. * @param {function} cb - Callback to pass texture to.
  52976. */
  52977. loadImage: function (src, data, handleImageTextureLoaded) {
  52978. var hash = this.hash(data);
  52979. var textureCache = this.textureCache;
  52980. // Texture already being loaded or already loaded. Wait on promise.
  52981. if (textureCache[hash]) {
  52982. textureCache[hash].then(handleImageTextureLoaded);
  52983. return;
  52984. }
  52985. // Texture not yet being loaded. Start loading it.
  52986. textureCache[hash] = loadImageTexture(src, data);
  52987. textureCache[hash].then(handleImageTextureLoaded);
  52988. },
  52989. /**
  52990. * High-level function for loading canvas textures (THREE.Texture).
  52991. *
  52992. * @param {Element|string} src - Texture source.
  52993. * @param {object} data - Texture data.
  52994. * @param {function} cb - Callback to pass texture to.
  52995. */
  52996. loadCanvas: function (src, data, cb) {
  52997. // Hack readyState and HAVE_CURRENT_DATA on canvas to work with THREE.VideoTexture
  52998. src.readyState = 2;
  52999. src.HAVE_CURRENT_DATA = 2;
  53000. this.loadVideo(src, data, cb);
  53001. },
  53002. /**
  53003. * Load video texture (THREE.VideoTexture).
  53004. * Which is just an image texture that RAFs + needsUpdate.
  53005. * Note that creating a video texture is synchronous unlike loading an image texture.
  53006. * Made asynchronous to be consistent with image textures.
  53007. *
  53008. * @param {Element|string} src - Texture source.
  53009. * @param {object} data - Texture data.
  53010. * @param {function} cb - Callback to pass texture to.
  53011. */
  53012. loadVideo: function (src, data, cb) {
  53013. var hash;
  53014. var texture;
  53015. var textureCache = this.textureCache;
  53016. var videoEl;
  53017. var videoTextureResult;
  53018. function handleVideoTextureLoaded (result) {
  53019. result.texture.needsUpdate = true;
  53020. cb(result.texture, result.videoEl);
  53021. }
  53022. // Video element provided.
  53023. if (typeof src !== 'string') {
  53024. // Check cache before creating texture.
  53025. videoEl = src;
  53026. hash = this.hashVideo(data, videoEl);
  53027. if (textureCache[hash]) {
  53028. textureCache[hash].then(handleVideoTextureLoaded);
  53029. return;
  53030. }
  53031. // If not in cache, fix up the attributes then start to create the texture.
  53032. fixVideoAttributes(videoEl);
  53033. }
  53034. // Only URL provided. Use video element to create texture.
  53035. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  53036. // Generated video element already cached. Use that.
  53037. hash = this.hashVideo(data, videoEl);
  53038. if (textureCache[hash]) {
  53039. textureCache[hash].then(handleVideoTextureLoaded);
  53040. return;
  53041. }
  53042. // Create new video texture.
  53043. texture = new THREE.VideoTexture(videoEl);
  53044. texture.minFilter = THREE.LinearFilter;
  53045. setTextureProperties(texture, data);
  53046. // If iOS and video is HLS, do some hacks.
  53047. if (this.sceneEl.isIOS &&
  53048. isHLS(videoEl.src || videoEl.getAttribute('src'),
  53049. videoEl.type || videoEl.getAttribute('type'))) {
  53050. // Actually BGRA. Tell shader to correct later.
  53051. texture.format = THREE.RGBAFormat;
  53052. texture.needsCorrectionBGRA = true;
  53053. // Apparently needed for HLS. Tell shader to correct later.
  53054. texture.flipY = false;
  53055. texture.needsCorrectionFlipY = true;
  53056. }
  53057. // Cache as promise to be consistent with image texture caching.
  53058. videoTextureResult = {texture: texture, videoEl: videoEl};
  53059. textureCache[hash] = Promise.resolve(videoTextureResult);
  53060. handleVideoTextureLoaded(videoTextureResult);
  53061. },
  53062. /**
  53063. * Create a hash of the material properties for texture cache key.
  53064. */
  53065. hash: function (data) {
  53066. if (data.src.tagName) {
  53067. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  53068. data = utils.extendDeep({}, data);
  53069. data.src = data.src.src;
  53070. }
  53071. return JSON.stringify(data);
  53072. },
  53073. hashVideo: function (data, videoEl) {
  53074. return calculateVideoCacheHash(data, videoEl);
  53075. },
  53076. /**
  53077. * Keep track of material in case an update trigger is needed (e.g., fog).
  53078. *
  53079. * @param {object} material
  53080. */
  53081. registerMaterial: function (material) {
  53082. this.materials[material.uuid] = material;
  53083. },
  53084. /**
  53085. * Stop tracking material, and dispose of any textures not being used by
  53086. * another material component.
  53087. *
  53088. * @param {object} material
  53089. */
  53090. unregisterMaterial: function (material) {
  53091. delete this.materials[material.uuid];
  53092. // If any textures on this material are no longer in use, dispose of them.
  53093. var textureCounts = this.textureCounts;
  53094. Object.keys(material)
  53095. .filter(function (propName) {
  53096. return material[propName] && material[propName].isTexture;
  53097. })
  53098. .forEach(function (mapName) {
  53099. textureCounts[material[mapName].uuid]--;
  53100. if (textureCounts[material[mapName].uuid] <= 0) {
  53101. material[mapName].dispose();
  53102. }
  53103. });
  53104. },
  53105. /**
  53106. * Trigger update to all registered materials.
  53107. */
  53108. updateMaterials: function (material) {
  53109. var materials = this.materials;
  53110. Object.keys(materials).forEach(function (uuid) {
  53111. materials[uuid].needsUpdate = true;
  53112. });
  53113. },
  53114. /**
  53115. * Track textures used by material components, so that they can be safely
  53116. * disposed when no longer in use. Textures must be registered here, and not
  53117. * through registerMaterial(), because textures may not be attached at the
  53118. * time the material is registered.
  53119. *
  53120. * @param {Event} e
  53121. */
  53122. onMaterialTextureLoaded: function (e) {
  53123. if (!this.textureCounts[e.detail.texture.uuid]) {
  53124. this.textureCounts[e.detail.texture.uuid] = 0;
  53125. }
  53126. this.textureCounts[e.detail.texture.uuid]++;
  53127. }
  53128. });
  53129. /**
  53130. * Calculates consistent hash from a video element using its attributes.
  53131. * If the video element has an ID, use that.
  53132. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  53133. *
  53134. * @param data {object} - Texture data such as repeat.
  53135. * @param videoEl {Element} - Video element.
  53136. * @returns {string}
  53137. */
  53138. function calculateVideoCacheHash (data, videoEl) {
  53139. var i;
  53140. var id = videoEl.getAttribute('id');
  53141. var hash;
  53142. var videoAttributes;
  53143. if (id) { return id; }
  53144. // Calculate hash using sorted video attributes.
  53145. hash = '';
  53146. videoAttributes = data || {};
  53147. for (i = 0; i < videoEl.attributes.length; i++) {
  53148. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  53149. }
  53150. Object.keys(videoAttributes).sort().forEach(function (name) {
  53151. hash += name + ':' + videoAttributes[name] + ';';
  53152. });
  53153. return hash;
  53154. }
  53155. /**
  53156. * Load image texture.
  53157. *
  53158. * @private
  53159. * @param {string|object} src - An <img> element or url to an image file.
  53160. * @param {object} data - Data to set texture properties like `repeat`.
  53161. * @returns {Promise} Resolves once texture is loaded.
  53162. */
  53163. function loadImageTexture (src, data) {
  53164. return new Promise(doLoadImageTexture);
  53165. function doLoadImageTexture (resolve, reject) {
  53166. var isEl = typeof src !== 'string';
  53167. function resolveTexture (texture) {
  53168. setTextureProperties(texture, data);
  53169. texture.needsUpdate = true;
  53170. resolve(texture);
  53171. }
  53172. // Create texture from an element.
  53173. if (isEl) {
  53174. resolveTexture(new THREE.Texture(src));
  53175. return;
  53176. }
  53177. // Request and load texture from src string. THREE will create underlying element.
  53178. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  53179. TextureLoader.load(
  53180. src,
  53181. resolveTexture,
  53182. function () { /* no-op */ },
  53183. function (xhr) {
  53184. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  53185. xhr.statusText);
  53186. }
  53187. );
  53188. }
  53189. }
  53190. /**
  53191. * Set texture properties such as repeat and offset.
  53192. *
  53193. * @param {object} data - With keys like `repeat`.
  53194. */
  53195. function setTextureProperties (texture, data) {
  53196. var offset = data.offset || {x: 0, y: 0};
  53197. var repeat = data.repeat || {x: 1, y: 1};
  53198. var npot = data.npot || false;
  53199. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  53200. // and filters must not use mipmaps (i.e. Nearest or Linear).
  53201. if (npot) {
  53202. texture.wrapS = THREE.ClampToEdgeWrapping;
  53203. texture.wrapT = THREE.ClampToEdgeWrapping;
  53204. texture.magFilter = THREE.LinearFilter;
  53205. texture.minFilter = THREE.LinearFilter;
  53206. }
  53207. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  53208. if (repeat.x !== 1 || repeat.y !== 1) {
  53209. texture.wrapS = THREE.RepeatWrapping;
  53210. texture.wrapT = THREE.RepeatWrapping;
  53211. texture.repeat.set(repeat.x, repeat.y);
  53212. }
  53213. // Don't bother setting offset if it is 0/0.
  53214. if (offset.x !== 0 || offset.y !== 0) {
  53215. texture.offset.set(offset.x, offset.y);
  53216. }
  53217. }
  53218. /**
  53219. * Create video element to be used as a texture.
  53220. *
  53221. * @param {string} src - Url to a video file.
  53222. * @param {number} width - Width of the video.
  53223. * @param {number} height - Height of the video.
  53224. * @returns {Element} Video element.
  53225. */
  53226. function createVideoEl (src, width, height) {
  53227. var videoEl = document.createElement('video');
  53228. videoEl.width = width;
  53229. videoEl.height = height;
  53230. // Support inline videos for iOS webviews.
  53231. videoEl.setAttribute('playsinline', '');
  53232. videoEl.setAttribute('webkit-playsinline', '');
  53233. videoEl.autoplay = true;
  53234. videoEl.loop = true;
  53235. videoEl.crossOrigin = 'anonymous';
  53236. videoEl.addEventListener('error', function () {
  53237. warn('`$s` is not a valid video', src);
  53238. }, true);
  53239. videoEl.src = src;
  53240. return videoEl;
  53241. }
  53242. /**
  53243. * Fixes a video element's attributes to prevent developers from accidentally passing the
  53244. * wrong attribute values to commonly misused video attributes.
  53245. *
  53246. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  53247. * as booleans. Existence of those attributes will mean truthy.
  53248. *
  53249. * For example, translates <video loop="false"> to <video>.
  53250. *
  53251. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  53252. * @param {Element} videoEl - Video element.
  53253. * @returns {Element} Video element with the correct properties updated.
  53254. */
  53255. function fixVideoAttributes (videoEl) {
  53256. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  53257. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  53258. if (videoEl.getAttribute('loop') === 'false') {
  53259. videoEl.removeAttribute('loop');
  53260. }
  53261. if (videoEl.getAttribute('preload') === 'false') {
  53262. videoEl.preload = 'none';
  53263. }
  53264. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  53265. // To support inline videos in iOS webviews.
  53266. videoEl.setAttribute('playsinline', '');
  53267. videoEl.setAttribute('webkit-playsinline', '');
  53268. return videoEl;
  53269. }
  53270. },{"../core/system":113,"../lib/three":151,"../utils/":173,"../utils/material":174}],165:[function(_dereq_,module,exports){
  53271. var registerSystem = _dereq_('../core/system').registerSystem;
  53272. var THREE = _dereq_('../lib/three');
  53273. var SHADOW_MAP_TYPE_MAP = {
  53274. basic: THREE.BasicShadowMap,
  53275. pcf: THREE.PCFShadowMap,
  53276. pcfsoft: THREE.PCFSoftShadowMap
  53277. };
  53278. /**
  53279. * Shadow system.
  53280. *
  53281. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  53282. * options on the WebGLRenderer for configuring shadow appearance.
  53283. */
  53284. module.exports.System = registerSystem('shadow', {
  53285. schema: {
  53286. autoUpdate: {default: true},
  53287. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  53288. },
  53289. init: function () {
  53290. var sceneEl = this.sceneEl;
  53291. var data = this.data;
  53292. this.shadowMapEnabled = false;
  53293. if (!sceneEl.renderer) { return; } // For tests.
  53294. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  53295. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  53296. this.setShadowMapEnabled(this.shadowMapEnabled);
  53297. },
  53298. /**
  53299. * Enables/disables the renderer shadow map.
  53300. * @param {boolean} enabled
  53301. */
  53302. setShadowMapEnabled: function (enabled) {
  53303. var renderer = this.sceneEl.renderer;
  53304. this.shadowMapEnabled = enabled;
  53305. if (renderer) {
  53306. renderer.shadowMap.enabled = enabled;
  53307. }
  53308. }
  53309. });
  53310. },{"../core/system":113,"../lib/three":151}],166:[function(_dereq_,module,exports){
  53311. var registerSystem = _dereq_('../core/system').registerSystem;
  53312. var utils = _dereq_('../utils');
  53313. /**
  53314. * Tracked controls system.
  53315. * Maintain list with available tracked controllers.
  53316. */
  53317. module.exports.System = registerSystem('tracked-controls', {
  53318. init: function () {
  53319. var self = this;
  53320. this.controllers = [];
  53321. this.updateControllerList(navigator.getGamepads && navigator.getGamepads());
  53322. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  53323. if (!navigator.getVRDisplays) { return; }
  53324. this.sceneEl.addEventListener('enter-vr', function () {
  53325. navigator.getVRDisplays().then(function (displays) {
  53326. if (displays.length) { self.vrDisplay = displays[0]; }
  53327. });
  53328. });
  53329. },
  53330. tick: function () {
  53331. var gamepads;
  53332. // Call getGamepads for Chrome.
  53333. gamepads = navigator.getGamepads && navigator.getGamepads();
  53334. this.throttledUpdateControllerList(gamepads);
  53335. },
  53336. /**
  53337. * Update controller list.
  53338. */
  53339. updateControllerList: function (gamepads) {
  53340. var controllers = this.controllers;
  53341. var gamepad;
  53342. var i;
  53343. var prevCount;
  53344. if (!gamepads) { return; }
  53345. prevCount = controllers.length;
  53346. controllers.length = 0;
  53347. for (i = 0; i < gamepads.length; ++i) {
  53348. gamepad = gamepads[i];
  53349. if (gamepad && gamepad.pose) {
  53350. controllers.push(gamepad);
  53351. }
  53352. }
  53353. if (controllers.length !== prevCount) {
  53354. this.el.emit('controllersupdated', undefined, false);
  53355. }
  53356. }
  53357. });
  53358. },{"../core/system":113,"../utils":173}],167:[function(_dereq_,module,exports){
  53359. /**
  53360. * Faster version of Function.prototype.bind
  53361. * @param {Function} fn - Function to wrap.
  53362. * @param {Object} ctx - What to bind as context.
  53363. * @param {...*} arguments - Arguments to pass through.
  53364. */
  53365. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  53366. return (function (prependedArgs) {
  53367. return function bound () {
  53368. // Concat the bound function arguments with those passed to original bind
  53369. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  53370. return fn.apply(ctx, args);
  53371. };
  53372. })(Array.prototype.slice.call(arguments, 2));
  53373. };
  53374. },{}],168:[function(_dereq_,module,exports){
  53375. /* global THREE */
  53376. var debug = _dereq_('./debug');
  53377. var extend = _dereq_('object-assign');
  53378. var warn = debug('utils:coordinates:warn');
  53379. // Coordinate string regex. Handles negative, positive, and decimals.
  53380. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  53381. module.exports.regex = regex;
  53382. /**
  53383. * Parses coordinates from an "x y z" string.
  53384. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  53385. *
  53386. * @param {string} val - An "x y z" string.
  53387. * @param {string} defaults - fallback value.
  53388. * @returns {object} An object with keys [x, y, z].
  53389. */
  53390. function parse (value, defaultVec) {
  53391. var coordinate;
  53392. var vec;
  53393. if (value && value instanceof Object) {
  53394. if (defaultVec) {
  53395. value.x = value.x === undefined ? defaultVec.x : value.x;
  53396. value.y = value.y === undefined ? defaultVec.y : value.y;
  53397. value.z = value.z === undefined ? defaultVec.z : value.z;
  53398. value.w = value.w === undefined ? defaultVec.w : value.w;
  53399. }
  53400. return vecParseFloat(value);
  53401. }
  53402. if (value === null || value === undefined) {
  53403. return typeof defaultVec === 'object' ? extend({}, defaultVec) : defaultVec;
  53404. }
  53405. coordinate = value.trim().replace(/\s+/g, ' ').split(' ');
  53406. vec = {};
  53407. vec.x = coordinate[0] || defaultVec && defaultVec.x;
  53408. vec.y = coordinate[1] || defaultVec && defaultVec.y;
  53409. vec.z = coordinate[2] || defaultVec && defaultVec.z;
  53410. vec.w = coordinate[3] || defaultVec && defaultVec.w;
  53411. return vecParseFloat(vec);
  53412. }
  53413. module.exports.parse = parse;
  53414. /**
  53415. * Stringify coordinates from an object with keys [x y z].
  53416. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  53417. *
  53418. * @param {object|string} data - An object with keys [x y z].
  53419. * @returns {string} An "x y z" string.
  53420. */
  53421. function stringify (data) {
  53422. if (typeof data !== 'object') { return data; }
  53423. return [data.x, data.y, data.z, data.w].join(' ').trim();
  53424. }
  53425. module.exports.stringify = stringify;
  53426. /**
  53427. * @returns {bool}
  53428. */
  53429. function isCoordinates (value) {
  53430. return regex.test(value);
  53431. }
  53432. module.exports.isCoordinates = isCoordinates;
  53433. module.exports.isCoordinate = function (value) {
  53434. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  53435. return isCoordinates(value);
  53436. };
  53437. function vecParseFloat (vec) {
  53438. var key;
  53439. for (key in vec) {
  53440. if (vec[key] === undefined) {
  53441. delete vec[key];
  53442. continue;
  53443. }
  53444. if (vec[key].constructor === String) {
  53445. vec[key] = parseFloat(vec[key], 10);
  53446. }
  53447. }
  53448. return vec;
  53449. }
  53450. /**
  53451. * Convert {x, y, z} object to three.js Vector3.
  53452. */
  53453. module.exports.toVector3 = function (vec3) {
  53454. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  53455. };
  53456. },{"./debug":169,"object-assign":25}],169:[function(_dereq_,module,exports){
  53457. (function (process){
  53458. var debugLib = _dereq_('debug');
  53459. var extend = _dereq_('object-assign');
  53460. var settings = {
  53461. colors: {
  53462. debug: 'gray',
  53463. error: 'red',
  53464. info: 'gray',
  53465. warn: 'orange'
  53466. }
  53467. };
  53468. /**
  53469. * Monkeypatches `debug` so we can colorize error/warning messages.
  53470. *
  53471. * (See issue: https://github.com/visionmedia/debug/issues/137)
  53472. */
  53473. var debug = function (namespace) {
  53474. var d = debugLib(namespace);
  53475. d.color = getDebugNamespaceColor(namespace);
  53476. return d;
  53477. };
  53478. extend(debug, debugLib);
  53479. /**
  53480. * Returns the type of the namespace (e.g., `error`, `warn`).
  53481. *
  53482. * @param {String} namespace
  53483. * The debug logger's namespace (e.g., `components:geometry:warn`).
  53484. * @returns {String} The type of the namespace (e.g., `warn`).
  53485. * @api private
  53486. */
  53487. function getDebugNamespaceType (namespace) {
  53488. var chunks = namespace.split(':');
  53489. return chunks[chunks.length - 1]; // Return the last one
  53490. }
  53491. /**
  53492. * Returns the color of the namespace (e.g., `orange`).
  53493. *
  53494. * @param {String} namespace
  53495. * The debug logger's namespace (e.g., `components:geometry:warn`).
  53496. * @returns {String} The color of the namespace (e.g., `orange`).
  53497. * @api private
  53498. */
  53499. function getDebugNamespaceColor (namespace) {
  53500. var type = getDebugNamespaceType(namespace);
  53501. var color = settings.colors && settings.colors[type];
  53502. return color || null;
  53503. }
  53504. /**
  53505. * Returns `localStorage` if possible.
  53506. *
  53507. * This is necessary because Safari throws when a user disables
  53508. * cookies or `localStorage` and you attempt to access it.
  53509. *
  53510. * @returns {localStorage}
  53511. * @api private
  53512. */
  53513. function storage () {
  53514. try {
  53515. return window.localStorage;
  53516. } catch (e) {
  53517. }
  53518. }
  53519. /**
  53520. * To enable console logging, type this in the Console of your Dev Tools:
  53521. *
  53522. * localStorage.logs = 1
  53523. *
  53524. * To disable console logging:
  53525. *
  53526. * localStorage.logs = 0
  53527. *
  53528. */
  53529. var ls = storage();
  53530. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  53531. debug.enable('*');
  53532. } else {
  53533. debug.enable('*:error,*:info,*:warn');
  53534. }
  53535. if (process.browser) { window.logs = debug; }
  53536. module.exports = debug;
  53537. }).call(this,_dereq_('_process'))
  53538. },{"_process":32,"debug":8,"object-assign":25}],170:[function(_dereq_,module,exports){
  53539. (function (process){
  53540. var vrDisplay;
  53541. var polyfilledVRDisplay;
  53542. var POLYFILL_VRDISPLAY_ID = 'Cardboard VRDisplay';
  53543. if (navigator.getVRDisplays) {
  53544. navigator.getVRDisplays().then(function (displays) {
  53545. vrDisplay = displays.length && displays[0];
  53546. polyfilledVRDisplay = vrDisplay.displayName === POLYFILL_VRDISPLAY_ID;
  53547. });
  53548. }
  53549. function getVRDisplay () { return vrDisplay; }
  53550. module.exports.getVRDisplay = getVRDisplay;
  53551. /**
  53552. * Determine if a headset is connected by checking if a vrDisplay is available.
  53553. */
  53554. function checkHeadsetConnected () { return !!getVRDisplay(); }
  53555. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  53556. /**
  53557. * Check for positional tracking.
  53558. */
  53559. function checkHasPositionalTracking () {
  53560. var vrDisplay = getVRDisplay();
  53561. if (isMobile() || isGearVR()) { return false; }
  53562. return vrDisplay && vrDisplay.capabilities.hasPosition;
  53563. }
  53564. module.exports.checkHasPositionalTracking = checkHasPositionalTracking;
  53565. /**
  53566. * Checks if browser is mobile.
  53567. * @return {Boolean} True if mobile browser detected.
  53568. */
  53569. var isMobile = (function () {
  53570. var _isMobile = false;
  53571. (function (a) {
  53572. // eslint-disable-next-line no-useless-escape
  53573. 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))) {
  53574. _isMobile = true;
  53575. }
  53576. if (isIOS() || isTablet() || isR7()) {
  53577. _isMobile = true;
  53578. }
  53579. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  53580. return function () { return _isMobile; };
  53581. })();
  53582. module.exports.isMobile = isMobile;
  53583. /**
  53584. * Detect tablet devices.
  53585. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  53586. */
  53587. function isTablet (mockUserAgent) {
  53588. var userAgent = mockUserAgent || window.navigator.userAgent;
  53589. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  53590. }
  53591. module.exports.isTablet = isTablet;
  53592. function isIOS () {
  53593. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  53594. }
  53595. module.exports.isIOS = isIOS;
  53596. function isGearVR () {
  53597. return /SamsungBrowser.+Mobile VR/i.test(window.navigator.userAgent);
  53598. }
  53599. module.exports.isGearVR = isGearVR;
  53600. function isR7 () {
  53601. return /R7 Build/.test(window.navigator.userAgent);
  53602. }
  53603. module.exports.isR7 = isR7;
  53604. /**
  53605. * Checks mobile device orientation.
  53606. * @return {Boolean} True if landscape orientation.
  53607. */
  53608. module.exports.isLandscape = function () {
  53609. var orientation = window.orientation;
  53610. if (isR7()) { orientation += 90; }
  53611. return orientation === 90 || orientation === -90;
  53612. };
  53613. /**
  53614. * Check if device is iOS and older than version 10.
  53615. */
  53616. module.exports.isIOSOlderThan10 = function (userAgent) {
  53617. return /(iphone|ipod|ipad).*os.(7|8|9)/i.test(userAgent);
  53618. };
  53619. /**
  53620. * Check if running in a browser or spoofed browser (bundler).
  53621. * We need to check a node api that isn't mocked on either side.
  53622. * `require` and `module.exports` are mocked in browser by bundlers.
  53623. * `window` is mocked in node.
  53624. * `process` is also mocked by browserify, but has custom properties.
  53625. */
  53626. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  53627. /**
  53628. * Check if running in node on the server.
  53629. */
  53630. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  53631. /**
  53632. * Update an Object3D pose if a polyfilled vrDisplay is present.
  53633. */
  53634. module.exports.PolyfillControls = function PolyfillControls (object) {
  53635. var frameData;
  53636. if (window.VRFrameData) { frameData = new window.VRFrameData(); }
  53637. this.update = function () {
  53638. var pose;
  53639. if (!vrDisplay || !polyfilledVRDisplay) { return; }
  53640. vrDisplay.getFrameData(frameData);
  53641. pose = frameData.pose;
  53642. if (pose.orientation !== null) {
  53643. object.quaternion.fromArray(pose.orientation);
  53644. }
  53645. if (pose.position !== null) {
  53646. object.position.fromArray(pose.position);
  53647. } else {
  53648. object.position.set(0, 0, 0);
  53649. }
  53650. };
  53651. };
  53652. }).call(this,_dereq_('_process'))
  53653. },{"_process":32}],171:[function(_dereq_,module,exports){
  53654. /**
  53655. * Split a delimited component property string (e.g., `material.color`) to an object
  53656. * containing `component` name and `property` name. If there is no delimiter, just return the
  53657. * string back.
  53658. *
  53659. * Cache arrays from splitting strings via delimiter to save on memory.
  53660. *
  53661. * @param {string} str - e.g., `material.opacity`.
  53662. * @param {string} delimiter - e.g., `.`.
  53663. * @returns {array} e.g., `['material', 'opacity']`.
  53664. */
  53665. var propertyPathCache = {};
  53666. function getComponentPropertyPath (str, delimiter) {
  53667. delimiter = delimiter || '.';
  53668. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  53669. if (str.indexOf(delimiter) !== -1) {
  53670. propertyPathCache[delimiter][str] = str.split(delimiter);
  53671. } else {
  53672. propertyPathCache[delimiter][str] = str;
  53673. }
  53674. return propertyPathCache[delimiter][str];
  53675. }
  53676. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  53677. module.exports.propertyPathCache = propertyPathCache;
  53678. /**
  53679. * Get component property using encoded component name + component property name with a
  53680. * delimiter.
  53681. */
  53682. module.exports.getComponentProperty = function (el, name, delimiter) {
  53683. var splitName;
  53684. delimiter = delimiter || '.';
  53685. if (name.indexOf(delimiter) !== -1) {
  53686. splitName = getComponentPropertyPath(name, delimiter);
  53687. if (splitName.constructor === String) {
  53688. return el.getAttribute(splitName);
  53689. }
  53690. return el.getAttribute(splitName[0])[splitName[1]];
  53691. }
  53692. return el.getAttribute(name);
  53693. };
  53694. /**
  53695. * Set component property using encoded component name + component property name with a
  53696. * delimiter.
  53697. */
  53698. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  53699. var splitName;
  53700. delimiter = delimiter || '.';
  53701. if (name.indexOf(delimiter) !== -1) {
  53702. splitName = getComponentPropertyPath(name, delimiter);
  53703. if (splitName.constructor === String) {
  53704. el.setAttribute(splitName, value);
  53705. } else {
  53706. el.setAttribute(splitName[0], splitName[1], value);
  53707. }
  53708. return;
  53709. }
  53710. el.setAttribute(name, value);
  53711. };
  53712. },{}],172:[function(_dereq_,module,exports){
  53713. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  53714. var width = canvasEl.style.width;
  53715. var height = canvasEl.style.height;
  53716. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  53717. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  53718. // By changing the size 1 pixel and restoring the previous value
  53719. // we trigger a size recalculation cycle.
  53720. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  53721. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  53722. setTimeout(function () {
  53723. canvasEl.style.width = width;
  53724. canvasEl.style.height = height;
  53725. }, 200);
  53726. };
  53727. },{}],173:[function(_dereq_,module,exports){
  53728. /* global location */
  53729. /* Centralized place to reference utilities since utils is exposed to the user. */
  53730. var debug = _dereq_('./debug');
  53731. var deepAssign = _dereq_('deep-assign');
  53732. var device = _dereq_('./device');
  53733. var objectAssign = _dereq_('object-assign');
  53734. var objectPool = _dereq_('./object-pool');
  53735. var warn = debug('utils:warn');
  53736. module.exports.bind = _dereq_('./bind');
  53737. module.exports.coordinates = _dereq_('./coordinates');
  53738. module.exports.debug = debug;
  53739. module.exports.device = device;
  53740. module.exports.entity = _dereq_('./entity');
  53741. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  53742. module.exports.material = _dereq_('./material');
  53743. module.exports.objectPool = objectPool;
  53744. module.exports.split = _dereq_('./split').split;
  53745. module.exports.styleParser = _dereq_('./styleParser');
  53746. module.exports.trackedControls = _dereq_('./tracked-controls');
  53747. module.exports.checkHeadsetConnected = function () {
  53748. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  53749. return device.checkHeadsetConnected(arguments);
  53750. };
  53751. module.exports.isGearVR = function () {
  53752. warn('`utils.isGearVR` has moved to `utils.device.isGearVR`');
  53753. return device.isGearVR(arguments);
  53754. };
  53755. module.exports.isIOS = function () {
  53756. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  53757. return device.isIOS(arguments);
  53758. };
  53759. module.exports.isMobile = function () {
  53760. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  53761. return device.isMobile(arguments);
  53762. };
  53763. /**
  53764. * Returns throttle function that gets called at most once every interval.
  53765. *
  53766. * @param {function} functionToThrottle
  53767. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  53768. * @param {object} optionalContext - If given, bind function to throttle to this context.
  53769. * @returns {function} Throttled function.
  53770. */
  53771. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  53772. var lastTime;
  53773. if (optionalContext) {
  53774. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  53775. }
  53776. return function () {
  53777. var time = Date.now();
  53778. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  53779. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  53780. lastTime = time;
  53781. functionToThrottle.apply(null, arguments);
  53782. }
  53783. };
  53784. };
  53785. /**
  53786. * Returns throttle function that gets called at most once every interval.
  53787. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  53788. *
  53789. * @param {function} functionToThrottle
  53790. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  53791. * @param {object} optionalContext - If given, bind function to throttle to this context.
  53792. * @returns {function} Throttled function.
  53793. */
  53794. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  53795. var lastTime;
  53796. if (optionalContext) {
  53797. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  53798. }
  53799. return function (time, delta) {
  53800. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  53801. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  53802. lastTime = time;
  53803. functionToThrottle(time, sinceLastTime);
  53804. }
  53805. };
  53806. };
  53807. /**
  53808. * Returns debounce function that gets called only once after a set of repeated calls.
  53809. *
  53810. * @param {function} functionToDebounce
  53811. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  53812. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  53813. * @returns {function} Debounced function.
  53814. */
  53815. module.exports.debounce = function (func, wait, immediate) {
  53816. var timeout;
  53817. return function () {
  53818. var context = this;
  53819. var args = arguments;
  53820. var later = function () {
  53821. timeout = null;
  53822. if (!immediate) func.apply(context, args);
  53823. };
  53824. var callNow = immediate && !timeout;
  53825. clearTimeout(timeout);
  53826. timeout = setTimeout(later, wait);
  53827. if (callNow) func.apply(context, args);
  53828. };
  53829. };
  53830. /**
  53831. * Mix the properties of source object(s) into a destination object.
  53832. *
  53833. * @param {object} dest - The object to which properties will be copied.
  53834. * @param {...object} source - The object(s) from which properties will be copied.
  53835. */
  53836. module.exports.extend = objectAssign;
  53837. module.exports.extendDeep = deepAssign;
  53838. module.exports.clone = function (obj) {
  53839. return JSON.parse(JSON.stringify(obj));
  53840. };
  53841. /**
  53842. * Checks if two values are equal.
  53843. * Includes objects and arrays and nested objects and arrays.
  53844. * Try to keep this function performant as it will be called often to see if a component
  53845. * should be updated.
  53846. *
  53847. * @param {object} a - First object.
  53848. * @param {object} b - Second object.
  53849. * @returns {boolean} Whether two objects are deeply equal.
  53850. */
  53851. var deepEqual = (function () {
  53852. var arrayPool = objectPool.createPool(function () { return []; });
  53853. return function (a, b) {
  53854. var key;
  53855. var keysA;
  53856. var keysB;
  53857. var i;
  53858. var valA;
  53859. var valB;
  53860. // If not objects or arrays, compare as values.
  53861. if (a === undefined || b === undefined || a === null || b === null ||
  53862. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  53863. (a.constructor === Array && b.constructor === Array))) {
  53864. return a === b;
  53865. }
  53866. // Different number of keys, not equal.
  53867. keysA = arrayPool.use();
  53868. keysB = arrayPool.use();
  53869. keysA.length = 0;
  53870. keysB.length = 0;
  53871. for (key in a) { keysA.push(key); }
  53872. for (key in b) { keysB.push(key); }
  53873. if (keysA.length !== keysB.length) {
  53874. arrayPool.recycle(keysA);
  53875. arrayPool.recycle(keysB);
  53876. return false;
  53877. }
  53878. // Return `false` at the first sign of inequality.
  53879. for (i = 0; i < keysA.length; ++i) {
  53880. valA = a[keysA[i]];
  53881. valB = b[keysA[i]];
  53882. // Check nested array and object.
  53883. if ((typeof valA === 'object' || typeof valB === 'object') ||
  53884. (Array.isArray(valA) && Array.isArray(valB))) {
  53885. if (valA === valB) { continue; }
  53886. if (!deepEqual(valA, valB)) {
  53887. arrayPool.recycle(keysA);
  53888. arrayPool.recycle(keysB);
  53889. return false;
  53890. }
  53891. } else if (valA !== valB) {
  53892. arrayPool.recycle(keysA);
  53893. arrayPool.recycle(keysB);
  53894. return false;
  53895. }
  53896. }
  53897. arrayPool.recycle(keysA);
  53898. arrayPool.recycle(keysB);
  53899. return true;
  53900. };
  53901. })();
  53902. module.exports.deepEqual = deepEqual;
  53903. /**
  53904. * Computes the difference between two objects.
  53905. *
  53906. * @param {object} a - First object to compare (e.g., oldData).
  53907. * @param {object} b - Second object to compare (e.g., newData).
  53908. * @returns {object}
  53909. * Difference object where set of keys note which values were not equal, and values are
  53910. * `b`'s values.
  53911. */
  53912. module.exports.diff = (function () {
  53913. var keys = [];
  53914. return function (a, b, targetObject) {
  53915. var aVal;
  53916. var bVal;
  53917. var bKey;
  53918. var diff;
  53919. var key;
  53920. var i;
  53921. var isComparingObjects;
  53922. diff = targetObject || {};
  53923. // Collect A keys.
  53924. keys.length = 0;
  53925. for (key in a) { keys.push(key); }
  53926. if (!b) { return diff; }
  53927. // Collect B keys.
  53928. for (bKey in b) {
  53929. if (keys.indexOf(bKey) === -1) {
  53930. keys.push(bKey);
  53931. }
  53932. }
  53933. for (i = 0; i < keys.length; i++) {
  53934. key = keys[i];
  53935. aVal = a[key];
  53936. bVal = b[key];
  53937. isComparingObjects = aVal && bVal &&
  53938. aVal.constructor === Object && bVal.constructor === Object;
  53939. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  53940. (!isComparingObjects && aVal !== bVal)) {
  53941. diff[key] = bVal;
  53942. }
  53943. }
  53944. return diff;
  53945. };
  53946. })();
  53947. /**
  53948. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  53949. * @param {Event} event Event object.
  53950. * @returns {Boolean} Whether the key event should be captured.
  53951. */
  53952. module.exports.shouldCaptureKeyEvent = function (event) {
  53953. if (event.metaKey) { return false; }
  53954. return document.activeElement === document.body;
  53955. };
  53956. /**
  53957. * Splits a string into an array based on a delimiter.
  53958. *
  53959. * @param {string=} [str=''] Source string
  53960. * @param {string=} [delimiter=' '] Delimiter to use
  53961. * @returns {array} Array of delimited strings
  53962. */
  53963. module.exports.splitString = function (str, delimiter) {
  53964. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  53965. // First collapse the whitespace (or whatever the delimiter is).
  53966. var regex = new RegExp(delimiter, 'g');
  53967. str = (str || '').replace(regex, delimiter);
  53968. // Then split.
  53969. return str.split(delimiter);
  53970. };
  53971. /**
  53972. * Extracts data from the element given an object that contains expected keys.
  53973. *
  53974. * @param {Element} Source element.
  53975. * @param {Object} [defaults={}] Object of default key-value pairs.
  53976. * @returns {Object}
  53977. */
  53978. module.exports.getElData = function (el, defaults) {
  53979. defaults = defaults || {};
  53980. var data = {};
  53981. Object.keys(defaults).forEach(copyAttribute);
  53982. function copyAttribute (key) {
  53983. if (el.hasAttribute(key)) {
  53984. data[key] = el.getAttribute(key);
  53985. }
  53986. }
  53987. return data;
  53988. };
  53989. /**
  53990. * Retrieves querystring value.
  53991. * @param {String} name Name of querystring key.
  53992. * @return {String} Value
  53993. */
  53994. module.exports.getUrlParameter = function (name) {
  53995. // eslint-disable-next-line no-useless-escape
  53996. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  53997. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  53998. var results = regex.exec(location.search);
  53999. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  54000. };
  54001. /**
  54002. * Detects whether context is within iframe.
  54003. */
  54004. module.exports.isIframed = function () {
  54005. return window.top !== window.self;
  54006. };
  54007. /**
  54008. * Finds all elements under the element that have the isScene
  54009. * property set to true
  54010. */
  54011. module.exports.findAllScenes = function (el) {
  54012. var matchingElements = [];
  54013. var allElements = el.getElementsByTagName('*');
  54014. for (var i = 0, n = allElements.length; i < n; i++) {
  54015. if (allElements[i].isScene) {
  54016. // Element exists with isScene set.
  54017. matchingElements.push(allElements[i]);
  54018. }
  54019. }
  54020. return matchingElements;
  54021. };
  54022. // Must be at bottom to avoid circular dependency.
  54023. module.exports.srcLoader = _dereq_('./src-loader');
  54024. },{"./bind":167,"./coordinates":168,"./debug":169,"./device":170,"./entity":171,"./forceCanvasResizeSafariMobile":172,"./material":174,"./object-pool":175,"./split":176,"./src-loader":177,"./styleParser":178,"./tracked-controls":179,"deep-assign":10,"object-assign":25}],174:[function(_dereq_,module,exports){
  54025. var THREE = _dereq_('../lib/three');
  54026. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  54027. /**
  54028. * Update `material` texture property (usually but not always `map`)
  54029. * from `data` property (usually but not always `src`)
  54030. *
  54031. * @param {object} shader - A-Frame shader instance.
  54032. * @param {object} data
  54033. */
  54034. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  54035. var el = shader.el;
  54036. var material = shader.material;
  54037. var src = data[dataName];
  54038. // Because a single material / shader may have multiple textures,
  54039. // we need to remember the source value for this data property
  54040. // to avoid redundant operations which can be expensive otherwise
  54041. // (e.g. video texture loads).
  54042. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  54043. if (!src) {
  54044. // Forget the prior material src.
  54045. delete shader.materialSrcs[materialName];
  54046. // Remove the texture.
  54047. setMap(null);
  54048. return;
  54049. }
  54050. // Don't process if material src hasn't changed.
  54051. if (src === shader.materialSrcs[materialName]) { return; }
  54052. // Remember the new src for this texture (there may be multiple).
  54053. shader.materialSrcs[materialName] = src;
  54054. // If the new material src is already a texture, just use it.
  54055. if (src instanceof THREE.Texture) { setMap(src); } else {
  54056. // Load texture for the new material src.
  54057. // (And check if we should still use it once available in callback.)
  54058. el.sceneEl.systems.material.loadTexture(src,
  54059. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  54060. checkSetMap);
  54061. }
  54062. function checkSetMap (texture) {
  54063. // If the source has been changed, don't use loaded texture.
  54064. if (shader.materialSrcs[materialName] !== src) { return; }
  54065. setMap(texture);
  54066. }
  54067. function setMap (texture) {
  54068. material[materialName] = texture;
  54069. material.needsUpdate = true;
  54070. handleTextureEvents(el, texture);
  54071. }
  54072. };
  54073. /**
  54074. * Update `material.map` given `data.src`. For standard and flat shaders.
  54075. *
  54076. * @param {object} shader - A-Frame shader instance.
  54077. * @param {object} data
  54078. */
  54079. module.exports.updateMap = function (shader, data) {
  54080. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  54081. };
  54082. /**
  54083. * Updates the material's maps which give the illusion of extra geometry.
  54084. *
  54085. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  54086. * @param {object} shader - A-Frame shader instance
  54087. * @param {object} data
  54088. */
  54089. module.exports.updateDistortionMap = function (longType, shader, data) {
  54090. var shortType = longType;
  54091. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  54092. var el = shader.el;
  54093. var material = shader.material;
  54094. var src = data[longType + 'Map'];
  54095. var info = {};
  54096. info.src = src;
  54097. // Pass through the repeat and offset to be handled by the material loader.
  54098. info.offset = data[longType + 'TextureOffset'];
  54099. info.repeat = data[longType + 'TextureRepeat'];
  54100. info.wrap = data[longType + 'TextureWrap'];
  54101. if (src) {
  54102. if (src === shader[longType + 'TextureSrc']) { return; }
  54103. // Texture added or changed.
  54104. shader[longType + 'TextureSrc'] = src;
  54105. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  54106. return;
  54107. }
  54108. // Texture removed.
  54109. if (!material.map) { return; }
  54110. setMap(null);
  54111. function setMap (texture) {
  54112. material[shortType + 'Map'] = texture;
  54113. material.needsUpdate = true;
  54114. handleTextureEvents(el, texture);
  54115. }
  54116. };
  54117. /**
  54118. * Emit event on entities on texture-related events.
  54119. *
  54120. * @param {Element} el - Entity.
  54121. * @param {object} texture - three.js Texture.
  54122. */
  54123. function handleTextureEvents (el, texture) {
  54124. if (!texture) { return; }
  54125. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  54126. // Video events.
  54127. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  54128. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  54129. // Check to see if we need to use iOS 10 HLS shader.
  54130. // Only override the shader if it is stock shader that we know doesn't correct.
  54131. if (!el.components || !el.components.material) { return; }
  54132. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  54133. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  54134. el.setAttribute('material', 'shader', 'ios10hls');
  54135. }
  54136. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  54137. });
  54138. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  54139. // Works for non-looping videos only.
  54140. el.emit('materialvideoended', {src: texture.image, texture: texture});
  54141. });
  54142. }
  54143. module.exports.handleTextureEvents = handleTextureEvents;
  54144. /**
  54145. * Given video element src and type, guess whether stream is HLS.
  54146. *
  54147. * @param {string} src - src from video element (generally URL to content).
  54148. * @param {string} type - type from video element (generally MIME type if present).
  54149. */
  54150. module.exports.isHLS = function (src, type) {
  54151. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  54152. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  54153. return false;
  54154. };
  54155. },{"../lib/three":151}],175:[function(_dereq_,module,exports){
  54156. /*
  54157. Adapted deePool by Kyle Simpson.
  54158. MIT License: http://getify.mit-license.org
  54159. */
  54160. var EMPTY_SLOT = Object.freeze(Object.create(null));
  54161. // Default object factory.
  54162. function defaultObjectFactory () { return {}; }
  54163. /**
  54164. * Create a new pool.
  54165. */
  54166. module.exports.createPool = function createPool (objectFactory) {
  54167. var objPool = [];
  54168. var nextFreeSlot = null; // Pool location to look for a free object to use.
  54169. objectFactory = objectFactory || defaultObjectFactory;
  54170. function use () {
  54171. var objToUse;
  54172. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  54173. grow(objPool.length || 5);
  54174. }
  54175. objToUse = objPool[nextFreeSlot];
  54176. objPool[nextFreeSlot++] = EMPTY_SLOT;
  54177. clearObject(objToUse);
  54178. return objToUse;
  54179. }
  54180. function recycle (obj) {
  54181. if (!(obj instanceof Object)) { return; }
  54182. if (nextFreeSlot === null || nextFreeSlot === -1) {
  54183. objPool[objPool.length] = obj;
  54184. return;
  54185. }
  54186. objPool[--nextFreeSlot] = obj;
  54187. }
  54188. function grow (count) {
  54189. var currentLength;
  54190. var i;
  54191. count = count === undefined ? objPool.length : count;
  54192. if (count > 0 && nextFreeSlot == null) {
  54193. nextFreeSlot = 0;
  54194. }
  54195. if (count > 0) {
  54196. currentLength = objPool.length;
  54197. objPool.length += Number(count);
  54198. for (i = currentLength; i < objPool.length; i++) {
  54199. // Add new obj to pool.
  54200. objPool[i] = objectFactory();
  54201. }
  54202. }
  54203. return objPool.length;
  54204. }
  54205. function size () {
  54206. return objPool.length;
  54207. }
  54208. return {
  54209. grow: grow,
  54210. pool: objPool,
  54211. recycle: recycle,
  54212. size: size,
  54213. use: use
  54214. };
  54215. };
  54216. function clearObject (obj) {
  54217. var key;
  54218. if (!(obj.constructor === Object)) { return; }
  54219. for (key in obj) { obj[key] = undefined; }
  54220. }
  54221. module.exports.clearObject = clearObject;
  54222. },{}],176:[function(_dereq_,module,exports){
  54223. /**
  54224. * String split with cached result.
  54225. */
  54226. module.exports.split = (function () {
  54227. var splitCache = {};
  54228. return function (str, delimiter) {
  54229. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  54230. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  54231. splitCache[delimiter][str] = str.split(delimiter);
  54232. return splitCache[delimiter][str];
  54233. };
  54234. })();
  54235. },{}],177:[function(_dereq_,module,exports){
  54236. /* global Image, XMLHttpRequest */
  54237. var debug = _dereq_('./debug');
  54238. var warn = debug('utils:src-loader:warn');
  54239. /**
  54240. * Validate a texture, either as a selector or as a URL.
  54241. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  54242. * callback.
  54243. *
  54244. * `src` will be passed into the callback
  54245. *
  54246. * @params {string|Element} src - URL or media element.
  54247. * @params {function} isImageCb - callback if texture is an image.
  54248. * @params {function} isVideoCb - callback if texture is a video.
  54249. */
  54250. function validateSrc (src, isImageCb, isVideoCb) {
  54251. checkIsImage(src, function isAnImageUrl (isImage) {
  54252. if (isImage) {
  54253. isImageCb(src);
  54254. return;
  54255. }
  54256. isVideoCb(src);
  54257. });
  54258. }
  54259. /**
  54260. * Validates six images as a cubemap, either as selector or comma-separated
  54261. * URLs.
  54262. *
  54263. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  54264. must be wrapped by `url()`.
  54265. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  54266. must be wrapped by `url()`.
  54267. */
  54268. function validateCubemapSrc (src, cb) {
  54269. var aCubemap;
  54270. var cubemapSrcRegex = '';
  54271. var i;
  54272. var urls;
  54273. var validatedUrls = [];
  54274. for (i = 0; i < 5; i++) {
  54275. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  54276. }
  54277. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  54278. urls = src.match(new RegExp(cubemapSrcRegex));
  54279. // `src` is a comma-separated list of URLs.
  54280. // In this case, re-use validateSrc for each side of the cube.
  54281. function isImageCb (url) {
  54282. validatedUrls.push(url);
  54283. if (validatedUrls.length === 6) {
  54284. cb(validatedUrls);
  54285. }
  54286. }
  54287. if (urls) {
  54288. for (i = 1; i < 7; i++) {
  54289. validateSrc(parseUrl(urls[i]), isImageCb);
  54290. }
  54291. return;
  54292. }
  54293. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  54294. aCubemap = validateAndGetQuerySelector(src);
  54295. if (!aCubemap) { return; }
  54296. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  54297. return cb(aCubemap.srcs);
  54298. }
  54299. // Else if aCubeMap is not a <a-cubemap>.
  54300. warn('Selector "%s" does not point to <a-cubemap>', src);
  54301. }
  54302. /**
  54303. * Parses src from `url(src)`.
  54304. * @param {string} src - String to parse.
  54305. * @return {string} The parsed src, if parseable.
  54306. */
  54307. function parseUrl (src) {
  54308. var parsedSrc = src.match(/\url\((.+)\)/);
  54309. if (!parsedSrc) { return; }
  54310. return parsedSrc[1];
  54311. }
  54312. /**
  54313. * Call back whether `src` is an image.
  54314. *
  54315. * @param {string|Element} src - URL or element that will be tested.
  54316. * @param {function} onResult - Callback with whether `src` is an image.
  54317. */
  54318. function checkIsImage (src, onResult) {
  54319. var request;
  54320. if (src.tagName) {
  54321. onResult(src.tagName === 'IMG');
  54322. return;
  54323. }
  54324. request = new XMLHttpRequest();
  54325. // Try to send HEAD request to check if image first.
  54326. request.open('HEAD', src);
  54327. request.addEventListener('load', function (event) {
  54328. var contentType;
  54329. if (request.status >= 200 && request.status < 300) {
  54330. contentType = request.getResponseHeader('Content-Type');
  54331. if (contentType == null) {
  54332. checkIsImageFallback(src, onResult);
  54333. } else {
  54334. if (contentType.startsWith('image')) {
  54335. onResult(true);
  54336. } else {
  54337. onResult(false);
  54338. }
  54339. }
  54340. } else {
  54341. checkIsImageFallback(src, onResult);
  54342. }
  54343. request.abort();
  54344. });
  54345. request.send();
  54346. }
  54347. function checkIsImageFallback (src, onResult) {
  54348. var tester = new Image();
  54349. tester.addEventListener('load', onLoad);
  54350. function onLoad () { onResult(true); }
  54351. tester.addEventListener('error', onError);
  54352. function onError () { onResult(false); }
  54353. tester.src = src;
  54354. }
  54355. /**
  54356. * Query and validate a query selector,
  54357. *
  54358. * @param {string} selector - DOM selector.
  54359. * @return {object|null|undefined} Selected DOM element if exists.
  54360. null if query yields no results.
  54361. undefined if `selector` is not a valid selector.
  54362. */
  54363. function validateAndGetQuerySelector (selector) {
  54364. try {
  54365. var el = document.querySelector(selector);
  54366. if (!el) {
  54367. warn('No element was found matching the selector: "%s"', selector);
  54368. }
  54369. return el;
  54370. } catch (e) { // Capture exception if it's not a valid selector.
  54371. warn('"%s" is not a valid selector', selector);
  54372. return undefined;
  54373. }
  54374. }
  54375. module.exports = {
  54376. parseUrl: parseUrl,
  54377. validateSrc: validateSrc,
  54378. validateCubemapSrc: validateCubemapSrc
  54379. };
  54380. },{"./debug":169}],178:[function(_dereq_,module,exports){
  54381. /* Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5"). */
  54382. var styleParser = _dereq_('style-attr');
  54383. /**
  54384. * Deserializes style-like string into an object of properties.
  54385. *
  54386. * @param {string} value - HTML attribute value.
  54387. * @returns {object} Property data.
  54388. */
  54389. module.exports.parse = function (value) {
  54390. var parsedData;
  54391. if (typeof value !== 'string') { return value; }
  54392. parsedData = styleParser.parse(value);
  54393. // The style parser returns an object { "" : "test"} when fed a string
  54394. if (parsedData['']) { return value; }
  54395. return transformKeysToCamelCase(parsedData);
  54396. };
  54397. /**
  54398. * Serialize an object of properties into a style-like string.
  54399. *
  54400. * @param {object} data - Property data.
  54401. * @returns {string}
  54402. */
  54403. module.exports.stringify = function (data) {
  54404. if (typeof data === 'string') { return data; }
  54405. return styleParser.stringify(data);
  54406. };
  54407. /**
  54408. * Converts string from hyphen to camelCase.
  54409. *
  54410. * @param {string} str - String to camelCase.
  54411. * @return {string} CamelCased string.
  54412. */
  54413. function toCamelCase (str) {
  54414. return str.replace(/-([a-z])/g, camelCase);
  54415. function camelCase (g) { return g[1].toUpperCase(); }
  54416. }
  54417. module.exports.toCamelCase = toCamelCase;
  54418. /**
  54419. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  54420. * `maxValue`).
  54421. *
  54422. * @param {object} obj - The object to camelCase keys.
  54423. * @return {object} The object with keys camelCased.
  54424. */
  54425. function transformKeysToCamelCase (obj) {
  54426. var keys = Object.keys(obj);
  54427. var camelCaseObj = {};
  54428. keys.forEach(function (key) {
  54429. var camelCaseKey = toCamelCase(key);
  54430. camelCaseObj[camelCaseKey] = obj[key];
  54431. });
  54432. return camelCaseObj;
  54433. }
  54434. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  54435. },{"style-attr":35}],179:[function(_dereq_,module,exports){
  54436. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  54437. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  54438. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  54439. /**
  54440. * Called on controller component `.play` handlers.
  54441. * Check if controller matches parameters and inject tracked-controls component.
  54442. * Handle event listeners.
  54443. * Generate controllerconnected or controllerdisconnected events.
  54444. *
  54445. * @param {object} component - Tracked controls component.
  54446. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  54447. * @param {object} queryObject - Map of values to match.
  54448. */
  54449. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  54450. var el = component.el;
  54451. var isPresent = isControllerPresent(component, idPrefix, queryObject);
  54452. // If component was previously paused and now playing, re-add event listeners.
  54453. // Handle the event listeners here since this helper method is control of calling
  54454. // `.addEventListeners` and `.removeEventListeners`.
  54455. if (component.controllerPresent && !component.controllerEventsActive) {
  54456. component.addEventListeners();
  54457. }
  54458. // Nothing changed, no need to do anything.
  54459. if (isPresent === component.controllerPresent) { return isPresent; }
  54460. component.controllerPresent = isPresent;
  54461. // Update controller presence.
  54462. if (isPresent) {
  54463. component.injectTrackedControls();
  54464. component.addEventListeners();
  54465. el.emit('controllerconnected', {name: component.name, component: component});
  54466. } else {
  54467. component.removeEventListeners();
  54468. el.emit('controllerdisconnected', {name: component.name, component: component});
  54469. }
  54470. };
  54471. /**
  54472. * Enumerate controller (that have pose) and check if they match parameters.
  54473. *
  54474. * @param {object} component - Tracked controls component.
  54475. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  54476. * @param {object} queryObject - Map of values to match.
  54477. */
  54478. function isControllerPresent (component, idPrefix, queryObject) {
  54479. var gamepads;
  54480. var sceneEl = component.el.sceneEl;
  54481. var trackedControlsSystem;
  54482. var filterControllerIndex = queryObject.index || 0;
  54483. if (!idPrefix) { return false; }
  54484. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls'];
  54485. if (!trackedControlsSystem) { return false; }
  54486. gamepads = trackedControlsSystem.controllers;
  54487. if (!gamepads.length) { return false; }
  54488. return !!findMatchingController(gamepads, null, idPrefix, queryObject.hand,
  54489. filterControllerIndex);
  54490. }
  54491. module.exports.isControllerPresent = isControllerPresent;
  54492. /**
  54493. * Walk through the given controllers to find any where the device ID equals
  54494. * filterIdExact, or startsWith filterIdPrefix.
  54495. * A controller where this considered true is considered a 'match'.
  54496. *
  54497. * For each matching controller:
  54498. * If filterHand is set, and the controller:
  54499. * is handed, we further verify that controller.hand equals filterHand.
  54500. * is unhanded (controller.hand is ''), we skip until we have found a
  54501. * number of matching controllers that equals filterControllerIndex
  54502. * If filterHand is not set, we skip until we have found the nth matching
  54503. * controller, where n equals filterControllerIndex
  54504. *
  54505. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  54506. * one or both of: [filterHand, filterControllerIndex]
  54507. *
  54508. * @param {object} controllers - Array of gamepads to search
  54509. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  54510. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  54511. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  54512. * @param {object} filterControllerIndex - Find the nth matching controller,
  54513. * where n equals filterControllerIndex. defaults to 0.
  54514. */
  54515. function findMatchingController (controllers, filterIdExact, filterIdPrefix, filterHand,
  54516. filterControllerIndex) {
  54517. var controller;
  54518. var i;
  54519. var matchingControllerOccurence = 0;
  54520. var targetControllerMatch = filterControllerIndex || 0;
  54521. for (i = 0; i < controllers.length; i++) {
  54522. controller = controllers[i];
  54523. // Determine if the controller ID matches our criteria.
  54524. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  54525. continue;
  54526. }
  54527. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  54528. // If the hand filter and controller handedness are defined we compare them.
  54529. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  54530. // If we have detected an unhanded controller and the component was asking
  54531. // for a particular hand, we need to treat the controllers in the array as
  54532. // pairs of controllers. This effectively means that we need to skip
  54533. // NUM_HANDS matches for each controller number, instead of 1.
  54534. if (filterHand && !controller.hand) {
  54535. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  54536. }
  54537. // We are looking for the nth occurence of a matching controller
  54538. // (n equals targetControllerMatch).
  54539. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  54540. ++matchingControllerOccurence;
  54541. }
  54542. return undefined;
  54543. }
  54544. module.exports.findMatchingController = findMatchingController;
  54545. /**
  54546. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  54547. *
  54548. * @param {object} component - Controller component in use.
  54549. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  54550. * @param {object} evt - Event to process.
  54551. */
  54552. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  54553. var axes;
  54554. var buttonType;
  54555. var changed;
  54556. var detail;
  54557. var j;
  54558. for (buttonType in axesMapping) {
  54559. axes = axesMapping[buttonType];
  54560. changed = false;
  54561. for (j = 0; j < axes.length; j++) {
  54562. if (evt.detail.changed[axes[j]]) { changed = true; }
  54563. }
  54564. if (!changed) { continue; }
  54565. // Axis has changed. Emit the specific moved event with axis values in detail.
  54566. detail = {};
  54567. for (j = 0; j < axes.length; j++) {
  54568. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  54569. }
  54570. component.el.emit(buttonType + 'moved', detail);
  54571. }
  54572. };
  54573. /**
  54574. * Handle a button event and reemits the events.
  54575. *
  54576. * @param {string} id - id of the button.
  54577. * @param {string} evtName - name of the reemitted event
  54578. * @param {object} component - reference to the component
  54579. * @param {string} hand - handedness of the controller: left or right.
  54580. */
  54581. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  54582. var mapping = hand ? component.mapping[hand] : component.mapping;
  54583. var buttonName = mapping.buttons[id];
  54584. component.el.emit(buttonName + evtName);
  54585. if (component.updateModel) {
  54586. component.updateModel(buttonName, evtName);
  54587. }
  54588. };
  54589. },{"../constants":94}],180:[function(_dereq_,module,exports){
  54590. window.glStats = function () {
  54591. var _rS = null;
  54592. var _totalDrawArraysCalls = 0,
  54593. _totalDrawElementsCalls = 0,
  54594. _totalUseProgramCalls = 0,
  54595. _totalFaces = 0,
  54596. _totalVertices = 0,
  54597. _totalPoints = 0,
  54598. _totalBindTexures = 0;
  54599. function _h ( f, c ) {
  54600. return function () {
  54601. c.apply( this, arguments );
  54602. f.apply( this, arguments );
  54603. };
  54604. }
  54605. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  54606. _totalDrawArraysCalls++;
  54607. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  54608. else _totalVertices += arguments[ 2 ];
  54609. } );
  54610. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  54611. _totalDrawElementsCalls++;
  54612. _totalFaces += arguments[ 1 ] / 3;
  54613. _totalVertices += arguments[ 1 ];
  54614. } );
  54615. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  54616. _totalUseProgramCalls++;
  54617. } );
  54618. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  54619. _totalBindTexures++;
  54620. } );
  54621. var _values = {
  54622. allcalls: {
  54623. over: 3000,
  54624. caption: 'Calls (hook)'
  54625. },
  54626. drawelements: {
  54627. caption: 'drawElements (hook)'
  54628. },
  54629. drawarrays: {
  54630. caption: 'drawArrays (hook)'
  54631. }
  54632. };
  54633. var _groups = [ {
  54634. caption: 'WebGL',
  54635. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  54636. } ];
  54637. var _fractions = [ {
  54638. base: 'allcalls',
  54639. steps: [ 'drawelements', 'drawarrays' ]
  54640. } ];
  54641. function _update () {
  54642. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  54643. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  54644. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  54645. _rS( 'bindTexture' ).set( _totalBindTexures );
  54646. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  54647. _rS( 'glfaces' ).set( _totalFaces );
  54648. _rS( 'glvertices' ).set( _totalVertices );
  54649. _rS( 'glpoints' ).set( _totalPoints );
  54650. }
  54651. function _start () {
  54652. _totalDrawArraysCalls = 0;
  54653. _totalDrawElementsCalls = 0;
  54654. _totalUseProgramCalls = 0;
  54655. _totalFaces = 0;
  54656. _totalVertices = 0;
  54657. _totalPoints = 0;
  54658. _totalBindTexures = 0;
  54659. }
  54660. function _end () {}
  54661. function _attach ( r ) {
  54662. _rS = r;
  54663. }
  54664. return {
  54665. update: _update,
  54666. start: _start,
  54667. end: _end,
  54668. attach: _attach,
  54669. values: _values,
  54670. groups: _groups,
  54671. fractions: _fractions
  54672. };
  54673. };
  54674. window.threeStats = function ( renderer ) {
  54675. var _rS = null;
  54676. var _values = {
  54677. 'renderer.info.memory.geometries': {
  54678. caption: 'Geometries'
  54679. },
  54680. 'renderer.info.memory.textures': {
  54681. caption: 'Textures'
  54682. },
  54683. 'renderer.info.programs': {
  54684. caption: 'Programs'
  54685. },
  54686. 'renderer.info.render.calls': {
  54687. caption: 'Calls'
  54688. },
  54689. 'renderer.info.render.faces': {
  54690. caption: 'Faces',
  54691. over: 1000
  54692. },
  54693. 'renderer.info.render.points': {
  54694. caption: 'Points'
  54695. },
  54696. 'renderer.info.render.vertices': {
  54697. caption: 'Vertices'
  54698. }
  54699. };
  54700. var _groups = [ {
  54701. caption: 'Three.js - Memory',
  54702. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  54703. }, {
  54704. caption: 'Three.js - Render',
  54705. values: [ 'renderer.info.render.calls', 'renderer.info.render.faces', 'renderer.info.render.points', 'renderer.info.render.vertices' ]
  54706. } ];
  54707. var _fractions = [];
  54708. function _update () {
  54709. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  54710. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  54711. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  54712. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  54713. _rS( 'renderer.info.render.faces' ).set( renderer.info.render.faces );
  54714. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  54715. _rS( 'renderer.info.render.vertices' ).set( renderer.info.render.vertices );
  54716. }
  54717. function _start () {}
  54718. function _end () {}
  54719. function _attach ( r ) {
  54720. _rS = r;
  54721. }
  54722. return {
  54723. update: _update,
  54724. start: _start,
  54725. end: _end,
  54726. attach: _attach,
  54727. values: _values,
  54728. groups: _groups,
  54729. fractions: _fractions
  54730. };
  54731. };
  54732. /*
  54733. * From https://github.com/paulirish/memory-stats.js
  54734. */
  54735. window.BrowserStats = function () {
  54736. var _rS = null;
  54737. var _usedJSHeapSize = 0,
  54738. _totalJSHeapSize = 0;
  54739. if ( window.performance && !performance.memory ) {
  54740. performance.memory = {
  54741. usedJSHeapSize: 0,
  54742. totalJSHeapSize: 0
  54743. };
  54744. }
  54745. if ( performance.memory.totalJSHeapSize === 0 ) {
  54746. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  54747. }
  54748. var _values = {
  54749. memory: {
  54750. caption: 'Used Memory',
  54751. average: true,
  54752. avgMs: 1000,
  54753. over: 22
  54754. },
  54755. total: {
  54756. caption: 'Total Memory'
  54757. }
  54758. };
  54759. var _groups = [ {
  54760. caption: 'Browser',
  54761. values: [ 'memory', 'total' ]
  54762. } ];
  54763. var _fractions = [ {
  54764. base: 'total',
  54765. steps: [ 'memory' ]
  54766. } ];
  54767. var log1024 = Math.log( 1024 );
  54768. function _size ( v ) {
  54769. var precision = 100; //Math.pow(10, 2);
  54770. var i = Math.floor( Math.log( v ) / log1024 );
  54771. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  54772. }
  54773. function _update () {
  54774. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  54775. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  54776. _rS( 'memory' ).set( _usedJSHeapSize );
  54777. _rS( 'total' ).set( _totalJSHeapSize );
  54778. }
  54779. function _start () {
  54780. _usedJSHeapSize = 0;
  54781. }
  54782. function _end () {}
  54783. function _attach ( r ) {
  54784. _rS = r;
  54785. }
  54786. return {
  54787. update: _update,
  54788. start: _start,
  54789. end: _end,
  54790. attach: _attach,
  54791. values: _values,
  54792. groups: _groups,
  54793. fractions: _fractions
  54794. };
  54795. };
  54796. if (typeof module === 'object') {
  54797. module.exports = {
  54798. glStats: window.glStats,
  54799. threeStats: window.threeStats,
  54800. BrowserStats: window.BrowserStats
  54801. };
  54802. }
  54803. },{}],181:[function(_dereq_,module,exports){
  54804. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  54805. 'use strict';
  54806. ( function () {
  54807. if ( 'performance' in window == false ) {
  54808. window.performance = {};
  54809. }
  54810. var performance = window.performance;
  54811. if ( 'now' in performance == false ) {
  54812. var nowOffset = Date.now();
  54813. if ( performance.timing && performance.timing.navigationStart ) {
  54814. nowOffset = performance.timing.navigationStart;
  54815. }
  54816. performance.now = function now () {
  54817. return Date.now() - nowOffset;
  54818. };
  54819. }
  54820. if( !performance.mark ) {
  54821. performance.mark = function(){}
  54822. }
  54823. if( !performance.measure ) {
  54824. performance.measure = function(){}
  54825. }
  54826. } )();
  54827. window.rStats = function rStats ( settings ) {
  54828. function iterateKeys ( array, callback ) {
  54829. var keys = Object.keys( array );
  54830. for ( var j = 0, l = keys.length; j < l; j++ ) {
  54831. callback( keys[ j ] );
  54832. }
  54833. }
  54834. function importCSS ( url ) {
  54835. var element = document.createElement( 'link' );
  54836. element.href = url;
  54837. element.rel = 'stylesheet';
  54838. element.type = 'text/css';
  54839. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  54840. }
  54841. var _settings = settings || {};
  54842. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  54843. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  54844. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  54845. var _css = _settings.css || [ _cssFont, _cssRStats ];
  54846. _css.forEach(function (uri) {
  54847. importCSS( uri );
  54848. });
  54849. if ( !_settings.values ) _settings.values = {};
  54850. var _base, _div, _elHeight = 10, _elWidth = 200;
  54851. var _perfCounters = {};
  54852. function Graph ( _dom, _id, _defArg ) {
  54853. var _def = _defArg || {};
  54854. var _canvas = document.createElement( 'canvas' ),
  54855. _ctx = _canvas.getContext( '2d' ),
  54856. _max = 0,
  54857. _current = 0;
  54858. var c = _def.color ? _def.color : '#666666';
  54859. var _dotCanvas = document.createElement( 'canvas' ),
  54860. _dotCtx = _dotCanvas.getContext( '2d' );
  54861. _dotCanvas.width = 1;
  54862. _dotCanvas.height = 2 * _elHeight;
  54863. _dotCtx.fillStyle = '#444444';
  54864. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  54865. _dotCtx.fillStyle = c;
  54866. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  54867. _dotCtx.fillStyle = '#ffffff';
  54868. _dotCtx.globalAlpha = 0.5;
  54869. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  54870. _dotCtx.globalAlpha = 1;
  54871. var _alarmCanvas = document.createElement( 'canvas' ),
  54872. _alarmCtx = _alarmCanvas.getContext( '2d' );
  54873. _alarmCanvas.width = 1;
  54874. _alarmCanvas.height = 2 * _elHeight;
  54875. _alarmCtx.fillStyle = '#444444';
  54876. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  54877. _alarmCtx.fillStyle = '#b70000';
  54878. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  54879. _alarmCtx.globalAlpha = 0.5;
  54880. _alarmCtx.fillStyle = '#ffffff';
  54881. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  54882. _alarmCtx.globalAlpha = 1;
  54883. function _init () {
  54884. _canvas.width = _elWidth;
  54885. _canvas.height = _elHeight;
  54886. _canvas.style.width = _canvas.width + 'px';
  54887. _canvas.style.height = _canvas.height + 'px';
  54888. _canvas.className = 'rs-canvas';
  54889. _dom.appendChild( _canvas );
  54890. _ctx.fillStyle = '#444444';
  54891. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  54892. }
  54893. function _draw ( v, alarm ) {
  54894. _current += ( v - _current ) * 0.1;
  54895. _max *= 0.99;
  54896. if ( _current > _max ) _max = _current;
  54897. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  54898. if ( alarm ) {
  54899. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  54900. } else {
  54901. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  54902. }
  54903. }
  54904. _init();
  54905. return {
  54906. draw: _draw
  54907. };
  54908. }
  54909. function StackGraph ( _dom, _num ) {
  54910. var _canvas = document.createElement( 'canvas' ),
  54911. _ctx = _canvas.getContext( '2d' );
  54912. function _init () {
  54913. _canvas.width = _elWidth;
  54914. _canvas.height = _elHeight * _num;
  54915. _canvas.style.width = _canvas.width + 'px';
  54916. _canvas.style.height = _canvas.height + 'px';
  54917. _canvas.className = 'rs-canvas';
  54918. _dom.appendChild( _canvas );
  54919. _ctx.fillStyle = '#444444';
  54920. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  54921. }
  54922. function _draw ( v ) {
  54923. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  54924. var th = 0;
  54925. iterateKeys( v, function ( j ) {
  54926. var h = v[ j ] * _canvas.height;
  54927. _ctx.fillStyle = _colours[ j ];
  54928. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  54929. th += h;
  54930. } );
  54931. }
  54932. _init();
  54933. return {
  54934. draw: _draw
  54935. };
  54936. }
  54937. function PerfCounter ( id, group ) {
  54938. var _id = id,
  54939. _time,
  54940. _value = 0,
  54941. _total = 0,
  54942. _averageValue = 0,
  54943. _accumValue = 0,
  54944. _accumStart = performance.now(),
  54945. _accumSamples = 0,
  54946. _dom = document.createElement( 'div' ),
  54947. _spanId = document.createElement( 'span' ),
  54948. _spanValue = document.createElement( 'div' ),
  54949. _spanValueText = document.createTextNode( '' ),
  54950. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  54951. _graph = new Graph( _dom, _id, _def ),
  54952. _started = false;
  54953. _spanId.className = 'rs-counter-id';
  54954. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  54955. _spanValue.className = 'rs-counter-value';
  54956. _spanValue.appendChild( _spanValueText );
  54957. _dom.appendChild( _spanId );
  54958. _dom.appendChild( _spanValue );
  54959. if ( group ) group.div.appendChild( _dom );
  54960. else _div.appendChild( _dom );
  54961. _time = performance.now();
  54962. function _average ( v ) {
  54963. if ( _def && _def.average ) {
  54964. _accumValue += v;
  54965. _accumSamples++;
  54966. var t = performance.now();
  54967. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  54968. _averageValue = _accumValue / _accumSamples;
  54969. _accumValue = 0;
  54970. _accumStart = t;
  54971. _accumSamples = 0;
  54972. }
  54973. }
  54974. }
  54975. function _start () {
  54976. _time = performance.now();
  54977. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  54978. _started = true;
  54979. }
  54980. function _end () {
  54981. _value = performance.now() - _time;
  54982. if( _settings.userTimingAPI ) {
  54983. performance.mark( _id + '-end' );
  54984. if( _started ) {
  54985. performance.measure( _id, _id + '-start', _id + '-end' );
  54986. }
  54987. }
  54988. _average( _value );
  54989. }
  54990. function _tick () {
  54991. _end();
  54992. _start();
  54993. }
  54994. function _draw () {
  54995. var v = ( _def && _def.average ) ? _averageValue : _value;
  54996. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  54997. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  54998. _graph.draw( _value, a );
  54999. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  55000. }
  55001. function _frame () {
  55002. var t = performance.now();
  55003. var e = t - _time;
  55004. _total++;
  55005. if ( e > 1000 ) {
  55006. if ( _def && _def.interpolate === false ) {
  55007. _value = _total;
  55008. } else {
  55009. _value = _total * 1000 / e;
  55010. }
  55011. _total = 0;
  55012. _time = t;
  55013. _average( _value );
  55014. }
  55015. }
  55016. function _set ( v ) {
  55017. _value = v;
  55018. _average( _value );
  55019. }
  55020. return {
  55021. set: _set,
  55022. start: _start,
  55023. tick: _tick,
  55024. end: _end,
  55025. frame: _frame,
  55026. value: function () {
  55027. return _value;
  55028. },
  55029. draw: _draw
  55030. };
  55031. }
  55032. function sample () {
  55033. var _value = 0;
  55034. function _set ( v ) {
  55035. _value = v;
  55036. }
  55037. return {
  55038. set: _set,
  55039. value: function () {
  55040. return _value;
  55041. }
  55042. };
  55043. }
  55044. function _perf ( idArg ) {
  55045. var id = idArg.toLowerCase();
  55046. if ( id === undefined ) id = 'default';
  55047. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  55048. var group = null;
  55049. if ( _settings && _settings.groups ) {
  55050. iterateKeys( _settings.groups, function ( j ) {
  55051. var g = _settings.groups[ parseInt( j, 10 ) ];
  55052. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  55053. group = g;
  55054. }
  55055. } );
  55056. }
  55057. var p = new PerfCounter( id, group );
  55058. _perfCounters[ id ] = p;
  55059. return p;
  55060. }
  55061. function _init () {
  55062. if ( _settings.plugins ) {
  55063. if ( !_settings.values ) _settings.values = {};
  55064. if ( !_settings.groups ) _settings.groups = [];
  55065. if ( !_settings.fractions ) _settings.fractions = [];
  55066. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  55067. _settings.plugins[ j ].attach( _perf );
  55068. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  55069. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  55070. } );
  55071. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  55072. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  55073. }
  55074. } else {
  55075. _settings.plugins = {};
  55076. }
  55077. _base = document.createElement( 'div' );
  55078. _base.className = 'rs-base';
  55079. _div = document.createElement( 'div' );
  55080. _div.className = 'rs-container';
  55081. _div.style.height = 'auto';
  55082. _base.appendChild( _div );
  55083. document.body.appendChild( _base );
  55084. if ( !_settings ) return;
  55085. if ( _settings.groups ) {
  55086. iterateKeys( _settings.groups, function ( j ) {
  55087. var g = _settings.groups[ parseInt( j, 10 ) ];
  55088. var div = document.createElement( 'div' );
  55089. div.className = 'rs-group';
  55090. g.div = div;
  55091. var h1 = document.createElement( 'h1' );
  55092. h1.textContent = g.caption;
  55093. h1.addEventListener( 'click', function ( e ) {
  55094. this.classList.toggle( 'hidden' );
  55095. e.preventDefault();
  55096. }.bind( div ) );
  55097. _div.appendChild( h1 );
  55098. _div.appendChild( div );
  55099. } );
  55100. }
  55101. if ( _settings.fractions ) {
  55102. iterateKeys( _settings.fractions, function ( j ) {
  55103. var f = _settings.fractions[ parseInt( j, 10 ) ];
  55104. var div = document.createElement( 'div' );
  55105. div.className = 'rs-fraction';
  55106. var legend = document.createElement( 'div' );
  55107. legend.className = 'rs-legend';
  55108. var h = 0;
  55109. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  55110. var p = document.createElement( 'p' );
  55111. p.textContent = _settings.fractions[ j ].steps[ k ];
  55112. p.style.color = _colours[ h ];
  55113. legend.appendChild( p );
  55114. h++;
  55115. } );
  55116. div.appendChild( legend );
  55117. div.style.height = h * _elHeight + 'px';
  55118. f.div = div;
  55119. var graph = new StackGraph( div, h );
  55120. f.graph = graph;
  55121. _div.appendChild( div );
  55122. } );
  55123. }
  55124. }
  55125. function _update () {
  55126. iterateKeys( _settings.plugins, function ( j ) {
  55127. _settings.plugins[ j ].update();
  55128. } );
  55129. iterateKeys( _perfCounters, function ( j ) {
  55130. _perfCounters[ j ].draw();
  55131. } );
  55132. if ( _settings && _settings.fractions ) {
  55133. iterateKeys( _settings.fractions, function ( j ) {
  55134. var f = _settings.fractions[ parseInt( j, 10 ) ];
  55135. var v = [];
  55136. var base = _perfCounters[ f.base.toLowerCase() ];
  55137. if ( base ) {
  55138. base = base.value();
  55139. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  55140. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  55141. var val = _perfCounters[ s ];
  55142. if ( val ) {
  55143. v.push( val.value() / base );
  55144. }
  55145. } );
  55146. }
  55147. f.graph.draw( v );
  55148. } );
  55149. }
  55150. /*if( _height != _div.clientHeight ) {
  55151. _height = _div.clientHeight;
  55152. _base.style.height = _height + 2 * _elHeight + 'px';
  55153. console.log( _base.clientHeight );
  55154. }*/
  55155. }
  55156. _init();
  55157. return function ( id ) {
  55158. if ( id ) return _perf( id );
  55159. return {
  55160. element: _base,
  55161. update: _update
  55162. };
  55163. };
  55164. }
  55165. if (typeof module === 'object') {
  55166. module.exports = window.rStats;
  55167. }
  55168. },{}],182:[function(_dereq_,module,exports){
  55169. /*
  55170. * Copyright 2015 Google Inc. All Rights Reserved.
  55171. * Licensed under the Apache License, Version 2.0 (the "License");
  55172. * you may not use this file except in compliance with the License.
  55173. * You may obtain a copy of the License at
  55174. *
  55175. * http://www.apache.org/licenses/LICENSE-2.0
  55176. *
  55177. * Unless required by applicable law or agreed to in writing, software
  55178. * distributed under the License is distributed on an "AS IS" BASIS,
  55179. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  55180. * See the License for the specific language governing permissions and
  55181. * limitations under the License.
  55182. */
  55183. var Util = {};
  55184. Util.base64 = function(mimeType, base64) {
  55185. return 'data:' + mimeType + ';base64,' + base64;
  55186. };
  55187. Util.isMobile = function() {
  55188. var check = false;
  55189. (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);
  55190. return check;
  55191. };
  55192. Util.isIOS = function() {
  55193. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  55194. };
  55195. Util.isIFrame = function() {
  55196. try {
  55197. return window.self !== window.top;
  55198. } catch (e) {
  55199. return true;
  55200. }
  55201. };
  55202. Util.appendQueryParameter = function(url, key, value) {
  55203. // Determine delimiter based on if the URL already GET parameters in it.
  55204. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  55205. url += delimiter + key + '=' + value;
  55206. return url;
  55207. };
  55208. // From http://goo.gl/4WX3tg
  55209. Util.getQueryParameter = function(name) {
  55210. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  55211. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  55212. results = regex.exec(location.search);
  55213. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  55214. };
  55215. Util.isLandscapeMode = function() {
  55216. return (window.orientation == 90 || window.orientation == -90);
  55217. };
  55218. module.exports = Util;
  55219. },{}],183:[function(_dereq_,module,exports){
  55220. /*
  55221. * Copyright 2015 Google Inc. All Rights Reserved.
  55222. * Licensed under the Apache License, Version 2.0 (the "License");
  55223. * you may not use this file except in compliance with the License.
  55224. * You may obtain a copy of the License at
  55225. *
  55226. * http://www.apache.org/licenses/LICENSE-2.0
  55227. *
  55228. * Unless required by applicable law or agreed to in writing, software
  55229. * distributed under the License is distributed on an "AS IS" BASIS,
  55230. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  55231. * See the License for the specific language governing permissions and
  55232. * limitations under the License.
  55233. */
  55234. var Util = _dereq_('./util.js');
  55235. /**
  55236. * Android and iOS compatible wakelock implementation.
  55237. *
  55238. * Refactored thanks to dkovalev@.
  55239. */
  55240. function AndroidWakeLock() {
  55241. var video = document.createElement('video');
  55242. video.addEventListener('ended', function() {
  55243. video.play();
  55244. });
  55245. this.request = function() {
  55246. if (video.paused) {
  55247. // Base64 version of videos_src/no-sleep-60s.webm.
  55248. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  55249. video.play();
  55250. }
  55251. };
  55252. this.release = function() {
  55253. video.pause();
  55254. video.src = '';
  55255. };
  55256. }
  55257. function iOSWakeLock() {
  55258. var timer = null;
  55259. this.request = function() {
  55260. if (!timer) {
  55261. timer = setInterval(function() {
  55262. window.location.href = '/';
  55263. setTimeout(window.stop, 0);
  55264. }, 15000);
  55265. }
  55266. }
  55267. this.release = function() {
  55268. if (timer) {
  55269. clearInterval(timer);
  55270. timer = null;
  55271. }
  55272. }
  55273. }
  55274. function getWakeLock() {
  55275. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  55276. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  55277. return iOSWakeLock;
  55278. } else {
  55279. return AndroidWakeLock;
  55280. }
  55281. }
  55282. module.exports = getWakeLock();
  55283. },{"./util.js":182}]},{},[149])(149)
  55284. });
  55285. //# sourceMappingURL=aframe-master.js.map